forked from udacity/frontend-nanodegree-arcade-game
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
120 lines (104 loc) · 2.73 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
const playerFrame = {
borderX: {
start: 0,
end: 400
},
borderY: {
start: 0,
end: 400
},
};
const enemyFrame = {
borderX: {
start: -100,
end: 505
}
};
class Player {
constructor(x, y) {
this.x = x;
this.y = y;
this.sprite = 'images/char-boy.png';
this.stepX = 100;
this.stepY = 85;
}
update() {
this.checkWin();
}
render() {
ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
}
handleInput(move) {
switch(move) {
case 'left':
this.x -= this.stepX;
if (this.x < playerFrame.borderX.start) this.x = playerFrame.borderX.start;
break;
case 'right':
this.x += this.stepX;
if (this.x > playerFrame.borderX.end) this.x = playerFrame.borderX.end;
break;
case 'up':
this.y -= this.stepY;
break;
case 'down':
this.y += this.stepY;
if (this.y > playerFrame.borderY.end) this.y = playerFrame.borderY.end;
break;
default:
break;
}
}
checkWin() {
if (this.y < playerFrame.borderY.start) setTimeout(() => {
this.resetStart();
alert('You win!');
}, 10);
}
resetStart(){
this.x = (this.stepX * 2);
this.y = playerFrame.borderY.end;
}
}
class Enemy {
constructor(x, y, player) {
this.x = x;
this.y = y;
this.player = player;
this.sprite = 'images/enemy-bug.png';
this.speed = (Math.random() * 200) + 200;
this.gap = 50;
}
update(dt) {
this.x += this.speed * dt;
if (this.x > enemyFrame.borderX.end) this.x = enemyFrame.borderX.start;
this.checkCollisions();
}
render() {
ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
}
checkCollisions() {
if (
this.x >= this.player.x - this.gap &&
this.x <= this.player.x + this.gap &&
this.y >= this.player.y - this.gap &&
this.y <= this.player.y + this.gap
) setTimeout(() => {
this.player.resetStart();
alert('You lose!');
}, 10);
}
}
const player = new Player(200, 400);
const allEnemies = [];
const EnemySetY = [60, 145, 225];
EnemySetY.forEach(point => allEnemies.push(new Enemy((Math.random()*200), point, player)));
document.addEventListener('keyup', function(e) {
const allowedKeys = {
37: 'left',
38: 'up',
39: 'right',
40: 'down'
};
player.handleInput(allowedKeys[e.keyCode]);
});