-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
575 lines (513 loc) · 15.1 KB
/
index.html
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
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>2048</title>
<link rel="icon" type="image/x-icon" href="https://play2048.co/favicon.ico">
<style>
* {
box-sizing: border-box;
}
body {
margin: 0;
padding: 0;
font-family: "Clear Sans", "Helvetica Neue", Arial, sans-serif;
background: #faf8ef;
}
.container {
display: flex;
align-items: center;
flex-direction: column;
height: 100vh;
gap: 8px;
width: 500px;
margin: 0 auto;
padding-top: 32px;
}
.game-over {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgb(238 228 218 / 73%);
display: flex;
opacity: 0;
transition: opacity 500ms ease-out 750ms;
justify-content: center;
align-items: center;
flex-direction: column;
gap: 16px;
z-index: 2;
}
.game-over h2 {
font-size: 48px;
color: #776e65;
margin: 0;
}
.restart {
padding: 8px 16px;
background-color: #8f7a66;
color: #f9f6f2;
border: none;
border-radius: 4px;
font-size: 18px;
font-weight: bold;
cursor: pointer;
}
.restart:hover {
background-color: #9c8774;
}
.restart:focus {
outline: none;
}
.header {
display: flex;
flex-direction: column;
gap: 24px;
width: 500px;
}
.header--top {
display: flex;
justify-content: space-between;
align-items: flex-end;
width: 100%;
}
.title {
font-size: 72px;
color: #776e65;
margin: 0;
}
.subtitle {
font-size: 18px;
color: #776e65;
}
.scores {
display: flex;
gap: 8px;
flex-wrap: wrap;
}
.scores > * {
display: flex;
flex-direction: column;
font-size: 14px;
font-weight: bold;
background-color: #bbada0;
padding: 8px 16px 2px;
color: #ebe4da;
text-align: center;
border-radius: 6px;
text-transform: uppercase;
flex-grow: 1;
}
.scores > * > span {
font-weight: bold;
font-size: 24px;
color: #ffffff;
}
.game-container {
width: 500px;
height: 500px;
padding: 16px;
background-color: #bbada0;
border-radius: 6px;
user-select: none;
position: relative;
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 16px;
}
.blank-tile {
background-color: #cdc1b4;
border-radius: 4px;
gap: 16px;
}
.cell {
position: absolute;
width: 105px;
height: 105px;
background-color: #eee4da;
border-radius: 4px;
display: flex;
justify-content: center;
align-items: center;
transition: left 100ms ease-out, top 100ms ease-out, scale 200ms ease-out 100ms, opacity 0ms ease-out 100ms;
font-weight: bold;
}
.garbage {
transition: left 100ms ease-out, top 100ms ease-out, scale 200ms ease-out 100ms, opacity 0ms ease-out 100ms;
}
.upgrade {
animation: bump 150ms ease-in-out 100ms;
}
@keyframes bump {
0% {
transform: scale(1.0)
}
50% {
transform: scale(1.2)
}
100% {
transform: scale(1.0)
}
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<div class="header--top">
<div class="header--left">
<h1 class="title">2048</h1>
<span class="subtitle">Join the tiles, get <strong>2048!</strong></span>
</div>
<div class="header--right">
<button class="restart">New game</button>
</div>
</div>
<div class="scores">
<div>Time <span id="timeValue">00:00</span></div>
<div>Moves <span id="movesValue">0</span></div>
<div>Tiles <span id="tilesValue">0</span></div>
<div>Score <span id="scoreValue">0</span></div>
<div>Best <span id="bestValue">0</span></div>
</div>
</div>
<div class="game-container">
<div class="game-over">
<h2>Game over!</h2>
<button class="restart">Try again</button>
</div>
</div>
</div>
<script>
const bgColours = {
2: '#eee4da',
4: '#ede0c8',
8: '#f2b179',
16: '#f59563',
32: '#f67c5f',
64: '#f65e3b',
128: '#edcf72',
256: '#edcc61',
512: '#edc850',
1024: '#edc53f',
2048: '#edc22e',
};
const fgColours = {
2: '#776e65',
4: '#776e65',
8: '#f9f6f2',
16: '#f9f6f2',
32: '#f9f6f2',
64: '#f9f6f2',
128: '#f9f6f2',
256: '#f9f6f2',
512: '#f9f6f2',
1024: '#f9f6f2',
2048: '#f9f6f2',
};
const fontSizes = {
2: '52px',
4: '52px',
8: '52px',
16: '52px',
32: '52px',
64: '52px',
128: '44px',
256: '44px',
512: '44px',
1024: '38px',
2048: '38px',
};
// Fill the game container with blank tiles
const gameContainer = document.querySelector('.game-container');
const scoreContainer = document.querySelector('#scoreValue');
const bestContainer = document.querySelector('#bestValue');
const movesContainer = document.querySelector('#movesValue');
const tilesContainer = document.querySelector('#tilesValue');
const timeContainer = document.querySelector('#timeValue');
const gameOverContainer = document.querySelector('.game-over');
let best = localStorage.getItem('best') || 0;
bestContainer.textContent = best;
for (let i = 0; i < 16; i++) {
const blankTile = document.createElement('div');
blankTile.classList.add('blank-tile');
gameContainer.appendChild(blankTile);
}
let startTime = null;
let endTime = null;
let interval = null;
let score = 0;
let movesCount = 0;
let tilesCount = 0;
const cells = new Array(16).fill(null);
const cellElems = new Array(16).fill(null);
function restartGame() {
clearInterval(interval)
displayTime(0, 0)
localStorage.removeItem('currentGame')
for (let i = 0; i < 16; i++) {
const el = cellElems[i]
if (el) {
el.remove()
}
}
cells.fill(null)
cellElems.fill(null)
score = 0
movesCount = 0
tilesCount = 0
scoreContainer.textContent = score
movesContainer.textContent = movesCount
tilesContainer.textContent = tilesCount
startTime = null
endTime = null
timeContainer.textContent = '00:00'
gameOverContainer.style.transition = 'unset'
gameOverContainer.style.opacity = '0'
gameOverContainer.offsetHeight;
gameOverContainer.style.transition = null
spawnRandomTiles(2)
}
document.querySelectorAll('.restart').forEach((el) => {
el.addEventListener('click', restartGame)
})
const spawnRandomTiles = (n) => {
for (let i = 0; i < n; i++) {
const val = Math.random() > 0.9 ? 4 : 2
// Collect up all the empty cells;
const empty = cells
.map((value, index) => ({index, value}))
.filter((e) => !e.value)
const index = empty[Math.floor(Math.random() * empty.length)].index;
const x = index % 4;
const y = Math.floor(index / 4);
const el = document.createElement('div')
el.classList.add("cell", "spawning")
el.textContent = `${val}`
el.style.left = `${x * 105 + (x + 1) * 16}px`;
el.style.top = `${y * 105 + (y + 1) * 16}px`;
el.style.scale = '0';
el.style.color = fgColours[val];
el.style.backgroundColor = bgColours[val];
el.style.fontSize = fontSizes[val];
cells[index] = val
cellElems[index] = el
gameContainer.appendChild(el)
el.offsetHeight;
el.style.scale = '1';
}
}
function displayTime(startTime, endTime) {
const elapsed = endTime - startTime
const minutes = Math.floor(elapsed / 60000)
const seconds = Math.floor((elapsed % 60000) / 1000)
timeContainer.textContent = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
}
function storeCurrentGame() {
localStorage.setItem('currentGame', JSON.stringify({
cells,
score,
movesCount,
tilesCount,
startTime,
endTime: Date.now(),
}))
}
const currentGame = JSON.parse(localStorage.getItem('currentGame'))
if (currentGame) {
score = currentGame.score
movesCount = currentGame.movesCount
tilesCount = currentGame.tilesCount
scoreContainer.textContent = score
movesContainer.textContent = movesCount
tilesContainer.textContent = tilesCount
startTime = Date.now() - (currentGame.endTime - currentGame.startTime)
displayTime(startTime, Date.now())
interval = setInterval(() => {
displayTime(startTime, Date.now())
storeCurrentGame()
}, 250)
for (let i = 0; i < currentGame.cells.length; i++) {
const val = currentGame.cells[i]
if (!val)
continue
const x = i % 4;
const y = Math.floor(i / 4);
const el = document.createElement('div')
el.classList.add("cell")
el.textContent = `${val}`
el.style.left = `${x * 105 + (x + 1) * 16}px`;
el.style.top = `${y * 105 + (y + 1) * 16}px`;
el.style.color = fgColours[val];
el.style.backgroundColor = bgColours[val];
el.style.fontSize = fontSizes[val];
cells[i] = val
cellElems[i] = el
gameContainer.appendChild(el)
}
} else {
spawnRandomTiles(2)
}
function handlePlay(indices) {
let garbage = document.querySelectorAll(".garbage")
for (let el of garbage) {
el.remove()
}
let moved = false;
let scoreChange = 0;
for (let i = 0; i < 16; i += 4) {
let edge = 0
let didMerge = false;
for (let j = i; j < i + 4; j++) {
const index = indices[j];
if (cells[index] === null)
continue
let edgeIndex = indices[i + edge];
let isMerge = false
if (j % 4 !== 0 && edge > 0 && cells[index] === cells[indices[i + edge - 1]] && !didMerge) {
edgeIndex = indices[i + edge - 1]
isMerge = true
}
if (edgeIndex === index) {
edge++
continue
}
moved = true
// get the element for the cell that's amount to move
const movingEl = cellElems[index];
movingEl.style.transition = 'unset';
movingEl.offsetHeight;
movingEl.style.transition = null;
movingEl.offsetHeight;
// Figure out the position it's going to move to
const x = edgeIndex % 4;
const y = Math.floor(edgeIndex / 4)
movingEl.style.top = `${y * 105 + (y + 1) * 16}px`
movingEl.style.left = `${x * 105 + (x + 1) * 16}px`
if (isMerge) {
movingEl.classList.add("garbage")
movingEl.style.opacity = '0'
const edgeEl = cellElems[edgeIndex]
edgeEl.classList.add("garbage")
edgeEl.style.opacity = '0'
edgeEl.style.zIndex = '1'
let val = cells[index] * 2
const upgradeEl = document.createElement('div')
upgradeEl.classList.add("cell", "upgrade")
upgradeEl.textContent = `${val}`
upgradeEl.style.left = `${x * 105 + (x + 1) * 16}px`;
upgradeEl.style.top = `${y * 105 + (y + 1) * 16}px`;
upgradeEl.style.opacity = '0';
upgradeEl.style.color = fgColours[val];
upgradeEl.style.backgroundColor = bgColours[val];
upgradeEl.style.fontSize = fontSizes[val];
gameContainer.appendChild(upgradeEl)
upgradeEl.offsetHeight;
upgradeEl.style.opacity = '1';
cells[edgeIndex] = val
cells[index] = null
cellElems[edgeIndex] = upgradeEl
cellElems[index] = null;
didMerge = true
scoreChange += val
tilesCount++
tilesContainer.textContent = tilesCount
} else {
cells[edgeIndex] = cells[index]
cells[index] = null
cellElems[edgeIndex] = cellElems[index]
cellElems[index] = null
didMerge = false
}
if (!isMerge) {
edge++
}
}
}
return {moved, scoreChange}
}
function isGameOver() {
for (let i = 0; i < 16; i++) {
if (cells[i] === null)
return false
if (i % 4 !== 3 && cells[i] === cells[i + 1])
return false
if (i < 12 && cells[i] === cells[i + 4])
return false
}
return true
}
document.addEventListener('keydown', function (ev) {
let indices = [];
switch (ev.key) {
case "ArrowLeft":
for (let row = 0; row < 4; row++) {
for (let col = 0; col < 4; col++) {
indices.push(row * 4 + col)
}
}
break
case "ArrowRight":
for (let row = 0; row < 4; row++) {
for (let col = 3; col >= 0; col--) {
indices.push(row * 4 + col)
}
}
break
case "ArrowUp":
for (let col = 0; col < 4; col++) {
for (let row = 0; row < 4; row++) {
indices.push(row * 4 + col)
}
}
break
case "ArrowDown":
for (let col = 0; col < 4; col++) {
for (let row = 3; row >= 0; row--) {
indices.push(row * 4 + col)
}
}
break
}
if (indices.length !== 16)
return
const {moved, scoreChange} = handlePlay(indices)
if (moved) {
spawnRandomTiles(1)
movesCount++
movesContainer.textContent = movesCount
if (startTime === null) {
startTime = Date.now()
interval = setInterval(() => {
displayTime(startTime, Date.now())
storeCurrentGame()
}, 250)
}
if (isGameOver()) {
clearInterval(interval)
endTime = Date.now()
displayTime(startTime, endTime)
gameOverContainer.style.opacity = '1'
localStorage.removeItem('currentGame')
} else {
storeCurrentGame()
}
}
if (scoreChange) {
score += scoreChange
scoreContainer.textContent = score
if (score > best) {
best = score
bestContainer.textContent = best
localStorage.setItem('best', best)
}
}
})
</script>
</body>
</html>