search
HomeWeb Front-endCSS TutorialBuild a Tic Tac Toe Game Website

Build a Tic Tac Toe Game Website

Introduction

Hello, fellow developers! I'm excited to share my latest project: a classic Tic-Tac-Toe Game. This project is a great way to practice your JavaScript skills, particularly in handling game logic, DOM manipulation, and user interactions. Whether you're just getting started with JavaScript or looking for a fun challenge, this Tic-Tac-Toe game is perfect for honing your skills.

Project Overview

The Tic-Tac-Toe Game is a web-based implementation of the popular two-player game. The project showcases how to create interactive elements, manage game state, and implement simple AI logic. The game is designed to be fully responsive, making it playable on both desktop and mobile devices.

Features

  • Two-Player Mode: Play with a friend on the same device.
  • Game Logic: Automatically checks for a winner or a draw after each move.
  • Reset Functionality: Easily restart the game at any point.
  • Responsive Design: The game layout adapts to different screen sizes, providing a consistent experience on all devices.

Technologies Used

  • HTML: Structures the game interface.
  • CSS: Styles the game board, buttons, and other UI elements.
  • JavaScript: Manages the game logic, including player turns, win conditions, and resetting the game.

Project Structure

Here's a quick look at the project structure:

Tic-Tac-Toe/
├── index.html
├── styles.css
└── script.js
  • index.html: Contains the HTML structure of the Tic-Tac-Toe game.
  • styles.css: Includes CSS styles for the game board and responsive design.
  • script.js: Handles the game logic, including player turns and win conditions.

Installation

To get started with the project, follow these steps:

  1. Clone the repository:

    git clone https://github.com/abhishekgurjar-in/Tic-Tac-Toe.git
    
  2. Open the project directory:

    cd Tic-Tac-Toe
    
  3. Run the project:

    • Open the index.html file in a web browser to start playing the Tic-Tac-Toe game.

Usage

  1. Open the website in a web browser.
  2. Start the game by clicking on any empty cell in the grid.
  3. Take turns to place your marks (X or O) in the cells.
  4. Check the result: The game will declare a winner if there’s a winning combination or a draw if all cells are filled.
  5. Reset the game: Click the "Reset Game" button to start a new game.

Code Explanation

HTML

The index.html file sets up the structure of the Tic-Tac-Toe game, including the game board and control buttons. Here’s a snippet:


  
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tic-Tac-Toe Game</title>
    <link rel="stylesheet" href="style.css">
    <script src="script.js" defer></script>
  
  
    <div class="msg-container hide">
      <p id="msg">Winner</p>
      <button id="new-btn">New Game</button>
    </div>
    <main>
      <h1 id="Tic-Tac-Toe">Tic Tac Toe</h1>
      <div class="container">
        <div class="game">
          <button class="box"></button>
          <button class="box"></button>
          <button class="box"></button>
          <button class="box"></button>
          <button class="box"></button>
          <button class="box"></button>
          <button class="box"></button>
          <button class="box"></button>
          <button class="box"></button>
        </div>
      </div>
      <button id="reset-btn">Reset Game</button>
    </main>
    <div class="footer">
      <p>Made with ❤️ by Abhishek Gurjar</p>
    </div>
  


CSS

The styles.css file styles the Tic-Tac-Toe game, including the grid layout, buttons, and responsive design. Here are some key styles:

* {
    margin: 0;
    padding: 0;
  }

  body {
    background-color: #548687;
    text-align: center;
  }

  .container {
    height: 70vh;
    display: flex;

    justify-content: center;
    align-items: center;
  }

  .game {
    height: 60vmin;
    width: 60vmin;
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    align-items: center;
    gap: 1.5vmin;
  }

  .box {
    height: 18vmin;
    width: 18vmin;
    border-radius: 1rem;
    border: none;
    box-shadow: 0 0 1rem rgba(0, 0, 0, 0.3);
    font-size: 8vmin;
    color: #b0413e;
    background-color: #ffffc7;
  }

  #reset-btn {
    padding: 1rem;
    font-size: 1.25rem;
    background-color: #191913;
    color: #fff;
    border-radius: 1rem;
    border: none;
  }

  #new-btn {
    padding: 1rem;
    font-size: 1.25rem;
    background-color: #191913;
    color: #fff;
    border-radius: 1rem;
    border: none;
  }

  #msg {
    color: #ffffc7;
    font-size: 5vmin;
  }

  .msg-container {
    height: 100vmin;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    gap: 4rem;
  }

  .hide {
    display: none;
  }
.footer {
  margin: 50px;
  text-align: center;
  color: white;
}

JavaScript

The script.js file manages the game logic, including handling player turns, checking for a winner, and resetting the game. Here’s a snippet:

let boxes = document.querySelectorAll(".box");
let resetBtn = document.querySelector("#reset-btn");
let newGameBtn = document.querySelector("#new-btn");
let msgContainer = document.querySelector(".msg-container");
let msg = document.querySelector("#msg");

