-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
296 lines (252 loc) · 7.58 KB
/
main.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
// get canvas
const canvas = document.getElementById('myCanvas');
const text = document.getElementById('text');
const context = canvas.getContext('2d');
// set grid size globally
// untested without square
const gridX = document.getElementById('myCanvas').getAttribute('width');
const gridY = document.getElementById('myCanvas').getAttribute('height');
// clear ranking button
document.getElementById('clearrankingbutton').addEventListener('click',() => clearRanking());
// fill ranking
let rankings = getRanking();
rankings.forEach(element => {
addRanking(element.name,element.points);
});
// needs to be a non-residual division of the grid
// otherwise snake pieces will overlap
const gridSize = 32;
let piecesPerBall;
let points = 0;
// snake
let pieces = [];
// global variable to clear interval
let interval;
// rename head globally for ease of use
let head;
function start() {
pieces = [];
// get custom pieces per ball or default 4
piecesPerBall = document.getElementById('piecesPerBall').value.trim() || 4;
// reset points to 0
points = 0;
text.innerHTML = "Points: "+points;
// if start is clicked again
if (interval) {
clearInterval(interval);
pieces = [];
}
// create snake head
const snake = new Snake();
pieces.push(snake);
draw(pieces);
// rename for ease of use
head = pieces[0];
let ball = addBall();
// listener for direction changing
document.addEventListener('keyup',updateDirection);
interval = setInterval(function() {
// movement
head.move();
// once more than just a head it has to update all other pieces
if (pieces.length > 1) {
updateBody();
}
if (ballCheck(ball)) {
// add X pieces per ball
for (let i = 0; i < piecesPerBall; i++) {
addPiece();
updateBody();
}
points++;
text.innerHTML = 'Points: '+points;
ball = addBall();
}
clearCanvas();
draw(pieces);
addBall(ball);
}, 17);
}
// CANVAS FUNCTIONS
// draws the snake on the canvas
function draw(array) {
array.forEach((element,index) => {
context.fillStyle = 'white';
if (index == 0) {
context.fillStyle = 'orange';
}
context.fillRect(element.position.x, element.position.y, gridSize, gridSize);
});
}
function clearCanvas () {
canvas.width = canvas.width;
}
// SNAKE FUNCTIONS
// adds a new piece based on the previous position of the last piece
function addPiece() {
let lastPiece = pieces[pieces.length-1];
let newPiece = new SnakePiece(lastPiece.prevPosition.x, lastPiece.prevPosition.y)
pieces.push(newPiece);
}
function updateBody() {
for (let i = 1; i < pieces.length; i++) {
const prevElement = pieces[i-1];
const prevPosition = pieces[i].position;
pieces[i] = new SnakePiece(prevElement.prevPosition.x, prevElement.prevPosition.y, prevPosition);
}
}
// updates the direction
function updateDirection(e){
if (e.keyCode === 38 /* up */ || e.keyCode === 87 /* w */ || e.keyCode === 90 /* z */){
head.changeDirection('up');
}
if (e.keyCode === 39 /* right */ || e.keyCode === 68 /* d */){
head.changeDirection('right');
}
if (e.keyCode === 40 /* down */ || e.keyCode === 83 /* s */){
head.changeDirection('down');
}
if (e.keyCode === 37 /* left */ || e.keyCode === 65 /* a */ || e.keyCode === 81 /* q */){
head.changeDirection('left');
}
}
// BALL FUNCTIONS
// adds a ball
function addBall(currentBall = null) {
let ballPos;
// uses old position
if (currentBall) {
ballPos = currentBall;
} else {
// generates new position if none specified
ballPos = {
x: Math.floor(Math.random()*(gridX-gridSize)),
y: Math.floor(Math.random()*(gridY-gridSize))
}
}
context.fillStyle = "deepskyblue";
context.fillRect(ballPos.x, ballPos.y, gridSize, gridSize);
return ballPos;
}
function ballCheck(ball) {
let checkX = false;
let checkY = false;
if (between(head.position.x, ball.x, ball.x+gridSize)
||
between(head.position.x+gridSize, ball.x, ball.x+gridSize)
) {
checkX = true;
}
if (between(head.position.y, ball.y, ball.y+gridSize)
||
between(head.position.y+gridSize, ball.y, ball.y+gridSize)) {
checkY = true;
}
return checkX && checkY;
}
// OTHER FUNCTIONS
function stop() {
if (interval) {
clearInterval(interval);
interval = null;
let regex = new RegExp(/^([a-zA-Z0-9]{3,15})$/);
let name;
do {
name = prompt('Input your name for rankings (leave blank for no ranking)\nOnly 3 to 15 alphanumeric characters.');
if(name) {
name = name.trim();
if(!regex.test(name)) {
alert('Bad input');
}
}
// name has to pass regex
// blank name wont be ranked
// ! because we want to exit when one of these is true
} while (!((name && regex.test(name)) || !name));
if (name) {
checkRanking(name,points);
}
}
}
function between(x, min, max) {
return min <= x && x <= max;
}
// RANKING FUNCTIONS
function checkRanking(playerName, playerPoints) {
let table = document.getElementById('rankingTable');
// delete rankings on DOM
while (table.children[1]) {
table.removeChild(table.children[1]);
}
let rankingLS = getRanking();
let exists = false;
// check if name already exists
rankingLS.forEach(element => {
if (element.name == playerName) {
exists = true;
}
});
// if it doesnt exist create it and push to LS
if (!exists) {
let player = {
name: playerName,
points: playerPoints
};
rankingLS.push(player);
rankingLS = sortRanking(rankingLS);
setRanking(rankingLS);
addAllRankings(rankingLS);
} else {
rankingLS.forEach(element => {
if (element.name == playerName) {
if (element.points < playerPoints) {
element.points = playerPoints;
rankingLS = sortRanking(rankingLS);
setRanking(rankingLS);
}
}
});
addAllRankings(rankingLS);
}
}
function addRanking(playerName,playerPoints) {
let table = document.getElementById('rankingTable');
let tr = document.createElement('tr');
let tdName = document.createElement('td');
tdName.innerHTML = playerName;
tr.append(tdName);
let tdPoints = document.createElement('td');
tdPoints.innerHTML = playerPoints;
tr.append(tdPoints);
table.append(tr);
}
function addAllRankings(data) {
data.forEach(element => {
addRanking(element.name,element.points);
});
}
function sortRanking(data) {
data = data.sort((a,b) => (a.points < b.points) ? 1 : -1);
return data;
}
function clearRanking() {
let table = document.getElementById('rankingTable');
// delete rankings on DOM
while (table.children[1]) {
table.removeChild(table.children[1]);
}
// delete rankings on LS
setRanking([]);
}
function getRanking() {
let data = localStorage.getItem('ranking');
if (data == null) {
data = [];
} else {
data = JSON.parse(data);
}
return data;
}
function setRanking(data) {
localStorage.setItem('ranking',JSON.stringify(data));
}