-
Notifications
You must be signed in to change notification settings - Fork 0
/
game.js
351 lines (346 loc) · 8.62 KB
/
game.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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
/*jslint bitwise:true, es5: true */
(function (window, undefined) {
'use strict';
var KEY_ENTER = 13,
KEY_LEFT = 37,
KEY_UP = 38,
KEY_RIGHT = 39,
KEY_DOWN = 40,
canvas = null,
ctx = null,
lastPress = null,
pause = false,
gameover = false,
currentScene = 0,
scenes = [],
mainScene = null,
gameScene = null,
highscoresScene = null,
body = [],
food = null,
foodExtraPoint = null,
foodExtraPointTime = 0,
highscores = [],
posHighscore = 10,
dir = 0,
score = 0,
userId = 1,
iBody = new Image(),
iFood = new Image(),
iFoodExtra = new Image(),
aEat = new Audio(),
aDie = new Audio();
window.requestAnimationFrame = (function () {
return window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
function (callback) {
window.setTimeout(callback, 17);
};
}());
document.addEventListener('keydown', function (evt) {
if (evt.which >= 37 && evt.which <= 40) {
evt.preventDefault();
}
lastPress = evt.which;
}, false);
function Rectangle(x, y, width, height) {
this.x = (x === undefined) ? 0 : x;
this.y = (y === undefined) ? 0 : y;
this.width = (width === undefined) ? 0 : width;
this.height = (height === undefined) ? this.width : height;
}
Rectangle.prototype = {
constructor: Rectangle,
intersects: function (rect) {
if (rect === undefined) {
window.console.warn('Missing parameters on function intersects');
} else {
return (this.x < rect.x + rect.width &&
this.x + this.width > rect.x &&
this.y < rect.y + rect.height &&
this.y + this.height > rect.y);
}
},
fill: function (ctx) {
if (ctx === undefined) {
window.console.warn('Missing parameters on function fill');
} else {
ctx.fillRect(this.x, this.y, this.width, this.height);
}
},
drawImage: function (ctx, img) {
if (img === undefined) {
window.console.warn('Missing parameters on function drawImage');
} else {
if (img.width) {ctx.drawImage(img, this.x, this.y);
} else {
ctx.strokeRect(this.x, this.y, this.width, this.height);
}
}
}
};
function Scene() {
this.id = scenes.length;
scenes.push(this);
}
Scene.prototype = {
constructor: Scene,
load: function () {},
paint: function (ctx) {},
act: function () {}
};
function loadScene(scene) {
currentScene = scene.id;
scenes[currentScene].load();
}
function random(max) {
return ~~(Math.random() * max);
}
function addHighscore(score) {
posHighscore = 0;
while (highscores[posHighscore] > score && posHighscore < highscores.length) {
posHighscore += 1;
}
highscores.splice(posHighscore, 0, score);
if (highscores.length > 10) {
highscores.length = 10;
}
localStorage.highscores = highscores.join(',');
}
function repaint() {
window.requestAnimationFrame(repaint);
if (scenes.length) {
scenes[currentScene].paint(ctx);
}
}
function run() {
setTimeout(run, 50);
if (scenes.length) {
scenes[currentScene].act();
}
}
function init() {
// Get canvas and context
canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
// Load assets
iBody.src = 'assets/body.png';
iFood.src = 'assets/fruit.png';
iFoodExtra.src = 'assets/extra-fruit.png';
aEat.src = 'assets/chomp.oga';
aDie.src = 'assets/dies.oga';
// Create food
food = new Rectangle(80, 80, 10, 10);
// Create extra point food
foodExtraPoint = new Rectangle(80, 80, 10, 10);
if (localStorage.highscores) {
highscores = localStorage.highscores.split(',');
}
// Start game
run();
repaint();
}
// Main Scene
mainScene = new Scene();
mainScene.paint = function (ctx) {
// Clean canvas
ctx.fillStyle = '#030';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Draw title
ctx.fillStyle = '#fff';
ctx.textAlign = 'center';
ctx.fillText('SNAKE', 300, 120);
ctx.fillText('Press Enter', 300, 180);
};
mainScene.act = function () {
// Load next scene
if (lastPress === KEY_ENTER) {
loadScene(highscoresScene);
lastPress = null;
}
};
// Game Scene
gameScene = new Scene();
gameScene.load = function () {
score = 0;
dir = 1;
body.length = 0;
body.push(new Rectangle(40, 40, 10, 10));
body.push(new Rectangle(0, 0, 10, 10));
body.push(new Rectangle(0, 0, 10, 10));
food.x = random(canvas.width / 10 - 1) * 10;
food.y = random(canvas.height / 10 - 1) * 10;
foodExtraPointTime = Date.now() + 700*(5 + random(17));
foodExtraPoint.x = random(canvas.width / 10 - 1) * 10;
foodExtraPoint.y = random(canvas.height / 10 - 1) * 10;
gameover = false;
};
gameScene.paint = function (ctx) {
var i = 0,
l = 0;
// Clean canvas
ctx.fillStyle = '#030';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Draw player
ctx.strokeStyle = '#0f0';
for (i = 0, l = body.length; i < l; i += 1) {
body[i].drawImage(ctx, iBody);
}
// Draw walls
//ctx.fillStyle = '#999';
//for (i = 0, l = wall.length; i < l; i += 1) {
// wall[i].fill(ctx);
//}
// Draw foodctx.strokeStyle = '#f00';
food.drawImage(ctx, iFood);
if((Date.now() > foodExtraPointTime)){
foodExtraPoint.drawImage(ctx, iFoodExtra);
}
// Draw score
ctx.fillStyle = '#fff';
ctx.textAlign = 'left';
ctx.fillText('Score: ' + score, 0, 10);
// Debug last key pressed
//ctx.fillText('Last Press: '+lastPress,0,20);
// Draw pause
if (pause) {
ctx.textAlign = 'center';
if (gameover) {
ctx.fillText('GAME OVER', 300, 150);
} else {
ctx.fillText('PAUSE', 300, 150);
}
}
};
gameScene.act = function () {
var i = 0,
l = 0;
if (!pause) {
// GameOver Reset
if (gameover) {
loadScene(highscoresScene);
}
// Move Body
for (i = body.length - 1; i > 0; i -= 1) {
body[i].x = body[i - 1].x;
body[i].y = body[i - 1].y;
}
// Change Direction
if (lastPress === KEY_UP && dir !== 2) {
dir = 0;
}
if (lastPress === KEY_RIGHT && dir !== 3) {
dir = 1;
}
if (lastPress === KEY_DOWN && dir !== 0) {
dir = 2;
}
if (lastPress === KEY_LEFT && dir !== 1) {
dir = 3;
}
// Move Head
if (dir === 0) {
body[0].y -= 10;
}
if (dir === 1) {
body[0].x += 10;
}
if (dir === 2) {
body[0].y += 10;
}
if (dir === 3) {
body[0].x -= 10;
}
// Out Screen
if (body[0].x > canvas.width - body[0].width) {
body[0].x = 0;
}
if (body[0].y > canvas.height - body[0].height) {
body[0].y = 0;}
if (body[0].x < 0) {
body[0].x = canvas.width - body[0].width;
}
if (body[0].y < 0) {
body[0].y = canvas.height - body[0].height;
}
// POST to API
function postApiScore(actualScore){
fetch(`https://jsonplaceholder.typicode.com/users/${userId}/posts/`, {
method: 'POST',
body: JSON.stringify({
score: actualScore,
userId: userId,
}),
headers: {
'Content-type': 'application/json',
},
})
.then((response) => response.json())
.then((json) => {console.log(json); console.log("Score sent successfully");})
.catch((error) => {console.log(error);console.log("Error trying to send the score");})
}
// Food Intersects
if (body[0].intersects(food)) {
body.push(new Rectangle(0, 0, 10, 10));
score += 1;
postApiScore(score)
food.x = random(canvas.width / 10 - 1) * 10;
food.y = random(canvas.height / 10 - 1) * 10;
aEat.play();
}
// Extra point Food Intersects
if (body[0].intersects(foodExtraPoint,foodExtraPointTime)) {
score += 5;
postApiScore(score)
foodExtraPoint.x = random(canvas.width / 10 - 1) * 10;
foodExtraPoint.y = random(canvas.height / 10 - 1) * 10;
foodExtraPointTime = Date.now() + 700*(5 + random(17))
aEat.play()
}
// Body Intersects
for (i = 2, l = body.length; i < l; i += 1) {
if (body[0].intersects(body[i])) {
gameover = true;
pause = true;
aDie.play();
addHighscore(score);
}
}
}
// Pause/Unpause
if (lastPress === KEY_ENTER) {
pause = !pause;
lastPress = null;
}
};
// Highscore Scene
highscoresScene = new Scene();
highscoresScene.paint = function (ctx) {
var i = 0,
l = 0;
// Clean canvas
ctx.fillStyle = '#030';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Draw title
ctx.fillStyle = '#fff';
ctx.textAlign = 'center';
ctx.fillText('HIGH SCORES', 220, 30);
// Draw high scores
ctx.textAlign = 'right';
for (i = 0, l = highscores.length; i < l; i += 1) {
if (i === posHighscore) {
ctx.fillText('*' + highscores[i], 180, 40 + i * 10);
} else {
ctx.fillText(highscores[i], 180, 40 + i * 10);
}
}};
highscoresScene.act = function () {
// Load next scene
if (lastPress === KEY_ENTER) {
loadScene(gameScene);
lastPress = null;
}
};
window.addEventListener('load', init, false);
}(window));