let turnO = true; //playerX, playerO
let count = 0; //To Track Draw

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

const resetGame = () => {
  turnO = true;
  count = 0;
  enableBoxes();
  msgContainer.classList.add("hide");
};

boxes.forEach((box) => {
  box.addEventListener("click", () => {
    if (turnO) {
      //playerO
      box.innerText = "O";
      turnO = false;
    } else {
      //playerX
      box.innerText = "X";
      turnO = true;
    }
    box.disabled = true;
    count++;

    let isWinner = checkWinner();

    if (count === 9 && !isWinner) {
      gameDraw();
    }
  });
});

const gameDraw = () => {
  msg.innerText = `Game was a Draw.`;
  msgContainer.classList.remove("hide");
  disableBoxes();
};

const disableBoxes = () => {
  for (let box of boxes) {
    box.disabled = true;
  }
};

const enableBoxes = () => {
  for (let box of boxes) {
    box.disabled = false;
    box.innerText = "";
  }
};

const showWinner = (winner) => {
  msg.innerText = `Congratulations, Winner is ${winner}`;
  msgContainer.classList.remove("hide");
  disableBoxes();
};

const checkWinner = () => {
  for (let pattern of winPatterns) {
    let pos1Val = boxes[pattern[0]].innerText;
    let pos2Val = boxes[pattern[1]].innerText;
    let pos3Val = boxes[pattern[2]].innerText;

    if (pos1Val != "" && pos2Val != "" && pos3Val != "") {
      if (pos1Val === pos2Val && pos2Val === pos3Val) {
        showWinner(pos1Val);
        return true;
      }
    }
  }
};

newGameBtn.addEventListener("click", resetGame);
resetBtn.addEventListener("click", resetGame);

Live Demo

You can check out the live demo of the Tic-Tac-Toe Game here.

Conclusion

Building this Tic-Tac-Toe game was an enjoyable experience that allowed me to practice JavaScript, especially in creating interactive web applications. I hope this project inspires you to build your own games and explore the possibilities with JavaScript. Happy coding!

Credits

This project was developed as part of my ongoing journey to improve my web development skills, with a focus on JavaScript and DOM manipulation.

Author

  • Abhishek Gurjar
    • GitHub Profile

The above is the detailed content of Build a Tic Tac Toe Game Website. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Lost CSS Tricks of Cohost.orgThe Lost CSS Tricks of Cohost.orgApr 25, 2025 am 09:51 AM

In this post, Blackle Mori shows you a few of the hacks found while trying to push the limits of Cohost’s HTML support. Use these if you dare, lest you too get labelled a CSS criminal.

Next Level CSS Styling for CursorsNext Level CSS Styling for CursorsApr 23, 2025 am 11:04 AM

Custom cursors with CSS are great, but we can take things to the next level with JavaScript. Using JavaScript, we can transition between cursor states, place dynamic text within the cursor, apply complex animations, and apply filters.

Worlds Collide: Keyframe Collision Detection Using Style QueriesWorlds Collide: Keyframe Collision Detection Using Style QueriesApr 23, 2025 am 10:42 AM

Interactive CSS animations with elements ricocheting off each other seem more plausible in 2025. While it’s unnecessary to implement Pong in CSS, the increasing flexibility and power of CSS reinforce Lee's suspicion that one day it will be a

Using CSS backdrop-filter for UI EffectsUsing CSS backdrop-filter for UI EffectsApr 23, 2025 am 10:20 AM

Tips and tricks on utilizing the CSS backdrop-filter property to style user interfaces. You’ll learn how to layer backdrop filters among multiple elements, and integrate them with other CSS graphical effects to create elaborate designs.

SMIL on?SMIL on?Apr 23, 2025 am 09:57 AM

Well, it turns out that SVG's built-in animation features were never deprecated as planned. Sure, CSS and JavaScript are more than capable of carrying the load, but it's good to know that SMIL is not dead in the water as previously

'Pretty' is in the eye of the beholder'Pretty' is in the eye of the beholderApr 23, 2025 am 09:40 AM

Yay, let's jump for text-wrap: pretty landing in Safari Technology Preview! But beware that it's different from how it works in Chromium browsers.

CSS-Tricks Chronicles XLIIICSS-Tricks Chronicles XLIIIApr 23, 2025 am 09:35 AM

This CSS-Tricks update highlights significant progress in the Almanac, recent podcast appearances, a new CSS counters guide, and the addition of several new authors contributing valuable content.

Tailwind's @apply Feature is Better Than it SoundsTailwind's @apply Feature is Better Than it SoundsApr 23, 2025 am 09:23 AM

Most of the time, people showcase Tailwind's @apply feature with one of Tailwind's single-property utilities (which changes a single CSS declaration). When showcased this way, @apply doesn't sound promising at all. So obvio

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment