틱택토 웹 앱 만들기

CSSBeginner
지금 연습하기

소개

이 프로젝트에서는 HTML, CSS, JavaScript 를 사용하여 틱택토 게임을 만드는 방법을 배웁니다. 틱택토는 두 명의 플레이어가 3x3 격자에 X 또는 O 를 번갈아 표시하는 게임입니다. 목표는 가로, 세로 또는 대각선으로 세 개의 표시를 연속으로 만드는 것입니다. 필요한 HTML, CSS, JavaScript 파일을 생성하고 게임 로직을 단계별로 구현하게 됩니다.

👀 미리보기

Tic Tac Toe game preview

🎯 목표

이 프로젝트를 통해 다음을 학습하게 됩니다.

  • HTML 을 사용하여 틱택토 게임의 기본 구조를 설정하는 방법.
  • CSS 스타일을 추가하여 게임 요소의 모양을 정의하는 방법.
  • JavaScript 를 사용하여 게임 로직을 구현하는 방법.
  • 사용자 상호 작용을 처리하고, 승리 또는 무승부를 확인하며, 점수를 업데이트하는 방법.
  • 게임 보드를 렌더링하고 턴 표시기를 업데이트하는 방법.
  • 플레이어가 게임을 초기화하고 새 라운드를 시작할 수 있도록 하는 방법.

🏆 성과

이 프로젝트를 완료하면 다음을 수행할 수 있게 됩니다.

  • 웹 애플리케이션을 위한 HTML 파일 구조화.
  • CSS 클래스를 사용하여 요소 스타일링.
  • JavaScript 를 사용하여 게임 로직 구현.
  • 사용자 상호 작용을 처리하고 그에 따라 UI 업데이트.
  • 게임 보드 렌더링 및 턴 표시기 업데이트.
  • JavaScript 에서 이벤트 리스너 생성 및 이벤트 처리.
이것은 학습하고 연습하는 데 도움이 되는 단계별 지침을 제공하는 가이드형 실습입니다. 각 단계를 완료하고 실습 경험을 얻으려면 지침을 주의 깊게 따르십시오. 과거 데이터에 따르면 이 실습은 중급 수준이며 완료율은 52%입니다. 학습자들로부터 100%의 긍정적인 평가를 받았습니다.

HTML 파일 생성

index.html이라는 새 파일을 만들고 다음 코드를 추가합니다.

cd ~/project
touch index.html

이 코드는 틱택토 게임의 기본 구조를 설정합니다.

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Tic-Tac-Toe</title>
    <link
      href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css"
      rel="stylesheet"
    />
    <style>
      /* CSS styles for the game */
    </style>
  </head>

  <body>
    <div id="app">
      <h1 class="text-3xl font-bold mb-4 text-gray-900">Tic-Tac-Toe</h1>
      <div id="board" class="grid grid-cols-3 gap-4 mb-4">
        <!-- Game board cells -->
      </div>
      <div id="scoreboard" class="flex justify-between items-center mb-4">
        <!-- Player scores -->
      </div>
      <div
        id="turn-indicator"
        class="text-2xl font-bold mb-4 text-gray-900"
      ></div>
      <button
        id="reset-button"
        class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
      >
        Reset Game
      </button>
    </div>

    <script>
      // JavaScript code for the game logic
    </script>
  </body>
</html>
✨ 솔루션 확인 및 연습

CSS 스타일 추가

HTML 파일의 <head> 섹션에 있는 <style> 태그 안에 게임에 필요한 CSS 스타일을 추가합니다. 이 스타일은 게임 보드, 셀, 점수 및 버튼과 같은 게임 요소의 모양을 정의합니다.

<style>
  .board-cell {
    width: 100px;
    height: 100px;
  }

  body {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100vh;
    background-color: #222;
    font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
  }

  #app {
    text-align: center;
    background-color: #f5f5f5;
    border-radius: 8px;
    padding: 24px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  }

  h1 {
    font-size: 32px;
    color: #333;
  }

  .text-gray-900 {
    color: #333 !important;
  }

  .text-2xl {
    font-size: 24px;
  }

  .bg-blue-500 {
    background-color: #4267b2;
  }

  .bg-blue-500:hover {
    background-color: #3b5ca0;
  }

  .bg-blue-700 {
    background-color: #385898;
  }

  .text-white {
    color: #fff !important;
  }

  .rounded {
    border-radius: 4px;
  }

  .highlight {
    background-color: #ffed4a;
  }
</style>

프로젝트에 style.css를 추가하고 <link> 태그를 사용하여 HTML 파일에 연결할 수도 있습니다.

<link rel="stylesheet" href="style.css" />

선호하는 방식을 선택하세요.

✨ 솔루션 확인 및 연습

게임 로직 JavaScript 코드 추가

HTML 파일 끝에 있는 <script> 태그 안에 게임 로직을 처리하는 JavaScript 코드를 추가합니다. 이 코드는 게임 상태를 추적하고, 사용자 상호 작용을 처리하며, 승리 또는 무승부를 확인하고, 점수를 업데이트하며, 게임 보드를 렌더링합니다.

<script>
  // Game logic code
</script>
✨ 솔루션 확인 및 연습

게임 변수 초기화

JavaScript 코드 시작 부분에 필요한 변수들을 선언합니다. 이 변수들은 게임 상태, 플레이어 점수 및 기타 관련 정보를 저장합니다.

