-시작
-테이블 그리기
-랜덤한 위치에 숫자 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 = '';
}
});
});
}
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;
}
window.addEventListener('keyup', (event) => {
if (event.key === 'ArrowUp') {
moveCells('up');
} else if (event.key === 'ArrowDown') {
moveCells('down');
} else if (event.key === 'ArrowLeft') {
moveCells('left');
} else if (event.key === 'ArrowRight') {
moveCells('right');
}
});
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;
} 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;
}
if (prevData === cellData) {
const score = parseInt($score.textContent);
$score.textContent = score + currentRow[currentRow.length - 1] * 2;
currentRow[currentRow.length - 1] *= -2;
}
if (!data.flat().includes(0)) {
alert(`패배했습니다... ${$score.textContent}점`);
}
-2048이 되면 게임을 끝낸다.
if (data.flat().includes(2048)) { // 승리
draw();
setTimeout(() => {
alert('축하합니다. 2048을 만들었습니다!');
}, 0);
}