Codeground AI
EditorWorkspacesCoursesInterviews Ground Call New Daily Challenges
AI tools
  • Resume De-AI-ifierHumanize AI-written resumes & flag clichés
  • AI Email RewriterMake robotic AI emails sound human
  • AI Code DetectorSpot AI-generated or copied code
  • AI Watermark ToolStrip or embed invisible text watermarks
  • README GeneratorCreate, edit & preview GitHub READMEs
  • SQL AssistantExplain SQL or generate from English
  • Text SummarizerCondense articles and notes instantly
  • AI Text GeneratorDraft blogs, emails, and product copy
  • System Prompt DiffCompare prompts for behavior & risk deltas
  • AI Code SecurityScan for secrets, SQLi, SSRF & more
  • Commit Message GeneratorConventional commits from a git diff
  • Interview Question PackJD → coding, behavioral & system design Qs
  • Schema Seed DataTS/SQL schema → realistic JSON fixtures
  • GraphQL ExplainerExplain queries and debug GraphQL errors
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
  • Protobuf DecoderDecode Base64 or hex protobuf payloads
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
ReadsGames
Sign In Sign Up
EditorWorkspacesCoursesInterviewsGround CallDaily ChallengesReadsGames
Tools
Resume De-AI-ifierAI Email RewriterAI Code DetectorAI Watermark ToolREADME GeneratorSQL AssistantText SummarizerAI Text GeneratorSystem Prompt DiffAI Code SecurityCommit Message GeneratorInterview Question PackSchema Seed DataGraphQL ExplainerJSON DiffDiff & PatchJSON FormatterSQL FormatterJSON ↔ CSVBase64 CodecLog ParserProtobuf DecoderJWT 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. Interactive courses, 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
  • React (JSX)
  • Web (HTML/CSS/JS)
  • Shell / Bash
  • Ruby
  • Lua
  • Groovy

Databases

  • MongoDB
  • PostgreSQL
  • MySQL
  • Redis
  • ClickHouse

AI Tools

  • Resume De-AI-ifier
  • AI Email Rewriter
  • AI Code Detector
  • AI Watermark Tool
  • README Generator
  • SQL Assistant
  • Text Summarizer
  • AI Text Generator
  • System Prompt Diff
  • AI Code Security
  • Commit Message Generator
  • Interview Question Pack
  • Schema Seed Data
  • GraphQL Explainer

Data tools

  • JSON Diff
  • Diff & Patch
  • JSON Formatter
  • JSON ↔ CSV
  • SQL Formatter
  • SQL Query Generator
  • Log Parser
  • Protobuf Decoder

Utilities

  • JWT Debugger
  • Base64 Codec
  • Regex Tester
  • Epoch Converter
  • Current Unix Time
  • Timestamp Diff
  • Cron Builder
  • Meeting Planner
  • ENV Linter
  • Date Math
  • QR Generator
  • UUID Generator
  • Color Picker
  • Password Generator
  • Speed Test
  • Diagram Studio
  • Canvas Drawing
  • Lucky Draw Wheel

Platform & company

  • All Tools
  • Courses
  • Daily Challenges
  • Interviews
  • Reads
  • Games
  • Turtle (Kids)
  • About Us
  • Privacy Policy
  • Sitemap
  • Contact

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

About·Privacy·Sitemap·[email protected]