// Game logic
const board = ["", "", "", "", "", "", "", "", ""];
let currentPlayer = "X";
let gameEnded = false;
let playerXScore = 0;
let playerOScore = 0;
let winningCells = [];
✨ 솔루션 확인 및 연습

셀 클릭 처리

게임 보드의 셀을 클릭할 때 호출되는 handleCellClick 함수를 생성합니다. 이 함수는 보드 업데이트, 승리 확인, 점수 업데이트 및 현재 플레이어 변경과 같은 주요 게임 로직을 처리합니다.

function handleCellClick(index) {
  if (gameEnded || board[index] !== "") return;
  board[index] = currentPlayer;
  renderBoard();

  if (checkWin()) {
    updateScore();
    highlightWinningCells();
    alert(`Player ${currentPlayer} wins!`);
    gameEnded = true;
  } else if (board.every((cell) => cell !== "")) {
    alert("It's a tie!");
    gameEnded = true;
  } else {
    currentPlayer = currentPlayer === "X" ? "O" : "X";
    updateTurnIndicator();
  }
}
✨ 솔루션 확인 및 연습

승리 확인

게임 보드에 승리 조건이 있는지 확인하는 checkWin 함수를 생성합니다. 이 함수는 보드 배열의 값과 승리 조합을 비교하여 플레이어가 게임에서 이겼는지 확인합니다.

function checkWin() {
  const winningCombinations = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6]
  ];

  for (let i = 0; i < winningCombinations.length; i++) {
    const [a, b, c] = winningCombinations[i];
    if (board[a] !== "" && board[a] === board[b] && board[a] === board[c]) {
      winningCells = [a, b, c];
      return true;
    }
  }
  return false;
}
✨ 솔루션 확인 및 연습

게임 초기화

resetGame 함수를 생성하여 게임 상태를 초기 값으로 재설정합니다. 이 함수는 리셋 버튼을 클릭할 때 호출되며, 보드를 지우고, 현재 플레이어를 재설정하고, 승리한 셀을 지우고, 턴 표시기를 업데이트하고, 보드를 렌더링합니다.

function resetGame() {
  board.fill("");
  currentPlayer = "X";
  gameEnded = false;
  winningCells = [];
  updateTurnIndicator();
  renderBoard();
}
✨ 솔루션 확인 및 연습

플레이어 점수 업데이트

플레이어 점수를 업데이트하는 updateScore 함수를 생성합니다. 이 함수는 플레이어가 게임에서 승리했을 때 호출됩니다. 해당 플레이어의 점수를 증가시키고 페이지의 점수 표시를 업데이트합니다.

function updateScore() {
  if (currentPlayer === "X") {
    playerXScore++;
    document.getElementById("player-x-score").textContent = playerXScore;
  } else {
    playerOScore++;
    document.getElementById("player-o-score").textContent = playerOScore;
  }
}
✨ 솔루션 확인 및 연습

턴 표시기 업데이트

페이지에서 현재 플레이어의 턴을 표시하도록 턴 표시기를 업데이트하는 updateTurnIndicator 함수를 생성합니다.

function updateTurnIndicator() {
  const turnIndicator = document.getElementById("turn-indicator");
  turnIndicator.textContent = `Current Turn: Player ${currentPlayer}`;
}
✨ 솔루션 확인 및 연습

승리 셀 강조 표시

게임에서 플레이어가 승리했을 때 게임 보드의 승리 셀에 강조 표시 클래스를 추가하는 highlightWinningCells 함수를 생성합니다.

function highlightWinningCells() {
  const cells = document.querySelectorAll(".board-cell");
  cells.forEach((cell, index) => {
    if (winningCells.includes(index)) {
      cell.classList.add("highlight");
    }
  });
}
✨ 솔루션 확인 및 연습

요약

Summary content missing in import file.

✨ 솔루션 확인 및 연습

Add Event Listeners

Add event listeners to the game board cells and the reset button. These event listeners call the corresponding functions when the events occur.

// Event listeners
const cells = document.querySelectorAll(".board-cell");
cells.forEach((cell, index) => {
  cell.addEventListener("click", () => handleCellClick(index));
});

const resetButton = document.getElementById("reset-button");
resetButton.addEventListener("click", resetGame);
✨ 솔루션 확인 및 연습

Initial Render

At the end of the JavaScript code, add the code for the initial render. This code sets up the initial state of the game, updates the turn indicator, and renders the game board.

// Initial render
updateTurnIndicator();
renderBoard();
✨ 솔루션 확인 및 연습

Run the Project

You can now run the project and play Tic-Tac-Toe!

Click on Go Live button in the bottom right corner of WebIDE, to run the project.

WebIDE Go Live button

This will open the project in Web 8080 Tab.

Web 8080 Tab interface

Click on the cells to make your moves and click the reset button to start a new game.

✨ 솔루션 확인 및 연습

Summary

Congratulations! You have successfully created a Tic-Tac-Toe game using HTML, CSS, and JavaScript. The project covered creating the HTML file, adding CSS styles, implementing the game logic, and handling user interactions. The game allows two players to take turns, checks for a win or a tie, updates scores, and highlights winning cells. You can now run the project and enjoy playing Tic-Tac-Toe!