Codeground AI
EditorWorkspacesInterviews Meet New Daily Challenges
Data & format
  • JSON DiffCompare two JSON blobs side by side
  • Diff & PatchGenerate unified patches from text/code
  • JSON FormatterPretty-print and validate JSON
  • SQL FormatterFormat SQL and explain with AI
  • JSON ↔ CSVConvert tabular data both ways
  • Base64 CodecEncode and decode Base64
  • Log ParserPretty-print logs and highlight severity
Security & web
  • JWT DebuggerDecode and verify JSON Web Tokens
  • ENV LinterLint .env files and redact values
  • Password GeneratorStrong, configurable passwords
  • UUID GeneratorGenerate UUID v1/v4 in bulk
  • Regex TesterTest patterns in real time
Generators & utilities
  • Epoch ConverterConvert between Unix and dates
  • Meeting PlannerMatrix of slots across timezones
  • Date MathAdd duration with timezone awareness
  • Cron BuilderValidate cron and preview next runs
  • QR GeneratorMake scannable QR codes
  • Color PickerPick & convert colors
  • Lucky Draw WheelSpin-the-wheel utility
Network & creative
  • Speed TestMeasure network throughput
  • Diagram StudioFlowcharts & architecture diagrams
  • Canvas DrawingA scratchpad for sketches
  • Turtle GameCoding game for kids
See everything Codeground AI offers
Reads
Sign In Sign Up
EditorWorkspacesInterviewsMeetDaily ChallengesReads
Tools
JSON DiffDiff & PatchJSON FormatterSQL FormatterJSON ↔ CSVBase64 CodecLog ParserJWT DebuggerENV LinterPassword GeneratorUUID GeneratorRegex TesterEpoch ConverterMeeting PlannerDate MathCron BuilderQR GeneratorColor PickerLucky Draw WheelSpeed TestDiagram StudioCanvas DrawingTurtle Game

Sign InSign Up

Notifications 0

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


Codeground AI

The browser is the only IDE you need. Cloud workspaces, 15+ language runtimes, secure interview tooling and a polished developer toolbox — all in one tab.

Languages

  • Node.js
  • Python
  • Java
  • C++
  • Go
  • Rust
  • TypeScript
  • Web (HTML/CSS/JS)
  • Shell / Bash

Databases

  • MongoDB
  • PostgreSQL
  • MySQL
  • Redis
  • ClickHouse

Tools

  • JSON Diff
  • Diff & Patch
  • JSON Formatter
  • JSON ↔ CSV
  • JWT Debugger
  • Base64 Codec
  • Regex Tester
  • Epoch Converter
  • Cron Builder
  • Meeting Planner
  • SQL Formatter
  • ENV Linter
  • Date Math
  • Log Parser
  • QR Generator
  • UUID Generator
  • Color Picker
  • Password Generator
  • Speed Test
  • Diagram Studio
  • Canvas Drawing
  • Lucky Draw Wheel

Platform

  • Daily Challenges
  • Interviews
  • Reads
  • Turtle (Kids)

Company

  • About Us
  • Privacy Policy
  • Sitemap
  • Contact

© 2026 Codeground AI. Built for developers who want to ship.

About·Privacy·Sitemap·[email protected]