2048 게임 (html / js)

yun·2023년 3월 19일
0

절차

프로그래밍 사고

-시작
-테이블 그리기
-랜덤한 위치에 숫자 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 = '';
        }
      });
    });
  }
  • 랜덤한 위치에 숫자 2 넣기
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);
}

화면

소스코드(github)
링크텍스트
출처 "ZeroCho TV"
링크텍스트

profile
날아오르고 싶은 애벌레입니다.

0개의 댓글

관련 채용 정보