-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame.html
91 lines (85 loc) · 2.54 KB
/
game.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
#root {
margin: 30px auto;
width: 400px;
}
</style>
</head>
<body>
<div id="root">
<canvas id="canvas" width="400" height="400"></canvas>
</div>
<script>
let px = py = 10;
let gs = tc = 20;
let ax = ay = 13; // target initial position (13, 13)
let xv = yv = 0; // default direction (nowhere)
let trail = []; // snackself (array)
let tail = 5; // snack's minimum size
const canv = document.getElementById('canvas');
const ctx = canv.getContext('2d');
document.addEventListener('keydown', handleKeyPush);
setInterval(game, 1000 / 13);
function game() {
px += xv; // next step x-position
py += yv; // next step y-position
if (px < 0) { // when get out of the canvas
px = tc - 1;
}
if (px > tc - 1) { // when get out of the canvas
px = 0;
}
if (py < 0) { // when get out of the canvas
py = tc - 1;
}
if (py > tc - 1) { // when get out of the canvas
py = 0;
}
ctx.fillStyle = 'black'; // draw the canvas (game place)
ctx.fillRect(0, 0, canv.width, canv.height); // Rectangle with 400*400
ctx.fillStyle = 'lime'; // draw the snack
for (let i = 0; i < trail.length; i++) { // trail redraw full-loops
ctx.fillRect(trail[i].x * gs, trail[i].y * gs, gs - 2, gs - 2);
if (trail[i].x == px && trail[i].y == py) { // when bite snackself
tail = 5; // restart
}
}
trail.push({ x: px, y: py }); // next step
while (trail.length > tail) {
trail.shift(); // kick out the 'tail'(array's head)
}
if (ax == px && ay == py) { // got'it
tail++; // trail length +1
ax = Math.floor(Math.random() * tc); // next target x-position
ay = Math.floor(Math.random() * tc); // next target y-position
}
ctx.fillStyle = 'red'; // draw the target
ctx.fillRect(ax * gs, ay * gs, gs - 2, gs - 2);
}
function handleKeyPush(e) {
switch (e.keyCode) {
case 37: // left
xv = -1; yv = 0;
break;
case 38: // up
xv = 0; yv = -1;
break;
case 39: // right
xv = 1; yv = 0;
break;
case 40: // down
xv = 0; yv = 1;
break;
default: break;
}
}
</script>
</body>
</html>