Notifications 0

CodeGoundAI

ReadsNew

Speed TestNew

Code Grounds

RustGo LangNode JSPython 3C++JavaWeb(HTML, CSS, JS)

Data Grounds

RedisMongoDBPostgres

Tools New

Epoch ConverterCanvas Drawing boardBase64 EncodeBase64 DecodeJSON Web TokensJSON Diff

Popular

ReadsGrounds

Features

Realtime SharingShared OwnershipFast CompilationCloud Storage

Contact us

[email protected]

More to Explore

Sitemap

We @ CodeGroundAI

About UsPrivacy Policy

Building a Simple Tic-Tac-Toe Game with HTML, CSS, and JavaScript

Harsh Kothari - April 4, 2025


In this tutorial, we'll explore how to create a classic Tic-Tac-Toe game using only HTML, CSS, and JavaScript, without the need for any external assets. This game is a great introduction to basic web programming concepts such as handling user interactions, updating the DOM, and managing game logic.


Step 1: Setting Up the Project

Create a new folder for your project and inside it, create three files:

  • index.html — the main HTML document.
  • style.css — for styling the game.
  • script.js — to handle the game logic.


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 Game</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div id="gameBoard" class="game-board"></div>
    <script src="script.js"></script>
</body>
</html>


Step 2: Styling the Game

style.css

body {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    margin: 0;
    background-color: #f0f0f0;
}

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

.cell {
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #fff;
    font-size: 2em;
    cursor: pointer;
    user-select: none;
}


Step 3: JavaScript for Game Logic

script.js

const gameBoard = document.getElementById('gameBoard');
let currentPlayer = 'X';
const gameState = Array(9).fill(null);

function checkWinner() {
    const winPatterns = [
        [0, 1, 2], [3, 4, 5], [6, 7, 8], // Rows
        [0, 3, 6], [1, 4, 7], [2, 5, 8], // Columns
        [0, 4, 8], [2, 4, 6] // Diagonals
    ];

    for (let pattern of winPatterns) {
        const [a, b, c] = pattern;
        if (gameState[a] && gameState[a] === gameState[b] && gameState[a] === gameState[c]) {
            return gameState[a];
        }
    }
    return null;
}

function cellClicked(e) {
    const idx = e.target.getAttribute('data-index');
    if (gameState[idx] || checkWinner()) {
        return;
    }
    gameState[idx] = currentPlayer;
    e.target.textContent = currentPlayer;
    currentPlayer = currentPlayer === 'X' ? 'O' : 'X';

    const winner = checkWinner();
    if (winner) {
        alert(`${winner} wins!`);
    } else if (!gameState.includes(null)) {
        alert("It's a draw!");
    }
}

function createBoard() {
    for (let i = 0; i < gameState.length; i++) {
        const cell = document.createElement('div');
        cell.classList.add('cell');
        cell.setAttribute('data-index', i);
        cell.addEventListener('click', cellClicked);
        gameBoard.appendChild(cell);
    }
}

createBoard();


Conclusion: Running Your Game

Now that the game is set up, open your index.html file in any modern web browser to start playing Tic-Tac-Toe. You should see a grid of 9 squares where two players can take turns clicking to place 'X' or 'O'. The game will check for a winner after each move and declare a winner or a draw.

This simple project introduces key programming concepts such as arrays, loops, and functions, and shows how they can be applied to create interactive web applications. Feel free to expand this game by adding features like player vs computer mode, score tracking, or stylish animations. Enjoy your development journey!



Bonus: Try your game here

https://www.thecodeground.in/ground/web/41c0a3a0-eedf-4647-94ad-23547a10fd14


CodeGroundAI

CodeGroundAI is your all-in-one platform for seamless online coding. Whether you're a beginner or a pro, our IDE supports multiple programming languages, offers real-time collaboration, and provides a comprehensive toolkit for debugging, testing, and code execution.

Explore tools like the EPOCH Convertor, JSON Diff Checker, JWT Decoder, and Base64 Encoder/Decoder. With a real-time code-sharing platform and advanced comparison utilities, CodeGroundAI ensures you have everything you need for efficient development and accurate data handling.

Languages
  •  NodeJs
  •  Python
  •  Rust
  •  C++
  •  Java
  •  Golang
  •  Web
  •  MongoDB
  •  Redis
  •  Postgres
Tools
  •  Epoch Converter
  •  JSON Differentiator
  •  JWT Debugger
  •  Base64 Decode
  •  Base64 Encode
  •  Canvas
  •  Speed-Test
  •  Reads
Contact Us

Have questions or need support? Reach out to us for a smooth coding experience.

[email protected]

Connect with us on your favourite platform.

CodeGroundAI © 2024. All rights reserved.