Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App

Simple Tic-Tac-Toe Game using JavaScript

Last Updated : 06 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

This is a simple and interactive Tic Tac Toe game built using HTML, CSS, and JavaScript. Players take turns to mark X and O on the grid, with automatic win detection and the option to reset or start a new game.

What We’re Going to Create

  • Players take turns marking X and O on a 3x3 grid, with real-time interaction.
  • The game checks for a winner or a draw, displaying messages accordingly.
  • The layout adapts to different screen sizes, with a reset button to start a new game.

Project Preview

Screenshot-2025-01-25-125249
Simple Tic-Tac-Toe Game using JavaScript

Simple Tic-Tac-Toe Game - HTML and CSS Code

This Tic Tac Toe game features a simple yet interactive design, allowing two players to take turns marking X and O on a 3x3 grid. The layout is responsive, with a reset button to restart the game.

HTML
<html> <head>     <style>         * {             margin: 0;             padding: 0;         }         body {             background-color: lightcyan;             text-align: center;         }         .container {             height: 70vh;             display: flex;             justify-content: center;             align-items: center;         }         .game {             height: 60vmin;             width: 60vmin;             display: flex;             flex-wrap: wrap;             gap: 1.5vmin;             justify-content: center;         }         .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: red;             background-color: yellow;         }         #reset {             padding: 1rem;             font-size: 1.25rem;             background: #191913;             color: white;             border-radius: 1rem;             border: none;         }         .box:hover {             background-color: chocolate;         }         #new-btn {             padding: 1rem;             font-size: 1.25rem;             background: #191913;             color: white;             border-radius: 1rem;             border: none;         }         #msg {             font-size: 8vmin;         }         .msg-container {             height: 30vmin;         }         .hide {             display: none;         }     </style> </head> <body>     <div class="msg-container hide">         <p id="msg">Winner</p>         <button id="new-btn">New Game</button>     </div>     <main>         <h1>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">Reset Game</button>     </main> </body> </html> 

In this example

  • The game board is a flexbox-based grid inside a .container, ensuring a centered and responsive design.
  • Buttons for each cell have hover effects, rounded corners, and shadows, enhancing user experience.
  • The winner message container (.msg-container) is hidden by default and appears when the game ends, with buttons to start a new game or reset.

Simple Tic-Tac-Toe Game - JavaScript code

The JavaScript code manages the gameplay of Tic Tac Toe, including alternating turns, detecting winners based on patterns, and handling game resets.

JavaScript
let boxes = document.querySelectorAll('.box'); let resetBtn = document.querySelector('#reset'); let turnO = true; // Player O starts let newGameBtn = document.querySelector('#new-btn'); let msgContainer = document.querySelector('.msg-container'); let msg = document.querySelector('#msg');  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] ];  boxes.forEach((box) => {     box.addEventListener('click', function () {         if (turnO) {             box.innerText = 'O';             box.style.color = 'green';             turnO = false;             box.disabled = true;             checkWinner();         } else {             box.innerText = 'X';             box.style.color = 'black';             turnO = true;             box.disabled = true;             checkWinner();         }     }); });  const enableBoxes = () => {     for (let box of boxes) {         box.disabled = false;         box.innerText = "";     } };  const disableBoxes = () => {     for (let box of boxes) {         box.disabled = true;     } };  const showWinner = (winner) => {     msg.innerText = `Congratulations, Winner is ${winner}`;     msgContainer.classList.remove('hide');     disableBoxes(); };  const checkWinner = () => {     let hasWin = false;     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!==""              && pos1Val === pos2Val && pos2Val === pos3Val) {             showWinner(pos1Val);             hasWin = true;             return;         }     }      if (!hasWin) {         const allBoxes = [...boxes].every((box) => box.innerText !== "");         if (allBoxes) {             msgContainer.classList.remove('hide');             msg.innerText = 'Match Drawn';         }     } };  const resetGame = () => {     turnO = true;     enableBoxes();     msgContainer.classList.add('hide'); };  newGameBtn.addEventListener('click', resetGame); resetBtn.addEventListener('click', resetGame); 

In this example

  • The turnO variable tracks the player, placing 'X' or 'O' on each button click and switching turns.
  • box.addEventListener('click', …) detects clicks, marks the cell, and checks for a winner after each move.
  • checkWinner() scans predefined win patterns to see if any row, column, or diagonal has three identical marks.
  • resetGame() clears the board, re-enables boxes, and hides the winner message for a fresh start.
  • showWinner() reveals the winning message, disables all grid buttons, and stops further moves.

Simple Tic-Tac-Toe Game - Complete code

