Tic-Tac-Toe

Make Your Tic-Tac-Toe Game Better: User Names and JavaScript

Tic-Tac-Toe is a classic two-player strategy game played on a 3×3 grid. Players take turns marking empty cells with their symbol — either X or O. The first player to align three of their marks in a horizontal, vertical, or diagonal line wins the round. If all cells are filled and no player has won, the round ends in a draw. Playing Tic-Tac-Toe can improve your strategic thinking and offer endless entertainment!

This version includes:

  • A name entry screen to personalize the match
  • 3-round gameplay with automatic score tracking
  • Visual animations and sound effects for an engaging experience
  • A final scoreboard to declare the winner after all rounds

Whether you’re practicing your logic or challenging a friend, Tic-Tac-Toe is a fun and quick game that never gets old!

Let’s upgrade the Tic-Tac-Toe game into a 3-round match, and after the third round, it will:

✅ Show a final scoreboard with both players’ names and scores
✅ Show a “Play Again” button to restart from the name input screen

If you’re looking for a quick game, Tic-Tac-Toe is perfect for any gathering!

Sound effects (click, win, tie)
Animations (cell pop & win flash)

🧱 Main Parts of the Game

Engaging in a game of Tic-Tac-Toe with friends or family can create lasting memories. Consider adding custom features to enhance your Tic-Tac-Toe experience!

In addition to the updates, remember that Tic-Tac-Toe is not only about winning; it’s about having fun and challenging your mind.

1. HTML Structure

  • Start Screen: Where players enter their names
  • Game Board: The 3×3 grid where the game is played
  • Status Area: Shows current player, round info, and messages
  • Final Score Screen: Shows who won after 3 rounds
  • Audio Elements: For click, win, and tie sounds

Utilizing Tic-Tac-Toe in educational settings can be a great way to teach strategy and critical thinking.

Another way to enjoy Tic-Tac-Toe is by exploring different variations of the game to challenge yourself.

2. CSS Styling

Enhancing your Tic-Tac-Toe game with unique elements can make it even more enjoyable.

Handles:

  • Layout (centered content)
  • Cell styling
  • Hover effects
  • Win highlight animation
  • Pop animation on click
  • Button design

3. JavaScript Functionality

🔁 Game Flow:

  1. Players enter names → startGame()
  2. A game round begins → resetBoard()
  3. Players click cells → handleClick()
  4. After each move:
    • Check win → checkWinner()
    • If win → play sound, animate, wait → nextRound()
    • If tie → same but with tie logic
    • If neither → switch player
  5. After 3 rounds → showFinalScore()

You will also like this post

Get ready to play Tic-Tac-Toe as you learn new strategies that can lead to victories!

  1. How to Implement Word Scramble Game in Js
  2. Create Dx Ball Game Using JavaScript

