-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
88 lines (71 loc) · 1.66 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
var canvas = document.getElementById("mainCanvas");
var context = canvas.getContext("2d");
var keys = [],
width = 500,
height = 400,
speed = 4,
score = 0;
var player = {
x: 40,
y: 40,
width: 20,
height: 20
};
var cube = {
x: Math.random() * (width - 20),
y: Math.random() * (height - 20),
width: 20,
height: 20
};
window.addEventListener("keydown", function(e) {
keys[e.keyCode] = true;
}, false);
window.addEventListener("keyup", function(e) {
delete keys[e.keyCode];
}, false);
/*
KeyCodes
up - 38
down - 40
left - 37
right - 39
*/
function game() {
update();
render();
}
function update() {
if (keys[38]) player.y -= speed;
if (keys[40]) player.y += speed;
if (keys[37]) player.x -= speed;
if (keys[39]) player.x += speed;
if (player.x < 0) player.x = 0;
if (player.y < 0) player.y = 0;
if (player.x > width - player.width) player.x = width - player.width;
if (player.y > height - player.height) player.y = height - player.height;
if(collision(player, cube)) process();
}
function render() {
context.clearRect(0, 0, width, height);
context.fillStyle = "blue";
context.fillRect(player.x, player.y, player.width, player.height);
context.fillStyle = "red";
context.fillRect(cube.x, cube.y, cube.width, cube.height);
context.fillStyle = "black";
context.font = "bold 30px helvetica";
context.fillText(score, 10, 30);
}
function process(){
score++;
cube.x = Math.random() * (width - 20);
cube.y = Math.random() * (height - 20);
}
function collision(one, two) {
return !(one.x > two.x + one.width ||
one.x + one.width < two.x ||
one.y > two.y + height ||
one.y + one.height < two.y);
}
setInterval(function() {
game();
}, 1000 / 30); // 30fps