-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
103 lines (87 loc) · 2.11 KB
/
script.js
File metadata and controls
103 lines (87 loc) · 2.11 KB
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
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
document.addEventListener("keydown", keyDownEvent);
// render X times per second
var speed = window.location.search.split('=')[1];
setInterval(draw, 1000 / speed);
// game world
var gridSize = (tileSize = 25);
var nextX = (nextY = 0);
// snake
var defaultTailSize = 2;
var tailSize = defaultTailSize;
var snakeTrail = [];
var snakeX = (snakeY = 20);
// apple
var appleX = (appleY = 15);
// draw
function draw() {
// move snake to next pos
snakeX += nextX;
snakeY += nextY;
// snake out of canvas
if (snakeX < 0) {
snakeX = gridSize - 1;
}
if (snakeX > gridSize - 1) {
snakeX = 0;
}
if (snakeY < 0) {
snakeY = gridSize - 1;
}
if (snakeY > gridSize - 1) {
snakeY = 0;
}
//snake bite apple?
if (snakeX == appleX && snakeY == appleY) {
tailSize++;
appleX = Math.floor(Math.random() * gridSize);
appleY = Math.floor(Math.random() * gridSize);
}
//paint background
ctx.fillStyle = "black";
ctx.fillRect(0, 0, canvas.width, canvas.height);
// paint snake
ctx.fillStyle = "green";
for (var i = 0; i < snakeTrail.length; i++) {
ctx.fillRect(
snakeTrail[i].x * tileSize,
snakeTrail[i].y * tileSize,
tileSize,
tileSize
);
//snake bites tail?
if (snakeTrail[i].x == snakeX && snakeTrail[i].y == snakeY) {
tailSize = 1;
}
}
// paint apple
ctx.fillStyle = "red";
ctx.fillRect(appleX * tileSize, appleY * tileSize, tileSize, tileSize);
//set snake trail
snakeTrail.push({ x: snakeX, y: snakeY });
while (snakeTrail.length > tailSize) {
snakeTrail.shift();
}
}
// input
function keyDownEvent(e) {
switch (e.keyCode) {
case 37:
nextX = -1;
nextY = 0;
break;
case 38:
nextX = 0;
nextY = -1;
break;
case 39:
nextX = 1;
nextY = 0;
break;
case 40:
nextX = 0;
nextY = 1;
break;
}
}