✅ Full Working Code (HTML + CSS + JS — All in One)

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>Tic Tac Toe - 3 Rounds By Mycodingtutorial</title>
  <style>
    body {
      font-family: sans-serif;
      background: #222;
      color: #fff;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      height: 100vh;
      margin: 0;
    }

    div#gameContainer {
        background-color: #fff;
        padding: 65px 90px 65px 90px;
        border-radius: 15px;
    }
    h1 {
      margin-bottom: 10px;
      color: #000;
    }

    .board {
      display: grid;
      grid-template-columns: repeat(3, 100px);
      gap: 5px;
      margin-top: 20px;
    }

    .cell {
      width: 100px;
      height: 100px;
      background: #333;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 2.5rem;
      cursor: pointer;
      border-radius: 10px;
      transition: transform 0.2s ease;
    }

    .cell:hover {
      background: #444;
    }

    .cell.pop {
      animation: pop 0.2s ease;
    }

    @keyframes pop {
      0% { transform: scale(1); }
      50% { transform: scale(1.2); }
      100% { transform: scale(1); }
    }

    .cell.win {
      background: #4db2ec !important;
      color: #fff;
      animation: flash 0.5s ease alternate 3;
    }

    @keyframes flash {
      from { background: #4db2ec; }
      to   { background: #4db2ec; }
    }

    .status, button {
      margin-top: 15px;
      font-size: 18px;
      color: #000;
    }

    button {
      padding: 8px 16px;
      background: #4db2ec;
      color: white;
      border: none;
      border-radius: 6px;
      cursor: pointer;
    }

    button:hover {
      background: #4db2ec;
    }

    .start-screen, #finalScore {
      text-align: center;
    }

    div#roundInfo {
        color: #000;
        font-size: 18px;
        margin-top: 10px;
    }

    div#startScreen {
     background-color: #fff;
     padding: 65px 30px 65px 30px;
     border-radius: 15px;
    }
    .start-screen input {
      padding: 17px;
        margin: 10px;
        font-size: 16px;
        border-radius: 6px;
        border: 2px solid #4db2ec;
    }

    div#finalScore {
        background-color: #2c2c2c;
        padding: 65px 30px 65px 30px;
        border-radius: 15px;
        width: 27%;
    }
    div#scoreBoard p {
        font-size: 18px;
        text-transform: capitalize;
        font-weight: 600;
    }

    #gameContainer, #finalScore {
      display: none;
      flex-direction: column;
      align-items: center;
    }
  </style>
