-
Notifications
You must be signed in to change notification settings - Fork 0
/
snake.js
263 lines (238 loc) · 7.4 KB
/
snake.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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
const snakeGame = () => {
const canvas = document.createElement("canvas");
if (canvas.getContext) {
const primaryCanvas = document.getElementById("primaryCanvas");
const secondaryCanvas = document.getElementById("secondaryCanvas");
// GLOBAL VARIABLES
const primary = primaryCanvas.getContext("2d");
const secondary = secondaryCanvas.getContext("2d");
let tick;
let currentApple;
let currentInterval;
let score = 0;
// CONFIG
const config = {
appleFill: "rgb(250, 0, 0)",
snakeFill: "rgb(0, 0, 0)",
snakeInitialState: [
{ x: 4, y: 9 },
{ x: 3, y: 9 },
{ x: 2, y: 9 },
{ x: 1, y: 9 }
],
initialInterval: 200,
controls: {
left: ["ArrowLeft", "a", 37, 65],
up: ["ArrowUp", "w", 38, 87],
right: ["ArrowRight", "d", 39, 68],
down: ["ArrowDown", "s", 40, 83]
},
startDirection: "RIGHT",
updateScore: (currentScore) => {
currentScore += 10;
},
updateVelocity: (currentVelocity) => {
currentVelocity -= (currentVelocity / 100) * 3;
},
TILESIZE: 20
};
const {
appleFill,
snakeFill,
snakeInitialState,
initialInterval,
controls,
startDirection,
updateScore,
updateVelocity,
TILESIZE
} = config;
// TODO try to make it more DRY, you are probably getting / setting width & height abundantly.
const roundCanvasSize = ((canvas, tile) => {
let { height, width } = canvas;
let moduloX = width % tile;
let moduloY = height % tile;
canvas.height -= moduloY;
canvas.width -= moduloX;
})(primaryCanvas, TILESIZE);
const { height: HEIGHT, width: WIDTH } = primaryCanvas;
const LIMIT_X = WIDTH / TILESIZE - 1;
const LIMIT_Y = HEIGHT / TILESIZE - 1;
const GRIDSIZE_X = WIDTH / TILESIZE;
const GRIDSIZE_Y = HEIGHT / TILESIZE;
// HELPERS
const getRandom = (min, max) => {
return Math.floor(Math.random() * (max - min) + min);
};
// "candidate input is very hairy and needs to be refactored (in 2 of 3 cases they are actually separate coords, not an object.)"
const isMatch = (candidate, current) => {
let { posX: x, posY: y } = candidate;
if (Array.isArray(current)) {
let match = current.filter(item => item.posX === x && item.posY === y);
return !!match.length;
} else {
// currentApple is not an array
return x === current.posX && y === current.posY;
}
};
const drawRectangle = (posX, posY, dim = TILESIZE, fill) => {
primary.fillStyle = fill;
primary.fillRect(posX * TILESIZE, posY * TILESIZE, dim, dim);
};
const clearRectangle = (posX, posY, dim = TILESIZE) => {
primary.clearRect(posX * TILESIZE, posY * TILESIZE, dim, dim);
};
const spawnApple = () => {
currentApple = null;
currentApple = new Apple();
currentApple.render();
};
detectCollision = function(x, y, context) {
if (
x < 0 ||
y < 0 ||
x > LIMIT_X ||
y > LIMIT_Y ||
isMatch({ posX: x, posY: y }, context.shape)
) {
return true;
}
};
const playSound = (sound, volume = 0.1) => {
const audio = document.getElementById(sound);
if (audio) {
audio.volume = volume;
audio.currentTime = 0;
audio.play();
}
};
const repaintScore = () => {
secondary.clearRect(0, 0, secondaryCanvas.width, secondaryCanvas.height);
secondary.textAlign = "right";
secondary.fillStyle = "white";
secondary.font = "bold 24px monospace";
secondary.fillText(
`score: ${String(score).padStart(3, " ")}`,
secondaryCanvas.width,
50
);
};
// CONTROLS
controlDirection = e => {
if (!snake) return;
const { left, up, right, down } = controls;
key = e.key || e.keyIdentifier || e.keyCode;
switch (true) {
case !!~left.indexOf(key) && snake.direction !== "RIGHT":
snake.setDirection("LEFT").move();
break;
case !!~up.indexOf(key) && snake.direction !== "DOWN":
snake.setDirection("UP").move();
break;
case !!~right.indexOf(key) && snake.direction !== "LEFT":
snake.setDirection("RIGHT").move();
break;
case !!~down.indexOf(key) && snake.direction !== "UP":
snake.setDirection("DOWN").move();
break;
}
};
// CONSTRUCTORS
const Tile = function(posX, posY) {
this.posX = posX;
this.posY = posY;
};
const Apple = function() {
[this.posX, this.posY] = this.getFreeCoords();
};
Apple.prototype.getFreeCoords = function() {
const getMatches = function() {
let randX = getRandom(0, GRIDSIZE_X);
let randY = getRandom(0, GRIDSIZE_Y);
if (isMatch({ posX: randX, posY: randY }, snake.shape)) {
return getMatches();
}
return [randX, randY];
};
return getMatches();
};
Apple.prototype.render = function() {
drawRectangle(this.posX, this.posY, TILESIZE, appleFill);
};
const Snake = function() {
this.shape = snakeInitialState.map(item => new Tile(item.x, item.y));
this.direction = startDirection;
this.init = function() {
console.log("snake initialized!");
window.addEventListener(
"keydown",
e => {
// bind this?
controlDirection(e);
},
false
);
for (let item of this.shape) {
drawRectangle(item.posX, item.posY, TILESIZE, snakeFill);
}
spawnApple();
currentInterval = initialInterval;
tick = setInterval(this.move.bind(this), currentInterval);
};
this.setDirection = function(direction) {
this.direction = direction;
return this;
};
this.move = function() {
let { posX: newX, posY: newY } = this.shape[0];
switch (this.direction) {
case "LEFT":
newX -= 1;
break;
case "UP":
newY -= 1;
break;
case "RIGHT":
newX += 1;
break;
case "DOWN":
newY += 1;
break;
}
this.redraw(newX, newY);
};
this.redraw = function(x, y) {
const tileToAdd = new Tile(x, y);
const isCollision = detectCollision(
tileToAdd.posX,
tileToAdd.posY,
this
);
if (isCollision) {
// snake does crash to itself or to the edges of canvas
playSound("snake_crash");
clearInterval(tick);
snake = null;
} else {
this.shape.unshift(tileToAdd);
drawRectangle(tileToAdd.posX, tileToAdd.posY, TILESIZE, snakeFill);
if (isMatch(tileToAdd, currentApple)) {
// snake eats an apple
playSound("snake_apple-eaten");
// TODO Merge update and repaint score into one function
updateScore(score);
repaintScore();
updateVelocity(currentInterval);
spawnApple();
} else {
const tileToRemove = this.shape.pop();
clearRectangle(tileToRemove.posX, tileToRemove.posY, TILESIZE);
}
}
};
};
let snake = new Snake();
snake.init();
}
};
window.addEventListener("load", () => snakeGame(), false);