Tic Tac Toe Game

Technologies used -
Description

The Interactive Tic Tac Toe Game is a classic two-player game implemented using HTML, CSS, and JavaScript. This engaging application allows users to challenge each other in a fun and competitive environment, enhancing their strategic thinking and problem-solving skills. Players take turns placing their marks (X or O) in a 3×3 grid, with the objective of forming a line of three marks horizontally, vertically, or diagonally.

The game features an intuitive user interface that clearly displays the current player’s turn and provides feedback upon winning. Users can also reset the game at any time, making it easy to start a new round without refreshing the entire page. The incorporation of sound effects adds an extra layer of enjoyment, making the gaming experience even more immersive.

Highlighted Source Code
				
					let turn = "X";
let gameover = false;

const changeTurn = () => {
    return turn === "X" ? "0" : "X";
}

const checkWin = () => {
    let boxTexts = document.getElementsByClassName("boxText");
    let wins = [
        [0, 1, 2],
        [3, 4, 5],
        [6, 7, 8],
        [0, 3, 6],
        [1, 4, 7],
        [2, 5, 8],
        [0, 4, 8],
        [2, 4, 6],
    ];

    wins.forEach(e => {
        if ((boxTexts[e[0]].innerText === boxTexts[e[1]].innerText && boxTexts[e[2]].innerText === boxTexts[e[1]].innerText) && boxTexts[e[0]].innerText !== "") {
            document.querySelector(".info").innerText = boxTexts[e[0]].innerText + " Won";
            gameover = true;
            document.querySelector(".imgBox").getElementsByTagName("img")[0].style.width = "200px";
        }
    });
}

let boxes = document.getElementsByClassName("box");
Array.from(boxes).forEach((element) => {
    let boxText = element.querySelector(".boxText");
    element.addEventListener('click', () => {
        if (boxText.innerText === "") {
            boxText.innerText = turn;
            turn = changeTurn();
            checkWin();
            if (!gameover) {
                document.getElementsByClassName("info")[0].innerText = "Turn for " + turn;
            }
        }
    });
});

document.getElementById("reset").addEventListener("click", () => {
    let boxText = document.querySelectorAll(".boxText");
    Array.from(boxText).forEach(element => {
        element.innerText = " ";
    });
    turn = "X";
    gameover = false;
    document.getElementsByClassName("info")[0].innerText = "Turn for " + turn;
});
				
			

Related Projects

Fun Project

Tic Tac Toe Game

The Interactive Tic Tac Toe Game lets two players compete in a 3×3 grid. It includes a simple interface, feedback on wins, and sound effects for added fun.

Read More »
Form & Input Handling

Text-to-Speech Converter

This Text-to-Speech app lets you type text and listen to it spoken aloud in different voices. Choose a voice, click ‘Listen,’ and hear the text in real-time.

Read More »