</head>
<body>

  <!-- Start Screen -->
  <div class="start-screen" id="startScreen">
    <h1>Tic Tac Toe</h1>
    <input type="text" id="playerX" placeholder="Player X Name" required />
    <input type="text" id="playerO" placeholder="Player O Name" required />
    <br>
    <button onclick="startGame()">Start Game</button>
  </div>

  <!-- Game Screen -->
  <div id="gameContainer">
    <div class="board" id="board"></div>
    <div class="status" id="status">Loading...</div>
    <div id="roundInfo">Round 1 of 3</div>
    <button onclick="resetToNameScreen()">Quit to Start</button>
  </div>

  <!-- Final Score Screen -->
  <div id="finalScore">
    <h2>Final Score</h2>
    <div id="scoreBoard"></div>
    <button onclick="resetToNameScreen()">Play Again</button>
  </div>

  <!-- Sound Effects -->
  <audio id="clickSound" src="click.mp3"></audio>
  <audio id="winSound" src="Win.mp3"></audio>
  <audio id="tieSound" src="Tie.mp3"></audio>

  <script>
    const board = document.getElementById("board");
    const statusText = document.getElementById("status");
    const roundInfo = document.getElementById("roundInfo");
    const startScreen = document.getElementById("startScreen");
    const gameContainer = document.getElementById("gameContainer");
    const finalScore = document.getElementById("finalScore");
    const scoreBoard = document.getElementById("scoreBoard");

    const clickSound = document.getElementById("clickSound");
    const winSound = document.getElementById("winSound");
    const tieSound = document.getElementById("tieSound");

    let cells = Array(9).fill(null);
    let currentPlayer = "X";
    let gameOver = false;
    let playerNames = { X: "Player X", O: "Player O" };
    let scores = { X: 0, O: 0 };
    let round = 1;
    const maxRounds = 3;

    const winningCombos = [
      [0, 1, 2], [3, 4, 5], [6, 7, 8],
      [0, 3, 6], [1, 4, 7], [2, 5, 8],
      [0, 4, 8], [2, 4, 6]
    ];

    function startGame() {
      const nameX = document.getElementById("playerX").value.trim();
      const nameO = document.getElementById("playerO").value.trim();

      if (!nameX || !nameO) {
        alert("Please enter names for both players.");
        return;
      }

      playerNames = { X: nameX, O: nameO };
      scores = { X: 0, O: 0 };
      round = 1;

      startScreen.style.display = "none";
      gameContainer.style.display = "flex";
      resetBoard();
    }

    function createBoard() {
      board.innerHTML = "";
      cells.forEach((cell, index) => {
        const div = document.createElement("div");
        div.classList.add("cell");
        div.dataset.index = index;
        div.textContent = cell || "";
        div.addEventListener("click", handleClick);
        board.appendChild(div);
      });
    }

    function handleClick(e) {
      const index = e.target.dataset.index;
      if (cells[index] || gameOver) return;

      clickSound.play();
      cells[index] = currentPlayer;
      e.target.textContent = currentPlayer;
      e.target.classList.add("pop");

      if (checkWinner(currentPlayer)) {
        highlightWinner(currentPlayer);
        statusText.textContent = `${playerNames[currentPlayer]} Wins Round ${round}! 🎉`;
        scores[currentPlayer]++;
        gameOver = true;
        winSound.play();
        setTimeout(nextRound, 1500);
        return;
      }

      if (!cells.includes(null)) {
        statusText.textContent = `Round ${round} is a Tie!`;
        gameOver = true;
        tieSound.play();
        setTimeout(nextRound, 1500);
        return;
      }

      currentPlayer = currentPlayer === "X" ? "O" : "X";
      statusText.textContent = `${playerNames[currentPlayer]} Turn`;
    }

    function checkWinner(player) {
      return winningCombos.some(combo =>
        combo.every(index => cells[index] === player)
      );
    }

    function highlightWinner(player) {
      const combo = winningCombos.find(combo =>
        combo.every(index => cells[index] === player)
      );
      if (combo) {
        combo.forEach(index => {
          board.children[index].classList.add("win");
        });
      }
    }

    function nextRound() {
      if (round >= maxRounds) {
        showFinalScore();
        return;
      }
      round++;
      resetBoard();
    }

    function resetBoard() {
      cells = Array(9).fill(null);
      currentPlayer = "X";
      gameOver = false;
      statusText.textContent = `${playerNames.X} Turn`;
      roundInfo.textContent = `Round ${round} of ${maxRounds}`;
      createBoard();
    }

    function showFinalScore() {
      gameContainer.style.display = "none";
      finalScore.style.display = "flex";

      const nameX = playerNames.X;
      const nameO = playerNames.O;

      scoreBoard.innerHTML = `
        <p>${nameX}: ${scores.X} points</p>
        <p>${nameO}: ${scores.O} points</p>
        <h3>${
          scores.X > scores.O
            ? `${nameX} Wins the Match! 🏆`
            : scores.O > scores.X
            ? `${nameO} Wins the Match! 🏆`
            : "It's a Tie Match!"
        }</h3>
      `;
    }

    function resetToNameScreen() {
      finalScore.style.display = "none";
      gameContainer.style.display = "none";
      startScreen.style.display = "block";
      document.getElementById("playerX").value = "";
      document.getElementById("playerO").value = "";
    }
  </script>
</body>
</html>

🏁 Final Score

Remember, playing Tic-Tac-Toe can also enhance your decision-making skills.

After 3 rounds, the showFinalScore() function compares scores and displays who won the best of 3.

✅ You Learned

  • How to structure a game in HTML, CSS, and JS
  • How to manage game state and logic
  • How to add interactivity and user feedback (audio + animation)
  • How to switch between screens (start/game/end)

As the game of Tic-Tac-Toe progresses, strategies may evolve, making each match unique.

Remember, every game of Tic-Tac-Toe presents a new opportunity to learn and improve.

So, gather your friends and family for a fun session of Tic-Tac-Toe!

Engage in friendly competition with Tic-Tac-Toe to keep the excitement alive!

Make Your Tic-Tac-Toe Game Better: User Names and JavaScript

Simple HTML for a Great Card Design

Make Your Tic-Tac-Toe Game Better: User Names and JavaScript

Simple Code Tricks to Make Your Postcard

Leave a comment

Your email address will not be published. Required fields are marked *