-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
executable file
·103 lines (89 loc) · 1.63 KB
/
script.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
let canvas = document.querySelector('#canvas');
let ctx = canvas.getContext('2d');
let WIDTH = 400;
let HEIGHT = 300;
let player = {
x: 0,
y: 0,
w: 50,
h: 50,
color: 'white',
};
let W_DOWN = false;
let S_DOWN = false;
let A_DOWN = false;
let D_DOWN = false;
document.addEventListener('keydown', function(e) {
switch (e.key) {
case 'w':
W_DOWN = true;
break;
case 's':
S_DOWN = true;
break;
case 'a':
A_DOWN = true;
break;
case 'd':
D_DOWN = true;
break;
}
});
document.addEventListener('keyup', function(e) {
switch (e.key) {
case 'w':
W_DOWN = false;
break;
case 's':
S_DOWN = false;
break;
case 'a':
A_DOWN = false;
break;
case 'd':
D_DOWN = false;
break;
}
});
function paintScene() {
ctx.fillStyle = 'black';
ctx.fillRect(0, 0, WIDTH, HEIGHT);
}
function paintPlayer() {
ctx.fillStyle = 'white';
const {x, y, w, h} = player;
ctx.fillRect(x, y, w, h);
}
function respondToKeys() {
if (W_DOWN) {
player.y -= 10;
}
if (S_DOWN) {
player.y += 10;
}
if (A_DOWN) {
player.x -= 10;
}
if (D_DOWN) {
player.x += 10;
}
if (player.y > HEIGHT - player.h) {
player.y = HEIGHT - player.h;
}
if (player.x > WIDTH - player.w) {
player.x = WIDTH - player.w;
}
if (player.x < 0) {
player.x = 0;
}
if (player.y < 0) {
player.y = 0;
}
}
function loop() {
paintScene();
paintPlayer();
respondToKeys();
requestAnimationFrame(loop);
}
loop();