Beginner’s Guide to Creating Tic Tac Toe Game using HTML, CSS, and JavaScript

Posted by

Create Tic Tac Toe with HTML, CSS, and JavaScript | Tutorial for BEGINNERS

/* Add CSS styling here */
.tic-tac-toe {
display: flex;
flex-wrap: wrap;
width: 300px;
}
.tic-tac-toe div {
width: 100px;
height: 100px;
display: flex;
justify-content: center;
align-items: center;
border: 1px solid #333;
font-size: 36px;
cursor: pointer;
}
.tic-tac-toe div:hover {
background-color: #f2f2f2;
}

Create Tic Tac Toe with HTML, CSS, and JavaScript | Tutorial for BEGINNERS

Welcome to this tutorial on how to create a simple Tic Tac Toe game using HTML, CSS, and JavaScript. This tutorial is perfect for beginners who are just starting to learn web development.

// Add JavaScript code here
let currentPlayer = ‘X’;
let board = [”, ”, ”, ”, ”, ”, ”, ”, ”];

function handleClick(index) {
if (board[index] === ”) {
board[index] = currentPlayer;
document.getElementById(‘tic-tac-toe’).children[index].innerHTML = currentPlayer;
if (checkWin()) {
alert(currentPlayer + ‘ wins!’);
resetBoard();
} else if (board.every(square => square !== ”)) {
alert(‘It’s a tie!’);
resetBoard();
} else {
currentPlayer = currentPlayer === ‘X’ ? ‘O’ : ‘X’;
}
}
}

function checkWin() {
const winConditions = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6]
];
return winConditions.some(condition => {
const [a, b, c] = condition;
return board[a] !== ” && board[a] === board[b] && board[b] === board[c];
});
}

function resetBoard() {
currentPlayer = ‘X’;
board = [”, ”, ”, ”, ”, ”, ”, ”, ”];
const squares = document.getElementById(‘tic-tac-toe’).children;
for (let i = 0; i < squares.length; i++) {
squares[i].innerHTML = '';
}
}

0 0 votes
Article Rating
4 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@kingreeses7212
10 months ago

Must have taken alot of HTML learning to create Noughts & Crosses in HTML

@tvJ4FK
10 months ago

Nice video, love a good game of tic tac toe.

@beyondultimate
10 months ago

Very interesting video! : )

@chuckf2156
10 months ago

Very interesting. I was always interested in coding but never could quite get it. Still cool though