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

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...

Create Your Own Chrome Dino Game with HTML, CSS, and JavaScript

Have you ever wanted to create your own version of the Chrome Dino game? With just a few lines of HTML, CSS, and JavaScript, you can bring this iconic game to life. Here's a step-by-step guide to building a simple yet fun version of the Dino game. HTML Start by creating an HTML file to define the game structure. You'll need a container for the game, a <div> for the dinosaur, another <div> for the cactus, and a score display. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Chrome Dino Game</title> <link rel="stylesheet" href="styles.css"> </head> <body> <div class="game-container"> <div id="dino" class="dino"></div> <div id="cactus" class="cactus...