-
Notifications
You must be signed in to change notification settings - Fork 0
/
game.js
240 lines (191 loc) · 4.98 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
/*
Pure JavaScript, CSS and HTML snake
By Vid Kreča, 13.2.2020
Notes:
Game loop:
- check for collisions (wall, food, snake itself)
- if collision with wall - end game
- if collision with food - add new node, spawn new food
- if collision with itself - end game
- advance snake (delete last node, add new)
- check if end of game (spawned enough food to end the game)
*/
var debug = true;
// Constants
const SNAKE_COLOR = "black";
const SNAKE_HEAD_COLOR = "white";
const CANVAS_COLOR = "gray";
const FOOD_COLOR = "red";
const GAME_SPEED = 150; // More is slower
const INIT_SNAKE_SIZE = 10;
const step = 10;
const canvas = document.getElementById("gameCanvas");
const ctx = canvas.getContext("2d");
let h = canvas.height;
let w = canvas.width;
// Variables
let snake = [];
function generateSnake() {
for (i = INIT_SNAKE_SIZE; i > 0; i--) {
let tx = (i+1)*step;
let ty = (h/2);
snake.push({x: tx, y: ty});
}
}
generateSnake();
let dx = step, dy = 0;
let interval;
let score = 0;
let changingDir = false;
let food;
let addPart = false;
document.body.onload = function() {
start();
}
// Initialization function
function start() {
getHighscore();
// Start game loop
interval = setInterval(loop, GAME_SPEED);
generateFood();
if (debug) console.log("Game started!");
}
function restart() {
snake = [];
generateSnake();
dx = step; dy = 0;
score = 0;
changingDir = false;
food = null;
generateFood();
addPart = false;
clearInterval(interval);
start();
}
document.getElementById("restartBtn").addEventListener("click", restart);
// Ends the game, displays score
function end(win = false) {
clearInterval(interval);
let text = (win) ? "You won :)" : "You lost :(";
// Display end text
ctx.fillStyle = "white";
ctx.fillRect(15, 25, 80, 70);
var txtSize = 15;
ctx.fillStyle = "red";
ctx.font = txtSize+"px Arial bold";
ctx.fillText("Game over!", 20, 40);
ctx.fillText(text, 20, 50+txtSize);
ctx.fillText("Score: "+score, 20, 60+txtSize*2);
if (debug) console.log("Game over!\n"+text+"\nScore: "+score);
saveHighscore();
}
// Highscore functions
function saveHighscore() {
var currHighscore = document.getElementById("highscore").innerText.split(":")[1];
if (score > currHighscore) {
chrome.storage.sync.set({ "highscore" : score }, function() {});
}
}
function getHighscore() {
chrome.storage.sync.get("highscore", function(items) {
if (!chrome.runtime.error) {
document.getElementById("highscore").innerText = "Highscore: "+items.highscore;
}
});
}
// Game loop
function loop() {
if (score > ((w/step)*(h/step)-INIT_SNAKE_SIZE)) end(true);
clear();
drawSnake();
collisionCheck();
advanceSnake();
}
// Clear canvas
function clear() {
// Set canvas background color
ctx.fillStyle = CANVAS_COLOR;
ctx.fillRect(0, 0, w, h);
// Draw food
ctx.fillStyle = FOOD_COLOR;
ctx.fillRect(food.x, food.y, step, step);
}
// Draw snake body
function drawSnake() {
let first = true;
snake.forEach((part) => {
if (first) {
ctx.fillStyle = SNAKE_HEAD_COLOR;
first = false;
}
else ctx.fillStyle = SNAKE_COLOR;
ctx.fillRect(part.x, part.y, step, step);
});
}
// Moves snake in current moving direction
function advanceSnake() {
changingDir = false;
if (addPart) addPart = false;
else snake.pop() // Removes last element
cx = snake[0].x;
cy = snake[0].y;
if (dx != 0) { // Left/Right
snake.unshift({x: cx+dx, y: cy});
}
else if (dy != 0) { // Up/Down
snake.unshift({x: cx, y: cy+dy});
}
}
// Checks for all types of collisions
function collisionCheck() {
cx = snake[0].x;
cy = snake[0].y;
// Check snake->snake collision
snake.forEach((part, i) => {
if (i != 0 && part.x == cx && part.y == cy) end();
});
// Check snake->wall collision
if (cx < 0 || cx > w-(1*step)) end();
if (cy < 0 || cy > h-(1*step)) end();
// Check snake->food collision
if (cx == food.x && cy == food.y) {
score++;
document.getElementById("score").innerHTML = "Score: " + score;
generateFood();
addPart = true;
}
}
// Generate random food location
function generateFood() {
let rx, ry;
let s = true;
while (s) {
s = false;
rx = (Math.random() * w-1);
ry = (Math.random() * h-1);
rx -= rx % step;
ry -= ry % step;
snake.forEach((part) => {
if (part.x == rx || part.y == ry) s = true;
});
}
food = {x: rx, y: ry};
if (debug) console.log("Food at: " + rx + ", " + ry);
}
// Event listener for keyboard input
document.addEventListener("keydown", changeDirection);
function changeDirection(event) {
const LEFT = 37;
const RIGHT = 39;
const UP = 38;
const DOWN = 40;
let key = event.keyCode;
if (changingDir) return;
switch (key) {
case LEFT: if (dx != step) { dx=-step; dy=0; } break;
case RIGHT: if (dx != -step) { dx=step; dy=0; } break;
case UP: if (dy != step) { dx=0; dy=-step; } break;
case DOWN: if (dy != -step) { dx=0; dy=step; } break;
}
changingDir = true;
}