Frog-Leap-Game

Форк
0
159 строк · 5.7 Кб
1
import { lilyPads } from './gameDraw.js';
2
import { createSplash } from './Splash.js';
3

4
export class Frog {
5
    constructor(canvas, ctx, splashes, setGameRunning, resetScore) {
6
        this.canvas = canvas;
7
        this.ctx = ctx;
8
        this.width = 40;
9
        this.height = 50;
10
        this.vx = 0;
11
        this.vy = 0;
12
        this.jumpPower = -15;
13
        this.gravity = 0.5;
14
        this.speed = 5;
15
        this.isJumping = false;
16
        this.jumpSound = new Audio('./assets/8-bit-jump.mp3'); // звук прыжка
17
        this.jumpSoundPlayed = false; // флаг звука прыжка
18
        this.isDrowned = false;
19
        this.splashes = splashes;
20
        this.drownSound = new Audio('./assets/8-bit-water-drop.wav'); // звук утопления
21
        this.drownSoundPlayed = false; // флаг звука утопления
22
        this.setGameRunning = setGameRunning; 
23
        this.resetScore = resetScore;
24
        this.resetPosition();            
25
    }
26

27
    resetPosition() {
28
        // Лягушка начинает с центральной кувшинки
29
        this.x = this.canvas.width / 2 - this.width / 2;
30
        this.y = this.canvas.height * 0.68 - this.height;
31
        this.isDrowned = false;
32
        this.vx = 0;
33
        this.vy = 0;
34
    }
35

36
    // Логика рисования лягушки
37
    draw() {        
38
        if (this.isDrowned) return; // Не рисовать лягушку, если она утонула
39

40
        const { ctx } = this;
41

42
        // Цвет, форма
43
        ctx.fillStyle = "green";
44
        ctx.fillRect(this.x, this.y, this.width, this.height);
45

46
        // Глаза
47
        ctx.fillStyle = "white";
48
        ctx.fillRect(this.x + 5, this.y + 5, 10, 10);
49
        ctx.fillRect(this.x + 25, this.y + 5, 10, 10);
50

51
        // Рот
52
        ctx.fillStyle = "red";
53
        ctx.fillRect(this.x + 10, this.y + 25, 20, 5);
54

55
        // Ноги
56
        ctx.fillStyle = "darkgreen";
57
        ctx.fillRect(this.x - 10, this.y + 30, 10, 20);
58
        ctx.fillRect(this.x + 40, this.y + 30, 10, 20); 
59
    }
60

61
    // Логика обновления позиции лягушки
62
    update() {        
63
        this.vy += this.gravity;
64
        this.x += this.vx;
65
        this.y += this.vy;
66

67
        // Проверка на столкновение с кувшинками
68
        let onLilyPad = false;
69

70
        for (const lilyPad of lilyPads) {
71
            if (
72
                this.y + this.height > lilyPad.y &&              
73
                this.x + this.width > lilyPad.x &&              
74
                this.x < lilyPad.x + lilyPad.width &&
75
                this.y + this.height <= lilyPad.y + lilyPad.height
76
            ) {
77
                // Если все условия выполнены, лягушка находится на кувшинке
78
                onLilyPad = true;
79
                this.y = lilyPad.y - this.height;              
80
                this.vy = 0;
81
                this.isJumping = false; // Лягушка больше не прыгает
82
                // Сбрасываем флаг, чтобы звук можно было проиграть снова
83
                this.jumpSoundPlayed = false;  
84
                this.drownSoundPlayed = false;
85
            }
86
        }
87

88
        // Если лягушка не на кувшинке и касается болота, то лягушка утонула
89
        if (!onLilyPad && this.y + this.height > this.canvas.height * 0.7) {
90
            this.drown();
91
        }
92

93
        // Лягушка не должна выходить за границы экрана
94
        if (this.x < 0) this.x = 0;
95
        if (this.x + this.width > this.canvas.width) {
96
            this.x = this.canvas.width - this.width;
97
        }
98
    }
99

100
    // Прыжок
101
    jump() {        
102
        if (!this.isJumping) {
103
            this.vy = this.jumpPower;
104
            this.isJumping = true;
105

106
            if (!this.jumpSoundPlayed) {  // Проверяем, был ли уже проигран звук
107
                this.jumpSound.currentTime = 0; // сбрасываем время воспроизведения звука
108
                this.jumpSound.play();
109
                this.jumpSoundPlayed = true;  // звук проигран
110
            }
111
        }
112
    }
113

114
    // Движения влево, вправо, стоп
115
    moveLeft() {
116
        this.vx = -this.speed;
117
    }
118

119
    moveRight() {
120
        this.vx = this.speed;
121
    }
122

123
    stop() {
124
        this.vx = 0;
125
    }
126

127
    // Логика утопления
128
    drown() {
129
        // Создаем всплеск воды
130
        createSplash(this.x + this.width / 2, this.y + this.height, this.splashes);
131

132
        this.isDrowned = true; // Лягушка утонула
133

134
        // Воспроизводим звук утопления
135
        if (!this.drownSoundPlayed) {  // проверяем, был ли уже проигран звук
136
            this.drownSound.currentTime = 0; // сбрасываем время воспроизведения звука
137
            this.drownSound.play();
138
            this.drownSoundPlayed = true;  // звук проигран
139
        }
140

141
        
142
        // Остановка игры с задержкой
143
        setTimeout(() => {            
144

145
            this.setGameRunning(false);
146

147
            // Сбрасываем счёт после утопления
148
            this.resetScore();
149
            
150

151
            // Показать текст "Game Over"
152
            document.getElementById("gameOverText").style.display = "block";
153

154
            // Обновить текст кнопки на "Play"
155
            document.getElementById("playButton").innerText = "Play";
156
            this.resetPosition();
157
        }, 1000);
158
    }
159
}
160

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.