-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathmain.js
483 lines (434 loc) · 15.7 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
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
let gameMode = 'classic';
let isForfeited = false;
let didGameStart = false;
let board = document.querySelector('.board');
let boardModal = document.querySelector('.boardModal');
for (let i = 0; i < 50; i++) {
let d = document.createElement('div');
board.insertBefore(d, board.children[0]);
}
boardResize();
let playerScore = 0;
let playerIndex = 24;
let playerImage = document.querySelector('#wknight').cloneNode();
playerImage.style.position = 'absolute';
playerImage.style.transform = 'translate(-50%,-50%)';
function getBoardSquareSize() {
return window.getComputedStyle(
document.querySelector('.board > div')
).getPropertyValue('height');
}
function boardResize() {
const vw = window.innerWidth;
if (vw <= 1024) {
const squareSize = board.clientWidth / 7;
board.style.gridTemplateColumns = `repeat(7, ${squareSize}px)`;
board.style.gridTemplateRows = `repeat(7, ${squareSize}px)`;
} else {
board.style.gridTemplateColumns = 'repeat(7, 10vh)';
board.style.gridTemplateRows = 'repeat(7, 10vh)';
}
}
function resizePlayer() {
const squareSize = getBoardSquareSize();
playerImage.style.maxWidth = squareSize;
playerImage.style.maxHeight = squareSize;
}
function drawToIndex(node, index) {
board.appendChild(node);
let shade = document.querySelector(`.board>:nth-child(${index + 1})`);
shadeRect = shade.getClientRects()[0];
boardRect = board.getClientRects()[0];
node.style.left = shadeRect.x - boardRect.x + shadeRect.width / 2;
node.style.top = shadeRect.y - boardRect.y + shadeRect.height / 2;
}
function drawPlayer() {
document.querySelector('#score').innerText = playerScore;
resizePlayer();
drawToIndex(playerImage, playerIndex);
if (PH.getStatus()) PH.drawPossibleMoves();
}
let targetDiffScore = 3;
let gameIsPlayed = false;
function resetGame() {
//Start the game
//this will enable keyboard movements only when game starts
Array.from(document.querySelectorAll(`.board>div`)).forEach(
(i) => (i.style.background = ''));
didGameStart = true;
// reset forfeit status for arcade time to run
isForfeited = false;
//spawn the knight
playerIndex = 24;
playerScore = 0;
combo = 0;
pieces.forEach((i) => {
i.cleanup();
i.icon.remove();
});
pieces = [];
targetDiffScore = 3;
boardModal.style.display = 'none';
drawPlayer();
document.querySelector('.gmode').disabled = true;
gameIsPlayed = true;
document.querySelector('#gmode-help').classList = '';
if (gameMode == 'arcade') {
document.getElementById("timer-box").style.display = 'block';
arcadeModeExec();
} else {
//clear the Timer if present from arcade mode
document.getElementById("timer-box").style.display = 'none';
}
clearAchievementProgressAfterReset();
}
function forfeitGame() {
if (gameIsPlayed) {
//reset the didGameStart
didGameStart = false;
isForfeited = true;
boardModal.style.display = 'grid';
document.querySelector('.loss_modal').style.display = 'block';
document.querySelector('.loss_modal span').innerText =
playerScore + ' You have forfeited the game!';
//updateHighscores(playerScore, gameMode);
document.querySelector('.gmode').disabled = false;
gameIsPlayed = false;
}
}
function getPlayerNextMoves(playerIndex1) {
let playerNextMoves = protopieces['knight'].generateMoves(playerIndex1);
return playerNextMoves;
}
function isSquareSafe(move, allPieces) {
for (p of allPieces) {
if (p.canHitSquare(move) && p.deploymentCounter <= 0) {
return false;
}
}
return true;
}
//a testing function for isSquareSafe
function checkNextMoveSafety(allPieces, playerIndex2) {
moves = getPlayerNextMoves(playerIndex2);
//Add the move that the player might stay in current place
moves.push(playerIndex2);
let safety = true;
for (move of moves) {
safety = safety & isSquareSafe(move, allPieces);
}
return safety;
}
let occupiedSquares = [];
let pieces = [];
let wasTouch = false;
board.addEventListener('touchstart', (e) => {
wasTouch = true;
});
board.addEventListener('mousemove', (e) => {
if (wasTouch) {
wasTouch = false;
return;
}
Array.from(document.querySelectorAll(`.board>div`)).forEach(
(i) => (i.style.background !='blue' ? i.style.background = '': i.style.background = 'blue')
);
let path = e.path || e.composedPath();
if (path[0].matches('.board>div>img')) {
let thePiece;
for (let i of pieces) {
if (i.icon == path[1]) {
thePiece = i;
break;
}
}
let possibleMoves = protopieces[thePiece.type].generateMoves(
thePiece.index
);
possibleMoves = possibleMoves.filter((i) => !isOccupied(i));
if (thePiece.type == "pawn") { // Pawn edge case since it only moves in one direction
possibleMoves = possibleMoves.filter((i) => thePiece.upDirection ? i < thePiece.index : i > thePiece.index)
}
for (let i of possibleMoves) {
document.querySelector(
`.board>div:nth-child(${i + 1})`
).style.background = 'lightblue';
}
}
});
let nope = {}; // intervals for red squares
function isValidPlayerMove(playerIndex, squareIndex) {
const [playerX, playerY] = coordsTo2D(playerIndex);
const [targetX, targetY] = coordsTo2D(squareIndex);
return playerIndex == squareIndex || playerMoveMatrix.some(([dx, dy]) => {
const tryX = playerX + dx;
const tryY = playerY + dy;
return (
playerCanMove(tryX, tryY) && (tryX == targetX && tryY == targetY)
);
});
}
board.addEventListener('click', (e) => {
let squareIndex;
let path = e.path || e.composedPath();
if (path[0].matches('.board')) return;
for (let p of path) {
if (p.matches('.board>img')) {
if (p == playerImage) squareIndex = playerIndex;
break;
}
if (p.matches('.board>div')) {
squareIndex = Array.from(
board.children
).indexOf(p);
if (squareIndex > 48) {
for (let i of pieces) {
if (i.icon == p) {
squareIndex = i.index;
break;
}
}
}
if (squareIndex == 49) return;
break;
}
}
//Check if the squareIndex is a valid move relative to the playerIndex
if (isValidPlayerMove(playerIndex, squareIndex)) {
//its a valid move, execute it
let killed = false;
playerIndex = squareIndex;
//move pieces
if (gameMode != 'arcade') {
pieces.map((p) => p.cleanup());
}
occupiedSquares = []; // reset so that pieces can take you if you take pieces
let piecesStillAlive = pieces.length
pieces = pieces.filter((p) => {
let ok = p.checkAlive();
if (!ok) {
totalKills++;
killed = true;
if (gameMode != 'pacifist') playerScore += protopieces[p.type].value;
combo++
p.icon.remove();
}
return ok;
});
if (piecesStillAlive <= pieces.length) {
combo = 0;
}
if (gameMode != 'arcade') {
pieces.map((p) => p.move());
}
let playerIsDead = pieces.reduce(
(d, pp) => d || (pp.index == playerIndex && !pp.deploymentCounter),
false
);
if (playerIsDead) {
//reset the didGameStart
didGameStart = false;
pieces.map((p) => p.draw());
//i deduct a kill when i get killed myself to not have both loss and achievements pop
if (killed) totalKills--;
document.querySelector('#score').innerText = playerScore;
document.querySelector('.gmode').disabled = false;
document.querySelector('.loss_modal').style.display = 'block';
document.querySelector('.loss_modal span').innerText = playerScore;
updateHighscores(playerScore, gameMode);
playerImage.remove();
boardModal.style.display = 'grid';
gameIsPlayed = false;
document.querySelector('#gmode-help').classList = 'hidden';
playerIndex = -1;
return;
// show the button
}
playerTotalSteps += 3;
occupiedSquares = [];
pieces.map((p) => p.checkAlive()); // repopulate occupied squares so we dont spawn on occupied squares
//add extra pieces
let diffScore = pieces.reduce((p, i) => p + protopieces[i.type].value, 0);
if (diffScore < targetDiffScore) {
let spawnArr = [];
for (let i of protoArr) {
for (let j = 0; j < i[1].spawnTries; j++) {
spawnArr.push(i[0]);
}
}
if (gameMode != 'arcade') {
let randomPiece = spawnArr[Math.floor(Math.random() * spawnArr.length)];
if (gameMode == 'knightmare') randomPiece = 'knight';
let allowSpawnLocations = [];
for (let i = 0; i < 49; i++) {
if (!isOccupied(i) && i != playerIndex) {
if ((randomPiece == "pawn" && (Math.floor(i / 7) == 1 || Math.floor(i / 7) == 5))) // Pawns always spawn on the second row on either side
allowSpawnLocations.push(i);
else if (randomPiece != "pawn")
allowSpawnLocations.push(i);
}
}
if (allowSpawnLocations.length) {
let randomPosition =
allowSpawnLocations[
Math.floor(Math.random() * allowSpawnLocations.length)
];
pieces.push(new Piece(randomPiece, randomPosition));
}
}
}
occupiedSquares = [];
pieces.map((p) => p.checkAlive()); // repopulate occupied squares
if (gameMode == 'strategist') {
pieces.filter((i) => i.deploymentCounter > 0).map((p) => p.draw());
pieces
.filter((i) => i.deploymentCounter == 0)
.map((p, i) => setTimeout(p.draw, (200 / pieces.length) * i));
} else {
pieces.map((p) => p.draw());
}
if (gameMode == 'pacifist')
playerScore +=
pieces.reduce(
(p, i) => (p + !i.deploymentCounter ? protopieces[i.type].value : 0),
0
) / 4;
targetDiffScore += gameMode == 'knightmare' ? 1 : 0.5;
playerScore++;
checkAchievements();
drawPlayer();
} else {
if (gameIsPlayed) PH.blinkInvalidMove(squareIndex);
}
});
/*using only keydown means if you hold down an option
you will keep moving in that direction as long as you can*/
if(gameMode!="loop"){
document.addEventListener('keydown', e => {
let destIndex;
// Check is the begin button was pressed
// If game did not start do nothing
if(!didGameStart) return;
const key = e.key;
if(key == "q" || key == "Q"){
//Q pressed, move 2 left and 1 up
destIndex = playerIndex - 9;
}else if(key == "w" || key == "W"){
//W pressed, move 1 left and 2 up
destIndex = playerIndex - 15;
}else if(key == "e" || key == "E"){
//E pressed, move 1 right and 2 up
destIndex = playerIndex - 13;
}else if(key == "r" || key == "R"){
//R pressed, move 2 right and 1 up
destIndex = playerIndex - 5;
}else if(key == "a" || key == "A"){
//A pressed, move 2 left and 1 down
destIndex = playerIndex + 5;
}else if(key == "s" || key == "S"){
//S pressed, move 1 left and 2 down
destIndex = playerIndex + 13;
}else if(key == "d" || key == "D"){
//D pressed, move 1 right and 2 down
destIndex = playerIndex + 15;
}else if(key == "f" || key == "F"){
//F pressed, move 2 right and 1 down
destIndex = playerIndex + 9;
}
/*destIndex now holds the destination index
check if destination will be a square on the board and gaem is not over
playerIndex == -1 signifies end of game*/
if(destIndex >= 0 && destIndex <= 48 && playerIndex != -1){
let boardChildren = board.children;
//we go to the equivalent square and simulate a click which triggers same event as a mouse click
boardChildren[destIndex].click();
}
});
}
function arcadeModeExec() {
//figure out which square we're on
let killed = false;
//move pieces
pieces.map((p) => p.cleanup());
occupiedSquares = []; // reset so that pieces can take you if you take pieces
pieces = pieces.filter((p) => {
let ok = p.checkAlive();
if (!ok) {
totalKills++;
killed = true;
if (gameMode != 'pacifist') playerScore += protopieces[p.type].value;
p.icon.remove();
}
return ok;
});
pieces.map((p) => p.move());
// repopulate occupied squares so we dont spawn on occupied squares
//add extra pieces
let playerIsDead = pieces.reduce(
(d, pp) => d || (pp.index == playerIndex && !pp.deploymentCounter),
false
);
if (playerIsDead) {
pieces.map((p) => p.draw());
//i deduct a kill when i get killed myself to not have both loss and achievements pop
if (killed) totalKills--;
document.querySelector('#score').innerText = playerScore;
document.querySelector('.gmode').disabled = false;
document.querySelector('.loss_modal').style.display = 'block';
document.querySelector('.loss_modal span').innerText = playerScore;
updateHighscores(playerScore, gameMode);
playerImage.remove();
boardModal.style.display = 'grid';
gameIsPlayed = false;
document.querySelector('#gmode-help').classList = 'hidden';
return;
// show the button
}
pieces.map((p) => p.checkAlive());
let diffScore = pieces.reduce((p, i) => p + protopieces[i.type].value, 0);
if (diffScore < targetDiffScore) {
let spawnArr = [];
for (let i of protoArr) {
for (let j = 0; j < i[1].spawnTries; j++) {
spawnArr.push(i[0]);
}
}
let randomPiece = spawnArr[Math.floor(Math.random() * spawnArr.length)];
let allowSpawnLocations = [];
for (let i = 0; i < 49; i++)
if (!isOccupied(i) && i != playerIndex) {
if ((randomPiece == "pawn" && (Math.floor(i / 7) == 1 || Math.floor(i / 7) == 5))) // Pawns always spawn on the second row on either side
allowSpawnLocations.push(i);
else if (randomPiece != "pawn")
allowSpawnLocations.push(i);
}
if (allowSpawnLocations.length) {
let randomPosition =
allowSpawnLocations[
Math.floor(Math.random() * allowSpawnLocations.length)
];
let newPiece = new Piece(randomPiece, randomPosition);
newPiece.deploymentCounter = 1; //time until new piece spawns
pieces.push(newPiece);
}
}
// repopulate occupied squares
pieces.map((p) => p.draw());
targetDiffScore += 0.5;
playerScore++;
checkAchievements();
drawPlayer();
if (!isForfeited) {
startMoveTimer();
setTimeout(arcadeModeExec, 2500);
}
}
window.addEventListener('resize', () => {
boardResize();
if(!didGameStart) {
resizePlayer();
} else {
pieces.forEach((p) => p.draw());
drawPlayer();
}
});