-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1500 lines (1270 loc) · 36.4 KB
/
script.js
File metadata and controls
1500 lines (1270 loc) · 36.4 KB
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use strict";
const gameBoard = document.getElementById("gameboard");
const pacLand = document.getElementById("pac-land");
const ghostWorld = document.getElementById("ghost-world");
//Gameboard layers
let world = [];
let pacmen = [];
let ghosts = [];
//Game characteristics
let level = "easy";
let players = 1;
let isSuper = false;
let gamePlay = false;
let score = {
current: 0,
remaining: 0,
winning: 0,
};
gameBoardSize();
function gameBoardSize() {
const screen = document.querySelector(".screen");
const layers = screen.querySelectorAll(".screen>div");
let width = window.innerWidth * 0.29;
width = width > 565 ? 565 : width;
const gameWidth = Math.round(width / 20) * 20;
screen.style.width = gameWidth + 7 + "px";
screen.style.height = gameWidth + 7 + "px";
layers.forEach((el) => {
el.style.width = gameWidth + "px";
el.style.height = gameWidth + "px";
});
}
function gameInit(level) {
generateMap(level);
generatePacLand();
generateGhostWorld(level);
setWinningScore();
runGhosts();
}
//* Generate Map
function generateMap(difficulty) {
// * enable gameplay
gamePlay = true;
// * reset mushroom status
mushroomSet = false;
// * clear gameboard classList
gameBoard.className = "";
level = difficulty;
// * create empty world
world = [];
// * get container dimensions and divide by 20 (round down)
const width = Math.floor(gameBoard.offsetWidth / 20);
const height = Math.floor(gameBoard.offsetHeight / 20);
let row = [];
// * create row that matches width
for (let i = 0; i < width; i++) {
i === 0 || i + 1 === width ? row.push(2) : row.push(0);
}
// * create number of rows to match height
for (let i = 0; i < height; i++) {
world.push(row);
}
// * Initial map has only bricks on edges & empty spaces in the middle
setBoundaries(world);
// * Generate walls based on difficulty
level === "hard" || level === "mushrooms"
? setRandomWalls()
: level === "medium"
? setMediumWalls()
: setLongWalls();
// * Generate Cherries
setCherries();
// * Generate HTML
mapHTML(world, gameBoard);
}
function setBoundaries(world) {
for (let y = 0; y < world.length; y++) {
world[y] =
y === 0 || y + 1 === world.length
? (world[y] = world[y].map((x) => {
return x === 2 ? (x = x) : (x = x + 2);
}))
: //Fill the remainder of the cells with coins
(world[y] = world[y].map((x) => {
return x === 2 ? (x = x) : (x = x + 1);
}));
}
}
function setRandomWalls() {
// Wall seeds should never touch the edges so start incrementing on the third row(y)
const limit = world.length - 2;
for (let i = 2; i < limit; i++) {
world[i] = world[i].map((row, loop) => {
//Set a 30% chance of generating a wall seed
const wallSeed = Math.random() > 0.3 ? true : false;
//skip first and last values in array
return (row =
loop < 1 || loop + 1 === world[i].length
? 2
: (row =
loop === 1 || loop + 2 === world[i].length
? 1
: wallSeed === false
? 2
: 1));
});
}
checkForOrphans();
}
function checkForOrphans() {
for (let i = 0; i < world.length; i++) {
const row = world[i];
//Find a coin(1) with bricks(2) on either side
orphanFinder(row, i);
}
}
function orphanFinder(row, y) {
for (let x = 0; x < row.length; x++) {
//skip first and last two rows for analysis
//skip first two and last two items in row
if (y > 1 && y < row.length - 2 && x > 1 && x < row.length - 2) {
//run position finder to update position object
position = positionDetails(row, y, x);
const sum =
position.up.val +
position.down.val +
position.left.val +
position.right.val;
//if the sum of all the positions is 8, the coin is surrounded
sum > 8 ? (world[y][x] = 2) : null;
}
}
}
function setMediumWalls() {
setLongWalls();
moreRandomBlocks();
checkForOrphans();
}
function setLongWalls() {
const numberAcross = Math.floor(Math.random() * 4) + 1;
const divisor = world.length % 2 === 0 ? 3 : 2;
for (let i = 1; i < world.length; i++) {
world[i] =
i > 1 && i < world.length - 2 && i % divisor === 0
? longWalls(world[i], numberAcross)
: world[i];
}
}
function longWalls(arr, num) {
const wallLength = Math.floor(arr.length / num);
let newRow = [];
for (let i = 1; i < arr.length; i + wallLength) {
const start = i;
const end = i + wallLength;
newRow.push(addBricks(arr.slice(start, end)));
i = end;
}
newRow = newRow.flat();
newRow[0] = 2;
newRow[1] = 1;
newRow[arr.length - 1] = 2;
newRow[arr.length - 2] = 1;
return newRow;
}
function addBricks(arr) {
for (let i = 0; i < arr.length; i++) {
i === arr.length - 1 ? (arr[i] = 1) : (arr[i] = 2);
}
return arr;
}
function moreRandomBlocks() {
for (let y = 0; y < world.length; y++) {
const row = world[y];
if (y > 1 && y < world.length - 1) {
let newRow = [];
for (let x = 0; x < row.length; x++) {
if (x > 1 && x < row.length - 1) {
const position = positionDetails(row, y, x);
//Set a 15% chance of generating a wall seed
const brickPlace = Math.random() > 0.15 ? true : false;
position.focus.val === 1 && position.up.val === 1
? brickPlace === false
? (row[x] = 2)
: row[x]
: null;
}
}
}
}
}
let position = {};
function positionDetails(row, y, x) {
//clear position
position = {};
position.up = {
x: x,
y: y - 1,
val: world[y - 1][x],
};
position.down = {
x: x,
y: y + 1,
val: world[y + 1][x],
};
position.left = {
x: x - 1,
y: y,
val: row[x - 1],
};
position.right = {
x: x + 1,
y: y,
val: row[x + 1],
};
position.focus = {
x: x,
y: y,
val: row[x],
};
return position;
}
function setCherries() {
// Cherries are all ways in the 4 corners
world[1][1] = 5;
world[1][world.length - 2] = 5;
world[world.length - 2][1] = 5;
world[world.length - 2][world.length - 2] = 5;
}
function mapHTML(layer, target) {
let HTML = "";
let ghostCount = 1;
for (let y = 0; y < layer.length; y++) {
HTML += '<div class="row">';
layer[y].map((row, x) => {
row === 1
? (HTML += HTMLS(20, y, x, "coin"))
: row === 2
? (HTML += HTMLS(-1, y, x, "brick"))
: row === 3
? (HTML += HTMLS(null, y, x, null, "pacman", "data-pacman", "right"))
: row === 4
? ((HTML += HTMLS(null, y, x, "ghost", null, "data-ghost", ghostCount)),
ghostCount++)
: row === 5
? (HTML += HTMLS(50, y, x, "cherries"))
: row === 6
? (HTML += HTMLS(null, y, x, null, "twopac", "data-pacman", "left"))
: (HTML += HTMLS(0, y, x));
});
HTML += "</div>";
}
target.innerHTML = HTML;
}
function HTMLS(
score,
y,
x,
elClass,
id = null,
dataArg = null,
dataVal = null
) {
let div = document.createElement("div");
score ? div.setAttribute("data-score", score) : null;
div.setAttribute("data-y", y);
div.setAttribute("data-x", x);
dataArg ? div.setAttribute(dataArg, dataVal) : null;
elClass ? div.classList.add(elClass) : null;
id ? div.setAttribute("id", id) : null;
return div.outerHTML;
}
//Creates layer arrays to "mirror" the world array
function mirrorArray() {
return [...Array(world.length)].flatMap((x) => [
(x = [...Array(world.length)].map((x) => (x = 0))),
]);
}
function generatePacLand() {
// * Create array to match shape of world array
pacmen = mirrorArray();
const available = worldTraverse(pacPlace);
const location = selectLocationRandomly(available);
//place pacman
pacmen[location[0]][location[1]] = 3;
//remove underlying world value
world[location[0]][location[1]] = 0;
players === 2 ? createTwopac() : null;
mapHTML(pacmen, pacLand);
//update world HTML
mapHTML(world, gameBoard);
}
function createTwopac() {
const available = worldTraverse(twoPacPlace);
const location = selectLocationRandomly(available);
//place pacman
pacmen[location[0]][location[1]] = 6;
//remove underlying world value
world[location[0]][location[1]] = 0;
}
function generateGhostWorld(level) {
// * Create array to match shape of world array
ghosts = mirrorArray();
const available = worldTraverse(ghostPlace);
const numGhosts =
level === "easy"
? 2
: level === "medium"
? 3
: level === "hard" || level === "mushrooms"
? 4
: null;
const quarters = quadrants();
// * iterate through quadrant keys (q1,q2 ... )
Object.keys(quadrants()).map((key, i) => {
// * if iteration is less than number of ghosts, create a ghost
i < numGhosts ? setGhostPoint(available, quarters[key]) : null;
});
mapHTML(ghosts, ghostWorld);
}
function setGhostPoint(coordinates, quarter) {
let available = [];
coordinates.map(([y, x], i) =>
y > quarter.yStart &&
y < quarter.yEnd &&
x > quarter.xStart &&
x < quarter.xEnd
? available.push([y, x])
: null
);
const location = selectLocationRandomly(available);
//place pacman
ghosts[location[0]][location[1]] = 4;
}
function possPositions(func) {
let results = [];
let i = 0;
for (let y = 0; y < world.length; y++) {
const row = world[y];
if (y > 1 && y < world.length - 1) {
for (let x = 0; x < row.length; x++) {
if (x > 1 && x < row.length - 1) {
const coordinates = func(row, y, x);
coordinates ? ((results[i] = coordinates), i++) : null;
}
}
}
}
return results.flat();
}
//produces an array of available coordinates
function worldTraverse(func) {
let coordinates = [];
world.map(function (row, y) {
row.map(function (col, x) {
// * y = the row
// * x = column positition
// * y[x] = the cell value
const result = func(y, x, world[y][x]);
result
? coordinates.push(result)
: //console.error("ERROR! check " + func)
null;
});
});
return coordinates;
}
function pacPlace(y, x, val) {
const center = centerPoint();
const range = percentageRange(0.1);
const low = range.low - center.y;
const high = range.high - center.y;
if (y > low && y < high && x > low && x < high && val !== 2) {
return [y, x];
}
}
function pacGamePlayPlace(y, x, val) {
const center = centerPoint();
const range = percentageRange(0.2);
const low = range.low - center.y;
const high = range.high - center.y;
if (y > low && y < high && x > low && x < high && val === 0) {
return [y, x];
}
}
function twoPacPlace(y, x, val) {
const quad = quadrants();
const low = quad.q4.yStart + 2;
const high = quad.q4.yEnd - 6;
if (y > low && y < high && x > low && x < high && val !== 2) {
return [y, x];
}
}
function ghostPlace(y, x, val) {
let valid = 0;
const quarters = quadrants();
const yLow = Math.floor(quarters.q1.yEnd * 0.25),
yHigh = Math.floor(quarters.q4.yEnd * 0.75),
xLow = Math.floor(quarters.q1.xEnd * 0.25),
xHigh = Math.floor(quarters.q4.xEnd * 0.75);
for (let i = 0; i < 4; i++) {
//are coordinates within +/- range of a given quarter center point
i === 0
? y < yLow + 3 && x > xLow - 2 && x < xLow + 3
? valid++
: valid
: //are coordinates within +/-(2) range of q2 center point
i === 1
? y < yLow + 3 && x > xHigh - 2 && x < xHigh + 2
? valid++
: valid
: //are coordinates within +/-(2) range of q3 center point
i === 2
? y > yHigh - 1 && y < yHigh + 3 && x < xLow + 3
? valid++
: valid
: //are coordinates within +/-(2) range of q4 center point
i === 3
? y > yHigh - 1 && y < yHigh + 6 && x > xHigh - 1 && x < xHigh + 3
? valid++
: valid
: //otherwise discard
null;
}
//If the coordinates meet any of the above criteria and are not bricks or twopac, return as valid
if (valid > 0 && val !== 2 && val !== 6) {
return [y, x];
}
}
function mushroomPlace(y, x, val) {
const pac = document.getElementById("pacman");
const pacY = parseInt(pac.dataset.y);
const pacX = parseInt(pac.dataset.x);
const lowY = pacY > 5 ? pacY - 4 : 1;
const highY = pacY > world.length - 5 ? pacY + 4 : world.length - 1;
const lowX = pacX > 5 ? pacX - 4 : 1;
const highX = pacX > world[0].length - 5 ? pacX + 4 : world[0].length - 1;
if (y > lowY && y < highY && x > lowX && x < highX && val !== 2) {
return [y, x];
}
}
function findGhostCoins(y, x, val) {
const el = gameBoard.querySelector(
'[data-y="' + y + '"][data-x="' + x + '"]'
);
const hasCoin = el.classList.contains("coin");
if (val === 0 && hasCoin) {
return [y, x];
}
}
function centerPoint() {
const centralY = Math.floor(world.length * 0.5);
const centralX = Math.floor(world[0].length * 0.5);
return { y: centralY, x: centralX };
}
function quadrants() {
const center = centerPoint();
const quarters = {
q1: { yStart: 0, yEnd: center.y, xStart: 0, xEnd: center.x },
q2: {
yStart: 0,
yEnd: center.y,
xStart: center.x + 1,
xEnd: world[0].length,
},
q3: { yStart: center.y + 1, yEnd: world.length, xStart: 0, xEnd: center.x },
q4: {
yStart: center.y + 1,
yEnd: world.length,
xStart: center.x + 1,
xEnd: world[0].length,
},
};
return quarters;
}
function percentageRange(percentage) {
const range = Math.ceil(world.length * percentage);
return { low: world.length - range, high: world.length + range };
}
function selectLocationRandomly(available) {
return available[Math.floor(Math.random() * available.length)];
}
function setWinningScore() {
const existing = parseInt(
document.querySelector("#score span+span").innerHTML
);
let values = worldTraverse(worldValue);
values = values.map((y) => (y === 1 ? 20 : y === 5 ? 50 : 0));
const sum = values.reduce((b, a) => b + a, 0);
score.winning = existing > 0 ? sum + existing : sum;
}
function worldValue(y, x, val) {
return val === 1 || val === 5 ? val : 0;
}
function runGhosts() {
//clear the interval before starting a new one
window.run ? window.clearInterval(run) : null;
const interval = level === "easy" ? 400 : level === "medium" ? 250 : 150;
window.run = setInterval(function () {
if (gamePlay === false) {
clearInterval(window.run);
} else {
moveGhosts();
}
}, interval);
}
function moveGhosts() {
const ghosts = document.querySelectorAll(".ghost");
for (const ghost of ghosts) {
setCourse(ghost);
}
}
function setCourse(ghost) {
const y = parseInt(ghost.dataset.y);
const x = parseInt(ghost.dataset.x);
const pacLocation = whereIsPacman();
//Get values from adjacent squares
const position = positionDetails(world[y], y, x);
const bestGuess = seekPacman(pacLocation, position);
//Set possible move array
let possibleMoves = [];
//remove possible moves that are not available due to bricks
const obj = Object.entries(position);
for (let i = 0; i < 4; i++) {
const direction = obj[i][0];
const worldVal = obj[i][1].val;
const isGhost = checkGhostWorld(position[direction]);
//remove possible moves where a brick, ghost
worldVal !== 2 && !isGhost ? possibleMoves.push(direction) : null;
}
//Select a move direction at random
const randomMove =
possibleMoves[Math.floor(Math.random() * possibleMoves.length)];
const move = makeDecision(bestGuess, randomMove);
const newCoordinates = position[move];
redrawGhost(ghost, newCoordinates);
}
function whereIsPacman() {
const el = document.getElementById("pacman");
return { y: el.dataset.y, x: el.dataset.x };
}
function seekPacman(pac, surroundings) {
//if Pacman is super, run away
const obj = Object.entries(surroundings);
//create array with y values
const whys = obj.map((y, i) => (y = obj[i][1].y));
const yMove = closest(whys, pac.y);
const yCoordinates = { y: obj[yMove][1].y, x: obj[yMove][1].x };
const exes = obj.map((x, i) => (x = obj[i][1].x));
const xMove = closest(exes, pac.x);
const xCoordinates = { y: obj[xMove][1].y, x: obj[xMove][1].x };
//check to make sure either direction is not a brick or ghost
const direction = moveCheck(yCoordinates)
? //favor y movement
obj[yMove][0]
: obj[xMove][0];
return direction;
}
function moveCheck(move) {
const isGhost = checkGhostWorld(move);
const isBrick = world[move.y][move.x] === 2 ? true : false;
return !isGhost && !isBrick ? true : false;
}
function closest(array, num) {
let i = 0;
let minDiff = 1000;
let ans;
for (i in array) {
const m = Math.abs(num - array[i]);
if (m < minDiff) {
minDiff = m;
//we only want the index because it will match the obj position
ans = i;
}
}
return ans;
}
let decision = 0;
function makeDecision(bestGuess, randomMove) {
const poss =
level === "easy" ? 8 : level === "medium" ? 6 : level === "hard" ? 5 : 4;
decision++;
return decision % poss === 0 ? bestGuess : randomMove;
}
function organizeByCountry(countries) {
return countries.reduce((acc, country) => {
const { countryName, ...rest } = country;
return { ...acc, [countryName]: rest };
}, {});
}
function redrawGhost(el, move) {
updateGhostWorld(el, move);
const killedAPac = pacCollision(move);
//If killdAPac returns three stop the game, otherwise kill twopac and continue
killedAPac ? (killedAPac === 3 ? stopGame(3) : killedATwopac()) : null;
}
function updateGhostWorld(el, move) {
//clear stop class if last move was stopped
el.classList.contains("stop") ? el.classList.remove("stop") : null;
//Every once in a while, stop and look around
const stop = Math.random() > 0.05 ? false : true;
if (stop === false) {
// * remove old position from array
ghosts[el.dataset.y][el.dataset.x] = 0;
//update ghosts array
ghosts[move.y][move.x] = 4;
const ghostType = el.dataset.ghost;
//remove ghost class
el.classList.remove("ghost");
//remove ghost data attributes
delete el.dataset.ghost;
const newPosition = ghostWorld.querySelector(
'[data-y="' + move.y + '"][data-x="' + move.x + '"]'
);
//carry over ghost type data attribute from old position
newPosition.dataset.ghost = ghostType;
//add ghost class name
newPosition.classList.add("ghost");
} else {
el.classList.add("stop");
}
}
function pacCollision(move) {
const pacSpot = pacmen[move.y][move.x];
// IF not super and pacman array element is 3 or 6, return value
return (!isSuper && pacSpot === 3) || pacSpot === 6 ? pacSpot : false;
}
document.onkeydown = checkKey;
let previousDirection;
let timesPushed = 0;
function checkKey(e) {
e = e || window.event;
const pacMoves = [38, 40, 37, 39];
const isPacman = pacMoves.includes(e.keyCode);
const twoPacMoves = [87, 83, 65, 68];
let isTwopac = twoPacMoves.includes(e.keyCode);
//Don't return true if game is single player
isTwopac = players === 2 ? isTwopac : false;
//select HTML element to move based on truthy-ness of includes method above
const el = isPacman
? document.getElementById("pacman")
: isTwopac
? document.getElementById("twopac")
: null;
const direction = isPacman
? e.keyCode == "38"
? "up"
: e.keyCode == "40"
? "down"
: e.keyCode == "37"
? "left"
: e.keyCode == "39"
? "right"
: null
: isTwopac
? e.keyCode == "87"
? "up"
: e.keyCode == "83"
? "down"
: e.keyCode == "65"
? "left"
: e.keyCode == "68"
? "right"
: null
: null;
direction === previousDirection
? timesPushed++
: ((previousDirection = direction), (timesPushed = 0));
gamePlay && direction ? movePacmen(direction, el) : null;
}
function movePacmen(direction, el) {
// change data pacman to "animate" direction
el.dataset.pacman = direction;
// * get character's initial position
const y = parseInt(el.dataset.y);
const x = parseInt(el.dataset.x);
// * get surrounding values
const position = positionDetails(world[y], y, x);
// * select value of desired move
const desiredMove = position[direction];
// * set boolean depending on whether value is 2
const moveOK = determineMoveOkayness(position, desiredMove);
// * if ok, redraw pacman or twopac
moveOK
? redrawPacmen(el, position, position[direction], direction)
: timesPushed < 100
? // * otherwise animate bump
(playAudio("wallbump.mp3"),
animateBump(el, position[direction]),
getCoins(direction, position))
: (destroyBricks(
position[direction].y,
position[direction].x,
position[direction].val
),
(timesPushed = 0));
}
function redrawPacmen(el, position, move, direction) {
//False means character is twopac
const isPacman = el.id === "pacman";
//3 = Pacman, 6 = Twopac
const character = isPacman ? 3 : 6;
//update the PacLand array
pacMove(character, move, direction, el);
!isSuper
? normalConsumption(isPacman, move)
: superConsumption(move, position);
}
function normalConsumption(isPacman, move) {
const worldValue = world[move.y][move.x];
//If new position is a coin...
/*
* Update score by 20 points
* Remove coin class & add empty
*/
worldValue === 1
? (updateScore(20), munchModulo(), updateWorld(move, 0))
: //If new position is a Cherry...
/*
* Update score by 50 points
* Remove cherries class & add empty
*/
worldValue === 5
? (updateScore(50), playAudio("eat_fruit.wav"), updateWorld(move, 0))
: worldValue === 7
? initSuperPac()
: null;
const ghostValue = ghosts[move.y][move.x];
//If new position is a Ghost...
/*
* STOP THE GAME
*/
ghostValue === 4 ? (isPacman ? stopGame(3) : killedATwopac()) : null;
}
function superConsumption(move, position) {
const surroundings = describeAllBlocks(position);
for (const [key, value] of Object.entries(surroundings)) {
const y = value.y;
const x = value.x;
const val = value.val;
destroyBricks(y, x, val);
eatStuff(value);
}
}
function destroyBricks(y, x, val) {
// Don't destroy outer bricks
if (
y === 0 ||
x === 0 ||
x === world[0].length - 1 ||
y === world.length - 1
) {
return;
}
if (val === 2) {
// select brick
const brick = gameBoard.querySelector(
'[data-y="' + y + '"][data-x="' + x + '"]'
);
//remove brick from world array
world[y][x] = 0;
updateScore(5);
//TODO: work on animation
brick.classList.add("explode");
playAudio("break.wav");
setTimeout(() => {
brick.classList.remove("explode", "brick");
}, 100);
}
}
function eatStuff(move) {
const isGhost = checkGhostWorld(move);
//eat coins and update score
move.val === 1
? (updateScore(20), updateWorld(move, 0))
: move.val === 5
? (updateScore(50), playAudio("eat_fruit.wav"), updateWorld(move, 0))
: isGhost
? (eatGhost(move), updateScore(70))
: null;
}
function removeGhostCoins() {
const ghostCoins = worldTraverse(findGhostCoins);
for (let i = 0; i < ghostCoins.length; i++) {
const el = gameBoard.querySelector(
'[data-y="' + ghostCoins[i][0] + '"][data-x="' + ghostCoins[i][1] + '"]'
);
el.className = "";
}
}
function checkGhostWorld(move) {
const ghostSpot = ghosts[move.y][move.x];
return ghostSpot === 4 ? true : false;
}
function eatGhost(move) {
playAudio("eat_ghost.wav");
//remove from ghost array
ghosts[move.y][move.x] = 0;
//remove from Ghost HTML
const ghost = ghostWorld.querySelector(
'[data-y="' + move.y + '"][data-x="' + move.x + '"]'
);
ghost.className = "";
delete ghost.dataset.ghost;
}
function determineMoveOkayness(position, move) {
//normal pac can't move through bricks
let result = !isSuper ? move.val !== 2 : false;
if (isSuper) {
//if super pac runs into an outer wall, return false (can't move)
//otherwise they can run through bricks;
result =
move.y === 0 ||
move.x === 0 ||
move.x === world[0].length - 1 ||
move.y === world.length - 1
? false
: true;
}
return result;
}
function describeAllBlocks(position) {
/* ALL BLOCKS OBJ
* p1 p2 p3 *
* p4 😐 p5 *
* p6 p7 p8 *
*/
const allBlocks = {
p1: {
x: position.up.x - 1,
y: position.up.y,
val: world[position.up.x - 1][position.up.y],
},
p2: position.up,
p3: {
x: position.up.x + 1,
y: position.up.y,
val: world[position.up.x + 1][position.up.y],
},
p4: position.left,
p5: position.right,
p6: {
x: position.down.x - 1,
y: position.down.y,
val: world[position.down.x - 1][position.down.y],
},
p7: position.down,
p8: {
x: position.down.x + 1,
y: position.down.y,
val: world[position.down.x + 1][position.down.y],
},
};
return allBlocks;
}
function animateBump(el, obj) {
!isSuper ? el.classList.add("bump") : null;