-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js (Pikachu 2048)
606 lines (501 loc) · 19.4 KB
/
script.js (Pikachu 2048)
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
// global variables, used by multiple objects/functions
// created on start, required for onclick reference
var gameboard = undefined
// the game is not playing right now
var playing = false
// score variable, all tiles must be able to access
var score = 0
// access strings for each pikachu picture, from smallest to largest value
const pikachus = ['small-santa', 'small-witch', 'small-party', 'medium-santa', 'medium-witch', 'medium-party', 'medium-flower', 'medium-detective', 'large-santa', 'large-witch', 'large-party', 'large-flower', 'large-detective']
// variables for swiping
// where a touch started
var lastTouch = [0, 0]
// if swiping is enabled
var swipeEnabled = false
// Tile class: used by the Board class
class Tile {
// a new Tile needs to know where it is
constructor(position) {
this.position = position
// tiles start with either a value of 2 or 4
this.value = (random(1) + 1) * 2
}
// method to return the type of collision it has with another tile, if at all
// MEANING OF RETURN CODES
// 0: this tile is myself
// 1: bumped into a tile of the same value, other tile's value is boosted
// 2: bumped into a tile of different value
// 3: did not bump into anything
collide(tile) {
// first, check if the tile is the same
if (tile === this) {
return 0
}
// then, check is the two (different) tiles have the same position (i.e. were moved on each other)
if (arraysEqual(tile.getPosition(), this.position)) {
// if so, check if the tiles have the same value
if (tile.getValue() === this.value) {
// if so, increment score and the other tile's value
score += this.value + tile.getValue()
tile.setValue(this.value + tile.getValue())
document.getElementById('score').innerHTML = 'Score: ' + score
return 1
}
// otherwise, this is a different-value tile
else {
return 2
}
}
// no collision at all
return 3
}
// method for a tile to check if it is off the board
offBoard(width, height) {
// if off any side (compare own position against inputted width and height of board)
if (this.position[0] < 0 || this.position[1] < 0 || this.position[0] > height - 1 || this.position[1] > width - 1) {
return true
}
else {
return false
}
}
// method to move a tile a specified amount
move(direction) {
this.position[0] += direction[0]
this.position[1] += direction[1]
}
// method to make the tile show up, with a pikachu picture dependant on its value
display(board) {
board.cells[this.position[0]][this.position[1]].innerHTML = '<img src="images/' + pikachus[Math.log2(this.value) - 1] + '.png">'
}
// method to un-display a tile
clear(board) {
board.cells[this.position[0]][this.position[1]].innerHTML = ' '
}
// various getters and setters, needed for Tile or Board methods
// the position-setting function only sets one index at a time, so it needs the new position and its index
setPosition(index, position) {
// if the index given is not available, do not write the given position value
if (index >= this.position.length) {
return false
}
this.position[index] = position
}
getPosition() {
return this.position
}
setValue(value) {
this.value = value
}
getValue() {
return this.value
}
}
// Board class: contains all methods needed to play the game, except ones dependant on ouside input (i.e. keyboard)
class Board {
// a new Board need know nothing
constructor() {
// prepare the playing field (board) which the tiles will be on
this.cells = this.setUpBoard()
// the tiles that the board will use in play
this.tiles = []
// the highest value attained by the player
this.highestValue = 0
}
// method to prepare an array containing all the tds in the table, organized by their trs
setUpBoard() {
// clear the array
let board = []
for (let i = 0, rows = document.getElementsByTagName('TR'); i < rows.length; i++) {
// start the array for this row
let row = []
for (let j = 0, boxes = rows[i].getElementsByTagName('TD'); j < boxes.length; j++) {
// add the individual cell to this row's array
row.push(boxes[j])
}
// add this row's array to the master 'cells' array
board.push(row)
}
return board
}
// method to start a game
start() {
// a game starts with two tiles
this.newTile()
this.newTile()
// note the highest value present
this.highestValue = Math.max(this.tiles[0].getValue(), this.tiles[1].getValue())
// this means that keyboard inputs will be recognized
playing = true
// reset the gameboard background to indicate that the game is currently active
document.getElementsByTagName('table')[0].style.backgroundColor = 'white'
}
// method to check if a new tile overlaps an already-existing one
// cannot use collide() because if the new tile overlaps one with the same value,
// // it shouldn't change the existing tile's value, and must check all tiles at once
overlap(position) {
// check each tile in the Board's list of tiles (which at this point does not include the tile)
for (let i = 0; i < this.tiles.length; i++) {
// if the tiles share a position
if (arraysEqual(position, this.tiles[i].getPosition()) === true) {
return true
}
}
// if the method gets to here, the new tile does not overlap any existing tiles
return false
}
// method to make a random new tile appear
newTile() {
// variables noting size of the board for easy access
let w = this.cells[0].length
let h = this.cells.length
// as long as there is space
if (this.tiles.length < w * h) {
// generate a new tile
let tile = new Tile([random(h - 1), random(w - 1)])
// if this tile is where another tile already is
while (this.overlap(tile.getPosition()) === true) {
// generate a new tile, repeat
tile = new Tile([random(h - 1), random(w - 1)])
}
// show the new tile, and add it to the master array
tile.display(this)
this.tiles.push(tile)
}
// if there is not enough space on the board
else {
return false
}
}
// method to sort all tiles so that most 'extreme' tiles are first in a list
// 'extreme': furthest in the direction to be moved
// WHAT INPUTS DO/MEAN
// isHorizontal: if 1, will sort in a horizontal paridigm, if 0 will sort vertically
// direction: if 1 will go right->left, down->up
sort(isHorizontal, direction) {
// initialize return variable
let sorted = []
// for 0->3 or 3->0, the current extreme number that tiles are being checked for
for (let i = (1.5 + (1.5 * direction)); i !== (1.5 - (2.5 * direction)); i -= direction) {
// check each tile
for (let j = 0; j < this.tiles.length; j++) {
// if this tile is in the row/column currently being checked for, add it to the back of the list
if (this.tiles[j].getPosition()[isHorizontal] === i) {
sorted.push(this.tiles[j])
}
}
}
return sorted
}
// method to move a single given tile in a given direction
moveTile(tile, direction) {
// variable that can be changed at any point to 'true' to note that tile is done moving
let done = false
// move the tile
tile.move(direction)
// if the tile was moved off the board
if (tile.offBoard(this.cells.length, this.cells[0].length) === true) {
// move it back and note that the tile is done moving
tile.move([-direction[0], -direction[1]])
done = true
}
// check each other tile to see if the current tile bumped into it
for (let i = 0; i < this.tiles.length && done === false; i++) {
// run the collide method and store what it returns
let collide = tile.collide(this.tiles[i])
// if the tile bumped into another of the same value
if (collide === 1) {
// if the new tile has a new highest value
if (tile.getValue() * 2 > this.highestValue) {
// record it in the score area and for the Board
this.highestValue = tile.getValue() * 2
document.getElementById('score').innerHTML = 'You got to ' + this.highestValue + '!'
}
// remove the tile from the Board's master list of tiles, and note that it is done moving
this.tiles.splice(this.tiles.findIndex(function(check) {return check === tile}), 1)
done = true
}
// if the tile bumped into another of a different value
if (collide === 2) {
// move the tile backwards and note that it is done moving
tile.move([-direction[0], -direction[1]])
done = true
}
}
// return whether this tile is donw moving or not
return done
}
// method to return a tile at a certain position
getTileWithPosition(position) {
// check each tile
for (let i = 0; i < this.tiles.length; i++) {
// if it is in the desired position, return it
if (arraysEqual(this.tiles[i].getPosition(), position) === true) {
return this.tiles[i]
}
}
// otherwise, no tile is in the inputted position
return false
}
// method to check if there is a move available, only called when the board is full
movesAvailable() {
// checking for possible horizontal moves
// check each row
for (let i = 0; i < this.cells.length; i++) {
// check each column excluding the last one
for (let j = 0; j < this.cells[i].length - 1; j++) {
// checks a tile in the row & column specified, and then the one in the row specified and next column
// if the two tiles next to each other in this row have the same value
if (this.getTileWithPosition([i, j]).getValue() === this.getTileWithPosition([i, j + 1]).getValue()) {
// note that move horizontally is possible
return 'horizontal'
}
}
}
// checking for possible veritical moves
// check each column
for (let i = 0; i < this.cells[0].length; i++) {
// check each row excluding the last one
for (let j = 0; j < this.cells.length - 1; j++) {
// checks a tile in the row & column specified, and then the one in the next row and the column specified
// if the two tiles next to each other in this column have the same value
if (this.getTileWithPosition([j, i]).getValue() === this.getTileWithPosition([j + 1, i]).getValue()) {
// note that move horixontally is possible
return 'vertical'
}
}
}
// if the method is at this point, no moves are possible
return false
}
// method to move all tiles in a direction inputted by user
move(direction) {
// store the current positions of all of the tiles
let oldPos = this.getPositions()
// reset the hint arrows if they are showing
document.getElementById('hint').style.display = 'none'
// first, clear all tiles to remove imprints
for (let i = 0; i < this.tiles.length; i++) {
this.tiles[i].clear(this)
}
// initialize an array that will hold all the tiles sorted by 'extreme'ness
let sorted = []
// if the direction moving is horizontal, note that in the sort call
if (direction[0] === 0) {
sorted = this.sort(1, direction[1])
}
// likewise for verical movement
else {
sorted = this.sort(0, direction[0])
}
// while there are some tiles that have not completed moving
while (sorted.length > 0) {
// move most extreme tile, then if the tile is done moving, delete it from the list of active tiles
// reasons to be deleted: moving would go off board or colliding with another tile
// reasons to not be deleted: moving went to an empty space
// if not deleted, then the tile will be selected again
// // (still the front of the list) and repeat this whole process over again
if (this.moveTile(sorted[0], direction) === true) {
sorted.shift()
}
}
// once all tiles have moved, display all of them again
for (let i = 0; i < this.tiles.length; i++) {
this.tiles[i].display(this)
}
// if there is no room left on the board
if (this.tiles.length === this.cells.length * this.cells[0].length) {
// check if there are moves available
let avail = this.movesAvailable()
// if no moves are available
if (avail === false) {
// stop accepting move inputs and change the score to signify that
playing = false
document.getElementById('score').innerHTML = 'Congratulations, your score is ' + score
// change the gameboard to a gray background to give a visual signal
document.getElementsByTagName('table')[0].style.backgroundColor = 'lightgray'
}
// or if there are moves available
else {
// display the proper arrow
document.getElementById('hint').src = 'images/arrows-' + avail + '.png'
document.getElementById('hint').style.display = 'inline'
}
}
// if the tiles have moved
// /// (this would not trigger if the board is full, but the if statement above covers that case)
if (arraysEqual(oldPos, this.getPositions()) === false) {
// generate a new tile
this.newTile()
}
}
// method to return the position of every tile on the board
getPositions() {
// initialize return varaible
let positions = []
// for each tile on the board, add its position to the return variable
for (let i = 0; i < this.tiles.length; i++) {
// must give single values because arrays are only ever a reference, not original
positions.push([this.tiles[i].getPosition()[0], this.tiles[i].getPosition()[1]])
}
return positions
}
// method to clear and reset all tiles
clear() {
// delete all pictures from the board
for (let i = 0, n = gameboard.tiles.length; i < n; i++) {
gameboard.tiles[i].clear(gameboard)
}
// reset the Board's list of tiles
this.tiles = []
}
}
// function to give a random integer between 0 and a max number
function random(max) {
return Math.floor(Math.random() * (max + 1))
}
// function to check if two arrays are equal to each other (this cannot be done with simple '=' because arrays are objects)
function arraysEqual(arr1, arr2) {
// first check if the arrays are the same length - if not, then automatically not equal
if (arr1.length != arr2.length) {
return false
}
// then, check each element in the arrays for sameness
for (let i = 0; i < arr1.length; i++) {
// if the current element is an array
if (Array.isArray(arr1[i]) === true) {
// check if the corresponding element for array-ness, then recursive call to check if the two arrays are equal
if (Array.isArray(arr2[i]) === false || arraysEqual(arr1[i], arr2[i]) === false) {
return false
}
}
// or just check is the single value is the same
else if(arr1[i] !== arr2[i]) {
return false
}
}
// if all conditions have been met, then these arrays are equal
return true
}
// function to prepare the dictionary of pikachus
// I could have coded this in HTML, but I'm too lazy
function makeDict() {
// save the dictionary div for easy reference
let dict = document.getElementById('dict')
// for each pikachu
for (let i = 0; i < pikachus.length; i++) {
// add to the dictionary a div with the pikachu image and the calculated value
dict.innerHTML += '<div><img src="images/' + pikachus[i] + '.png"><p>' + Math.pow(2, i + 1) + '</p></div>'
}
}
// onclick function for the reset button
var reset = function() {
// reset the board
gameboard.clear()
// reset the score
score = 0
document.getElementById('score').innerHTML = 'Score: ' + score
// start a new game
gameboard.start()
}
// onclick function for the enable/disable swiping toggle button
var enableSwipe = function() {
// check the current state and change it to the opposite one
if (this.innerHTML === 'Enable Swiping') {
// enables swiping
swipeEnabled = true
this.innerHTML = 'Disable Swiping'
}
else if (this.innerHTML === 'Disable Swiping') {
// disables swiping
swipeEnabled = false
this.innerHTML = 'Enable Swiping'
}
}
// onlick function for the show/hide dictionary toggle button
var showDict = function() {
// check the current state and change it to the opposite one
if (this.innerHTML === 'Show Pikachu Dictionary') {
// shows the dictionary
document.getElementById('dict').style.display = 'block'
this.innerHTML = 'Hide Pikachu Dictionary'
}
else if (this.innerHTML === 'Hide Pikachu Dictionary') {
// hides the dictionary
document.getElementById('dict').style.display = 'none'
this.innerHTML = 'Show Pikachu Dictionary'
}
}
// when a key is pressed, this function runs
// onkeydown() is used rather than onkeypress() because arrow keys are needed
window.onkeydown = function(event) {
// check if the game is currently in session
if (playing === true) {
// save the key pressed in a shorter reference variable
let key = event.key
// call move() with the proper argument depending on the key pressed
if (key === 'ArrowUp' || key === 'w' || key === 'W') {
gameboard.move([-1, 0])
}
if (key === 'ArrowDown' || key === 's' || key === 'S') {
gameboard.move([1, 0])
}
if (key === 'ArrowRight' || key === 'd' || key === 'D') {
gameboard.move([0, 1])
}
if (key === 'ArrowLeft' || key === 'a' || key === 'A') {
gameboard.move([0, -1])
}
}
}
// when a key is pressed, this listener activates
window.addEventListener('keydown', function(event) {
// reference variable
let key = event.key
// if the game is currently in session and an up/down arrow key was pressed
if(playing === true && (key === 'ArrowDown' || key === 'ArrowUp')) {
// prevent the window from scrolling during play
event.preventDefault();
}
}, false)
// when a touch is detected to have started, this listener activates
window.addEventListener('touchstart', function(event) {
// if swiping is enabled
if (swipeEnabled === true) {
// save the position that the swipe starts at
lastTouch = [event.changedTouches[0].pageX, event.changedTouches[0].pageY]
}
}, false)
// when a touch is detected to have ended, this listener activates
window.addEventListener('touchend', function(event) {
// if swiping is enabled
if (swipeEnabled === true) {
// reference variable for the vector (x and y movement) of the swipe
let movement = [lastTouch[0] - event.changedTouches[0].pageX, lastTouch[1] - event.changedTouches[0].pageY]
// if there is significant movement in one direction and not the other, call move() with the proper arguments
if (movement[1] > 50 && Math.abs(movement[0]) < 50) {
gameboard.move([-1, 0])
}
else if (movement[1] < -50 && Math.abs(movement[0]) < 50) {
gameboard.move([1, 0])
}
else if (movement[0] < -50 && Math.abs(movement[1]) < 50) {
gameboard.move([0, 1])
}
else if (movement[0] > 50 && Math.abs(movement[1]) < 50) {
gameboard.move([0, -1])
}
}
}, false)
// when the page loads, this function runs
window.onload = function() {
// make a new gameboard, and have it start the game
gameboard = new Board()
gameboard.start()
// prepare the pikachu dictionary
makeDict()
// set onclick for the buttons
document.getElementById('reset').onclick = reset
document.getElementById('enable-swipe').onclick = enableSwipe
document.getElementById('show-dict').onclick = showDict
}