HTML
<html> <head>     <style>         * {             margin: 0;             padding: 0;         }         body {             background-color: lightcyan;             text-align: center;         }         .container {             height: 70vh;             display: flex;             justify-content: center;             align-items: center;         }         .game {             height: 60vmin;             width: 60vmin;             display: flex;             flex-wrap: wrap;             gap: 1.5vmin;             justify-content: center;         }         .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: red;             background-color: yellow;         }         #reset {             padding: 1rem;             font-size: 1.25rem;             background: #191913;             color: white;             border-radius: 1rem;             border: none;         }         .box:hover {             background-color: chocolate;         }         #new-btn {             padding: 1rem;             font-size: 1.25rem;             background: #191913;             color: white;             border-radius: 1rem;             border: none;         }         #msg {             font-size: 8vmin;         }         .msg-container {             height: 30vmin;         }         .hide {             display: none;         }     </style> </head> <body>     <div class="msg-container hide">         <p id="msg">Winner</p>         <button id="new-btn">New Game</button>     </div>     <main>         <h1>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">Reset Game</button>     </main>     <script>         let boxes = document.querySelectorAll('.box');         let resetBtn = document.querySelector('#reset');         let turnO = true; // Player O starts         let newGameBtn = document.querySelector('#new-btn');         let msgContainer = document.querySelector('.msg-container');         let msg = document.querySelector('#msg');          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]         ];          boxes.forEach((box) => {             box.addEventListener('click', function () {                 if (turnO) {                     box.innerText = 'O';                     box.style.color = 'green';                     turnO = false;                     box.disabled = true;                     checkWinner();                 } else {                     box.innerText = 'X';                     box.style.color = 'black';                     turnO = true;                     box.disabled = true;                     checkWinner();                 }             });         });          const enableBoxes = () => {             for (let box of boxes) {                 box.disabled = false;                 box.innerText = "";             }         };          const disableBoxes = () => {             for (let box of boxes) {                 box.disabled = true;             }         };          const showWinner = (winner) => {             msg.innerText = `Congratulations, Winner is ${winner}`;             msgContainer.classList.remove('hide');             disableBoxes();         };          const checkWinner = () => {             let hasWin = false;             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!=="" &&                      pos1Val === pos2Val && pos2Val === pos3Val) {                     showWinner(pos1Val);                     hasWin = true;                     return;                 }             }              if (!hasWin) {                 const allBoxes = [...boxes].every((box) => box.innerText !== "");                 if (allBoxes) {                     msgContainer.classList.remove('hide');                     msg.innerText = 'Match Drawn';                 }             }         };          const resetGame = () => {             turnO = true;             enableBoxes();             msgContainer.classList.add('hide');         };          newGameBtn.addEventListener('click', resetGame);         resetBtn.addEventListener('click', resetGame);     </script> </body> </html> 

A

asmitsirohi
Improve
Article Tags :
  • Technical Scripter
  • JavaScript
  • Web Technologies
  • Technical Scripter 2020
  • JavaScript-Projects

Similar Reads

    Create a snake game using HTML, CSS and JavaScript
    Snake Game is a single-player game where the snake gets bigger by eating the food and tries to save itself from the boundary of the rectangle and if the snake eats their own body the game will be over.Game Rules:If the snake goes out of the boundary or eats its own body the game will be over.Prerequ
    4 min read
    Design Dragon's World Game using HTML CSS and JavaScript
    Project Introduction: "Dragon's World" is a game in which one dragon tries to save itself from the other dragon by jumping over the dragon which comes in its way. The score is updated when one dragon saves himself from the other dragon.  The project will contain HTML, CSS and JavaScript files. The H
    6 min read
    Word Guessing Game using HTML CSS and JavaScript
    In this article, we will see how can we implement a word-guessing game with the help of HTML, CSS, and JavaScript. Here, we have provided a hint key & corresponding total number of gaps/spaces depending upon the length of the word and accept only a single letter as an input for each time. If it
    4 min read
    Build a Memory Card Game Using HTML CSS and JavaScript
    A memory game is a type of game that can be used to test or check the memory of a human being. It is a very famous game. In this game, the player has some cards in front of him and all of them facing down initially. The player has to choose a pair of cards at one time and check whether the faces of
    6 min read
    Create a Simon Game using HTML CSS & JavaScript
    In this article, we will see how to create a Simon Game using HTML, CSS, and JavaScript. In a Simon game, if the player succeeds, the series becomes progressively longer and more complex. Once the user is unable to repeat the designated order of the series at any point, the game is over.Prerequisite
    5 min read
    Create a Minesweeper Game using HTML CSS & JavaScript
    Minesweeper is a classic puzzle game that challenges your logical thinking and deduction skills. It's a great project for developers looking to improve their front-end web development skills. In this article, we'll walk through the steps to create a Minesweeper game using HTML, CSS, and JavaScript.
    4 min read
    Whack-a-Mole Game using HTML CSS and JavaScript
    Whack-A-Mole is a classic arcade-style game that combines speed and precision. The game is set in a grid of holes, and the objective is to "whack" or hit the moles that randomly pop up from these holes. In this article, we are going to create Whack-a-Mole using HTML, CSS and JavaScript.Preview Image
    3 min read
    Simple HTML CSS and JavaScript Game
    Tap-the-Geek is a simple game, in which the player has to tap the moving GeeksForGeeks logo as many times as possible to increase their score. It has three levels easy, medium, and hard. The speed of the circle will be increased from level easy to hard. I bet, it is very difficult for the players to
    4 min read
    Design Hit the Mouse Game using HTML, CSS and Vanilla Javascript
    In this article, we are going to create a game in which a mouse comes out from the holes, and we hit the mouse with a hammer to gain points. It is designed using HTML, CSS & Vanilla JavaScript.HTML Code:First, we create an HTML file (index.html).Now, after creating the HTML file, we are going to
    5 min read
    Create a 2D Brick Breaker Game using HTML CSS and JavaScript
    In this article, we will see how to create a 2D Brick Breaker Game using HTML CSS & JavaScript. Most of you already played this game on your Mobile Phones where you control a paddle to bounce a ball, aiming to demolish a wall of bricks arranged at the top of the screen. 2D Brick Breaker Game is
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences