Skip to main content

Creating an Interactive Tic Tac Toe Game


In this tutorial, we'll walk through the steps to create a dynamic Tic Tac Toe game using HTML, CSS, and JavaScript. This classic game is a great way to practice your web development skills and learn more about interactive web applications.

HTML Structure

We'll start with the HTML structure, which includes the game board, a reset button, and a status display:

<!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</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="container">
        <h1>Tic Tac Toe</h1>
        <div id="board" class="board"></div>
        <button id="reset">Reset Game</button>
        <div id="status"></div>
        <canvas id="winningLine"></canvas>
    </div>
    <script src="script.js"></script>
</body>
</html>
    

CSS Styling

Next, we'll add some CSS to style our game board and other elements:

body {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background-color: #f0f0f0;
    font-family: Arial, sans-serif;
    margin: 0;
}

.container {
    text-align: center;
    position: relative;
}

.board {
    display: grid;
    grid-template-columns: repeat(3, 100px);
    grid-gap: 10px;
    margin: 20px auto;
    position: relative;
}

.cell {
    width: 100px;
    height: 100px;
    background-color: #fff;
    border: 1px solid #ccc;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 2rem;
    cursor: pointer;
}

.cell.x {
    color: #ff4d4d;
}

.cell.o {
    color: #4d4dff;
}

button {
    padding: 10px 20px;
    font-size: 1rem;
    cursor: pointer;
}

#status {
    margin-top: 20px;
    font-size: 1.2rem;
}

#winningLine {
    position: absolute;
    top: 0;
    left: 0;
    pointer-events: none;
}
    

JavaScript Functionality

Finally, we'll add the JavaScript to handle the game logic, including drawing the winning line:

const board = document.getElementById('board');
const resetButton = document.getElementById('reset');
const statusDisplay = document.getElementById('status');
const winningLine = document.getElementById('winningLine');

let cells;
let currentPlayer;
let gameActive;
let gameState;

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

function initializeGame() {
    board.innerHTML = '';
    currentPlayer = 'x';
    gameActive = true;
    gameState = Array(9).fill(null);
    statusDisplay.textContent = `Player ${currentPlayer.toUpperCase()}'s turn`;
    for (let i = 0; i < 9; i++) {
        const cell = document.createElement('div');
        cell.classList.add('cell');
        cell.dataset.index = i;
        cell.addEventListener('click', handleCellClick);
        board.appendChild(cell);
    }
    cells = document.querySelectorAll('.cell');
    winningLine.width = board.offsetWidth;
    winningLine.height = board.offsetHeight;
    const ctx = winningLine.getContext('2d');
    ctx.clearRect(0, 0, winningLine.width, winningLine.height);
}

function handleCellClick(event) {
    const clickedCell = event.target;
    const clickedCellIndex = parseInt(clickedCell.dataset.index);
    if (gameState[clickedCellIndex] !== null || !gameActive) {
        return;
    }
    gameState[clickedCellIndex] = currentPlayer;
    clickedCell.classList.add(currentPlayer);
    clickedCell.textContent = currentPlayer.toUpperCase();
    checkResult();
    currentPlayer = currentPlayer === 'x' ? 'o' : 'x';
    if (gameActive) {
        statusDisplay.textContent = `Player ${currentPlayer.toUpperCase()}'s turn`;
    }
}

function checkResult() {
    let roundWon = false;
    for (let i = 0; i < winningConditions.length; i++) {
        const [a, b, c] = winningConditions[i];
        if (gameState[a] && gameState[a] === gameState[b] && gameState[a] === gameState[c]) {
            roundWon = true;
            drawWinningLine(a, c);
            break;
        }
    }

    if (roundWon) {
        statusDisplay.textContent = `Player ${currentPlayer.toUpperCase()} has won!`;
        gameActive = false;
        return;
    }

    const roundDraw = !gameState.includes(null);
    if (roundDraw) {
        statusDisplay.textContent = 'Draw!';
        gameActive = false;
        return;
    }
}

function drawWinningLine(start, end) {
    const cellSize = 100;
    const cellGap = 10;

    const startX = (start % 3) * (cellSize + cellGap) + cellSize / 2;
    const startY = Math.floor(start / 3) * (cellSize + cellGap) + cellSize / 2;
    const endX = (end % 3) * (cellSize + cellGap) + cellSize / 2;
    const endY = Math.floor(end / 3) * (cellSize + cellGap) + cellSize / 2;

    const ctx = winningLine.getContext('2d');
    ctx.beginPath();
    ctx.moveTo(startX, startY);
    ctx.lineTo(endX, endY);
    ctx.lineWidth = 5;
    ctx.strokeStyle = '#ff4d4d';
    ctx.stroke();
}

resetButton.addEventListener('click', initializeGame);

initializeGame();
    

Conclusion

With these steps, you can create an interactive Tic Tac Toe game. This project demonstrates how to combine HTML, CSS, and JavaScript to build a web-based game. Feel free to customize the game further and add more features to enhance the gameplay experience.

Comments

Popular posts from this blog

How To Make Casio Calculator using HTML, CSS Javascript with all Functional features

Creating a Casio FX-991CW calculator using HTML, CSS, and JavaScript is an engaging project for learning web development. This guide will help you create a functional calculator that can perform basic arithmetic, trigonometric functions, and square root calculations. Step 1: HTML Structure First, set up the HTML structure for the calculator. Here's an example: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Casio FX-991CW Calculator</title> <link rel="stylesheet" href="styles.css"> </head> <body> <div class="calculator"> <input type="text" class="calculator-screen" id="main-screen" value="" disabled /> <input type="text" class="calculator-screen" ...

Creating a Simple Car Racing Game with HTML, CSS, Javascript

In this post, we will create a simple car racing game using HTML, CSS, and JavaScript. This game will feature a player car, an opponent car, and a score counter. The player can move their car left and right to avoid collisions with the opponent car. Let's dive into the code! HTML Structure The HTML structure consists of a game area that contains the road, player car, opponent car, and score display: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Car Racing Game</title> <link rel="stylesheet" href="styles.css"> </head> <body> <div class="gameArea"> <div class="road"></div> <div class="playerCar"></div> <div class="opponentCar"></div...