-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2048.html
621 lines (596 loc) · 21.4 KB
/
2048.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
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
<!DOCTYPE html>
<html lang="ko">
<head>
<link rel="apple-touch-icon" sizes="57x57" href="./apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="./apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="./apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="./apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="./apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="./apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="./apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="./apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="./apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="./android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="./favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="./favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="./favicon-16x16.png">
<link rel="manifest" href="./manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="./ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<meta charset="UTF-8">
<title>2048</title>
<style>
body { overscroll-behavior-y: none; }
#table { border-collapse: collapse; user-select: none; }
#table td {
border: 10px solid #bbada0; width: 116px; height: 128px;
font-size: 50px; font-weight: bold; text-align: center;
}
#score { user-select: none; }
.color-2 { background-color: #eee4da; color: #776e65;}
.color-4 { background-color: #eee1c9; color: #776e65;}
.color-8 { background-color: #f3b27a; color: 'white';}
.color-16 { background-color: #f69664; color: 'white';}
.color-32 { background-color: #f77c5f; color: 'white';}
.color-64 { background-color: #f75f3b; color: 'white';}
.color-128 { background-color: #edd073; color: #776e65;}
.color-256 { background-color: #edcc62; color: #776e65;}
.color-512 { background-color: #edc950; color: #776e65;}
.color-1024 { background-color: #edc53f; color: #776e65;}
.color-2048 { background-color: #edc22e; color: #776e65;}
</style>
</head>
<body>
<table id="table"></table>
<div>
<span id="score">0</span>
<button id="back">되돌리기</button>
<span id="how_many_remain">3회 남음</span>
<button id="Fail">포기하기</button>
<button id="record">기록하기</button>
<span id="information"></span>
<div id="NotWorkGroup"></div>
<br> <button id="btnup">⇧</button><br><button id="btnlt">⇦</button><button id="btndn">⇩</button><button id="btnrt">⇨</button></div>
<script>
let end = 0;
let lose = 0;
let only_move = 1;
let removedAllEventListener = 0;
const $btnup = document.getElementById('btnup');
const $btndn = document.getElementById('btndn');
const $btnlt = document.getElementById('btnlt');
const $btnrt = document.getElementById('btnrt');
const $NotWork = document.getElementById('NotWork');
const congratulation_audio = new Audio('congratulation.wav');
const move_audio = new Audio('swoosh.mp3');
const lose_audio = new Audio('2048Lose_Mastering.wav');
const added = new Audio('pop.flac');
const $table = document.getElementById('table');
const $score = document.getElementById('score');
const $back = document.getElementById('back');
const $hmr = document.getElementById('how_many_remain');
const $set_fail = document.getElementById('Fail');
const $record = document.getElementById('record');
const $info = document.getElementById('information');
const $NotWorkGroup = document.getElementById('NotWorkGroup');
let how_many = 3;
let how_many_temp;
let data = [];
const history = [];
function removeAllEventListener(){
window.removeEventListener('keyup', key, false); // 패배시 이벤트 리스너 제거.
window.removeEventListener('mousedown', mousedown, false); // 패배시 이벤트 리스너 제거.
window.removeEventListener('mouseup', mouseup, false); // 패배시 이벤트 리스너 제거.
$table.removeEventListener('touchstart', touchstart, false); // 패배시 이벤트 리스너 제거.
$table.removeEventListener('touchend', touchend, false); // 패배시 이벤트 리스너 제거.
removedAllEventListener = 1;
};
function record(n, name, pw){
console.log('기록 시작');
if(name === null || pw === null) {
alert('기록이 취소되었습니다.');
console.log('취소!');
return;
};
if(!window.localStorage.getItem(pw)) {
console.log('첫번째 기록!');
window.localStorage.setItem(pw,n);
console.log('기록 완료!');
} else{
console.log('이전의 기록 발견!');
const prev = window.localStorage.getItem(pw);
if(prev < n){
window.localStorage.setItem(pw,n);
console.log('최고기록 달성!');
alert(n+'점\n최고기록 달성!\n축하드립니다!!🎉🎉');
console.log('완료');
} else if(prev > n){
const prev_temp = prev-n;
alert(prev_temp+'점 차이로 아쉽게 실패!');
const want_record = confirm('기록을 갱신 하시겠습니까?');
if(want_record){
if(confirm('기존기록은 삭제 됩니다.\n그래도 하시겠습니까?')){
window.localStorage.setItem(pw,n);
console.log('완료')
} else{
console.log('cancled');
};
return;
} else{
return;
};
} else{
console.log('동점!')
alert(n+'점으로 동점입니다.')
};
};
}
function login(n){
let restart_function = 0
console.log(n+'점을 기록.');
const name = prompt('당신의 닉네임을 작성해주세요.');
if(name == null) {
alert('기록이 취소되었습니다.');
return;
};
const pw = prompt('비밀번호를 입력해주세요');
if(pw == null) {
alert('기록이 취소되었습니다.');
return;
};
console.log(pw);
if(name){
console.log('닉네임: ' + name);
let name_list = false;
if(window.localStorage.getItem(name)){
name_list = window.localStorage.getItem(name);
console.log(String(name_list)+String(pw));
if(name_list == true){
console.log('가입필요.');
pw1 == prompt('신규 가입중...\n비밀번호를 다시 한번 입력해주세요');
if(pw == pw1){
window.localStorage.setItem(name, pw);
console.log('완료');
} else{
console.log('비밀번호 틀림');
alert('비밀번호가 틀렸습니다.');
restart_function = 1
// login(n);
};
} else if(name_list == pw){
console.log('기록 되어있는 닉네임.');
} else{
console.log('비밀번호 틀림');
alert('비밀번호가 틀렸습니다.');
restart_function = 1
// login(n);
};
} /*else if(pw != pw1){
console.log('비밀번호 틀림');
alert('비밀번호가 틀렸습니다.');
login(n);
}*/ else {
console.log('신규');
const pw1 = prompt('신규 가입중...\n비밀번호를 입력해주세요');
if(pw == pw1){
window.localStorage.setItem(name, pw);
console.log('완료');
alert('가입이 완료되었습니다. 본 계정은 본 기기에 한하여 사용이 가능합니다.')
} else{
console.log('비밀번호 틀림');
alert('비밀번호가 틀렸습니다.');
restart_function = 1
}
};
if(restart_function == 1){
login(n);
}
else{
record(n, name, pw);
};
// return;
} else{
return;
}
if(lose == 1){
removeAllEventListener;
};
}
function restore(n){
console.log('되돌리기 요청됨.')
if(how_many == 0){
$hmr.textContent = '되돌릴수 없습니다.'
$hmr.style.color = 'red'
console.log('되돌리기 취소됨.')
if (n === 1){
alert('되돌릴수 없습니다.');
console.log('Notifaction was completed with Pop Up Message.');
const confirm_record = confirm('점수를 기록 하시겠습니까?');
if(confirm_record){
// login(`${$score.textContent}`);
set_fail();
} else{
return;
};
};
return;
} else{
console.log('승인!')
const prevData = history.pop();
if (!prevData) return; // 되돌릴 게 없으면 종료
how_many = how_many - 1
how_many.toString;
how_many_temp = how_many + '회 남음';
$score.textContent = prevData.score;
$hmr.textContent = how_many_temp
data = prevData.table;
draw();
console.log('완료!')
}
}
let infinity_mode = 0
function set_fail(n) {
if (infinity_mode != 1){
end = 1;
lose = 1;
alert(`패배했습니다... ${$score.textContent}점`);
// if(n == 'manual') login(`${$score.textContent}`); // 수동으로 포기 할시 바로 기록여부 확인 후 종료.
const yesOrNo = confirm('한턴을 되돌리시겠습니까?');
console.log('패배\n\n되돌리기 = ' + yesOrNo);
if(yesOrNo){
restore(n);
} else{
/*
let url = new URL(window.location.href);
console.log(url)
url = url.toString();
// let temp =
let splited = url.substr(0, -9);
url = splited + '2048_Result.html';
console.log(url)
// var child = frames[0];
window.open('http://127.0.0.1:5500/2048_Result.html').postMessage($score.textContent, 'http://127.0.0.1:5500/2048_Result.html');
window.open("/2048_Result.html");
window.close();
// location.replace(url)
// login(`${$score.textContent}`);
*/
try {
window.opener.postMessage({score:$score.textContent,win:0}, '*')
close();
} catch (error) {
if (infinity_mode == 0) {
if (confirm('무한모드를 활성화 하시겠습니까?')){
infinity_mode = 1;
$info.textContent = 'infinity mode enabled.';
$info.style.color = 'blue';
} else {
infinity_mode = -1;
};
};
};
}
/*
lose_audio.currentTime = 0;
lose_audio.play();
$info.textContent = 'LOSE!';
$info.style.color = 'red';
*/
} else {
if (infinity_mode == 0) {
if (confirm('무한모드를 활성화 하시겠습니까?')){
infinity_mode = 1;
$info.textContent = 'infinity mode enabled.';
$info.style.color = 'blue';
} else {
infinity_mode = -1;
};
}
}
}
function complete(n){
end = 1;
congratulation_audio.play();
alert('🎉🎉🎉\n축하합니다. 2048을 만들었습니다!\n🎉🎉🎉');
// login(n);
window.opener.postMessage({score:$score.textContent,win:1}, '*')
close();
}
$set_fail.addEventListener('click', () => {
set_fail('manual');
})
$back.addEventListener('click', () => {
restore();
})
// $table -> $fragment -> $tr -> $td
function startGame() {
const $fragment = document.createDocumentFragment();
[1, 2, 3, 4].forEach(function () {
const rowData = [];
data.push(rowData);
const $tr = document.createElement('tr');
[1, 2, 3, 4].forEach(() => {
rowData.push(0);
const $td = document.createElement('td');
$tr.appendChild($td);
});
$fragment.appendChild($tr);
});
$table.appendChild($fragment);
put2ToRandomCell();
draw();
}
function put2ToRandomCell() {
const emptyCells = []; // [[i1, j1], [i2, j2], [i3, j3]]
data.forEach(function (rowData, i) {
rowData.forEach(function (cellData, j) {
if (!cellData) {
emptyCells.push([i, j]);
}
});
});
// randomCell === [i, j]
const randomCell = emptyCells[Math.floor(Math.random() * emptyCells.length)];
data[randomCell[0]][randomCell[1]] = 2;
}
function draw() {
data.forEach((rowData, i) => {
rowData.forEach((cellData, j) => {
const $target = $table.children[i].children[j];
if (cellData > 0) {
$target.textContent = cellData;
$target.className = 'color-' + cellData;
} else {
$target.textContent = '';
$target.className = '';
}
});
});
}
startGame();
/*
data = [
[32, 2, 4, 2],
[64, 4, 8, 4],
[2, 1024, 1024, 32],
[32, 16, 64, 4],
];
draw();
*/
function moveCells(direction) {
history.push({
table: JSON.parse(JSON.stringify(data)),
score: $score.textContent,
});
switch (direction) {
case 'left': {
const newData = [[], [], [], []];
data.forEach((rowData, i) => {
rowData.forEach((cellData, j) => {
if (cellData) { // newData = [2, 2, 4]
const currentRow = newData[i]
const prevData = currentRow[currentRow.length - 1];
if (prevData === cellData) { // 이전 값과 지금 값이 같으면
const score = parseInt($score.textContent);
$score.textContent = score + currentRow[currentRow.length - 1] * 2;
currentRow[currentRow.length - 1] *= -2;
only_move = 0;
added.currentTime = 0;
added.play();
} else {
newData[i].push(cellData);
}
}
});
});
console.log(newData);
[1, 2, 3, 4].forEach((rowData, i) => {
[1, 2, 3, 4].forEach((cellData, j) => {
data[i][j] = Math.abs(newData[i][j]) || 0;
});
});
break;
}
case 'right': {
const newData = [[], [], [], []];
data.forEach((rowData, i) => {
rowData.forEach((cellData, j) => {
if (rowData[3 - j]) {
const currentRow = newData[i]
const prevData = currentRow[currentRow.length - 1];
if (prevData === rowData[3 - j]) {
const score = parseInt($score.textContent);
$score.textContent = score + currentRow[currentRow.length - 1] * 2;
currentRow[currentRow.length - 1] *= -2;
only_move = 0;
added.currentTime = 0;
added.play();
} else {
newData[i].push(rowData[3 - j]);
}
}
});
});
console.log(newData);
[1, 2, 3, 4].forEach((rowData, i) => {
[1, 2, 3, 4].forEach((cellData, j) => {
data[i][3 - j] = Math.abs(newData[i][j]) || 0;
});
});
break;
}
case 'up': {
const newData = [[], [], [], []];
data.forEach((rowData, i) => {
rowData.forEach((cellData, j) => {
if (cellData) {
const currentRow = newData[j]
const prevData = currentRow[currentRow.length - 1];
if (prevData === cellData) {
const score = parseInt($score.textContent);
$score.textContent = score + currentRow[currentRow.length - 1] * 2;
currentRow[currentRow.length - 1] *= -2;
only_move = 0;
added.currentTime = 0;
added.play();
} else {
newData[j].push(cellData);
}
}
});
});
console.log(newData);
[1, 2, 3, 4].forEach((cellData, i) => {
[1, 2, 3, 4].forEach((rowData, j) => {
data[j][i] = Math.abs(newData[i][j]) || 0;
});
});
break;
}
case 'down': {
const newData = [[], [], [], []];
data.forEach((rowData, i) => {
rowData.forEach((cellData, j) => {
if (data[3 - i][j]) {
const currentRow = newData[j];
const prevData = currentRow[currentRow.length - 1];
if (prevData === data[3 - i][j]) {
const score = parseInt($score.textContent);
$score.textContent = score + currentRow[currentRow.length - 1] * 2;
currentRow[currentRow.length - 1] *= -2;
only_move = 0;
added.currentTime = 0;
added.play();
} else {
newData[j].push(data[3 - i][j]);
}
}
});
});
console.log(newData);
[1, 2, 3, 4].forEach((cellData, i) => {
[1, 2, 3, 4].forEach((rowData, j) => {
data[3 - j][i] = Math.abs(newData[i][j]) || 0;
});
});
break;
}
}
if (data.flat().includes(2048)) { // 승리
draw();
setTimeout(() => {
complete(2048);
}, 0);
// login($score.testContent)
} else if (!data.flat().includes(0)) { // 빈 칸이 없으면 패배
set_fail(1);
// alert(`패배했습니다... ${$score.textContent}점`);
} else {
put2ToRandomCell();
draw();
};
if (only_move == 1) {
move_audio.currentTime = 0.001;
move_audio.play();
} else if (removedAllEventListener == 1) {
move_audio.currentTime = 0;
only_move = 0;
} else {
only_move = 1;
};
}
function key(event){ // 키보드 이벤트 처리
if (event.key === 'ArrowUp') {
if (removedAllEventListener == 0) {
moveCells('up');
};
} else if (event.key === 'ArrowDown') {
if (removedAllEventListener == 0) {
moveCells('down');
};
} else if (event.key === 'ArrowLeft') {
if (removedAllEventListener == 0) {
moveCells('left');
};
} else if (event.key === 'ArrowRight') {
if (removedAllEventListener == 0) {
moveCells('right');
};
}
};
window.addEventListener('keyup', key); // 키보드 키 누른뒤 손땠을때 기준으로 이벤트 리스너 추가
let startCoord;
function mousedown(event){ // 마우스 시작점 기록
startCoord = [event.clientX, event.clientY];
};
function mouseup(event){ // 마우스 종료 위치 기록및 차이점으로 cell이동 여부 및 이동 방향 결정
const endCoord = [event.clientX, event.clientY];
const diffX = endCoord[0] - startCoord[0];
const diffY = endCoord[1] - startCoord[1];
if (diffX < 0 && Math.abs(diffX) > Math.abs(diffY)) {
if (removedAllEventListener == 0){
moveCells('left');
};
} else if (diffX > 0 && Math.abs(diffX) > Math.abs(diffY)) {
if (removedAllEventListener == 0){
moveCells('right');
};
} else if (diffY > 0 && Math.abs(diffX) <= Math.abs(diffY)) {
if (removedAllEventListener == 0){
moveCells('down');
};
} else if (diffY < 0 && Math.abs(diffX) <= Math.abs(diffY)) {
if (removedAllEventListener == 0){
moveCells('up');
};
}
};
function touchstart(event){ // 터치 시작점 기록
startCoord = [event.touches[0].clientX, event.touches[0].clientY];
};
function touchend(event){ // 터치 종료 위치 기록및 차이점으로 cell이동 여부 및 이동 방향 결정
const endCoord = [event.changedTouches[0].clientX, event.changedTouches[0].clientY];
const diffX_touch = endCoord[0] - startCoord[0];
const diffY_touch = endCoord[1] - startCoord[1];
if (diffX_touch < 0 && Math.abs(diffX_touch) > Math.abs(diffY_touch)) {
if (removedAllEventListener == 0){
moveCells('left');
};
} else if (diffX_touch > 0 && Math.abs(diffX_touch) > Math.abs(diffY_touch)) {
if (removedAllEventListener == 0){
moveCells('right');
};
} else if (diffY_touch > 0 && Math.abs(diffX_touch) <= Math.abs(diffY_touch)) {
if (removedAllEventListener == 0){
moveCells('down');
};
} else if (diffY_touch < 0 && Math.abs(diffX_touch) <= Math.abs(diffY_touch)) {
if (removedAllEventListener == 0){
moveCells('up');
};
}
};
window.addEventListener('mousedown', mousedown, false); // 마우스 버튼 입력 시작 감지
window.addEventListener('mouseup', mouseup, false); // 마우스 버튼 입력 중지 감지
window.addEventListener('touchstart', touchstart, false); // 터치 시작 감지
window.addEventListener('touchend', touchend, false);
function moveup(){
moveCells('up');
};
function movedn(){
moveCells('down');
};
function movelt(){
moveCells('left');
};
function movert(){
moveCells('right');
};
$btnup.addEventListener('click', moveup, false);
$btndn.addEventListener('click', movedn, false);
$btnlt.addEventListener('click', movelt, false);
$btnrt.addEventListener('click', movert, false);
</script>
</body>
</html>