Create a Responsive Tic-Tac-Toe Game with HTML, CSS, and JavaScript šŸ˜Š

Posted by

How to Build a Responsive Tic-Tac-Toe Game

/* CSS for the Tic-Tac-Toe Game */
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
#board {
display: grid;
grid-template-columns: 100px 100px 100px;
grid-gap: 10px;
background-color: #fff;
border: 2px solid #000;
}
.box {
width: 100px;
height: 100px;
display: flex;
justify-content: center;
align-items: center;
font-size: 32px;
cursor: pointer;
}

How to Build a Responsive Tic-Tac-Toe Game

// JavaScript for the Tic-Tac-Toe Game
let player1 = ‘X’;
let player2 = ‘O’;
let currentPlayer = player1;
let board = [”, ”, ”, ”, ”, ”, ”, ”, ”];

function playerTurn(box) {
let index = Array.from(box.parentNode.children).indexOf(box);
if (board[index] === ”) {
board[index] = currentPlayer;
box.innerHTML = currentPlayer;
checkWinner();
currentPlayer = currentPlayer === player1 ? player2 : player1;
}
}

function checkWinner() {
const winningCombos = [
[0, 1, 2], [3, 4, 5], [6, 7, 8],
[0, 3, 6], [1, 4, 7], [2, 5, 8],
[0, 4, 8], [2, 4, 6]
];
for (let combo of winningCombos) {
let [a, b, c] = combo;
if (board[a] && board[a] === board[b] && board[a] === board[c]) {
alert(currentPlayer + ‘ is the winner!’);
resetGame();
break;
}
}
if (!board.includes(”)) {
alert(‘It is a draw!’);
resetGame();
}
}

function resetGame() {
board = [”, ”, ”, ”, ”, ”, ”, ”, ”];
Array.from(document.querySelectorAll(‘.box’)).forEach(box => box.innerHTML = ”);
}

0 0 votes
Article Rating
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@rizwankhan-ki2ew
6 months ago

Awesome