Player X's turn
<script>
const board = document.getElementById("board");
const status = document.getElementById("status");
let currentPlayer = "X";
let cells = Array(9).fill(null);
function checkWinner() {
const winPatterns = [
[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 (const pattern of winPatterns) {
const [a, b, c] = pattern;
if (cells[a] && cells[a] === cells[b] && cells[a] === cells[c]) {
status.innerText = `Player ${cells[a]} wins!`;
document.querySelectorAll(".cell").forEach(cell => cell.classList.add("taken"));
return true;
}
}
if (!cells.includes(null)) {
status.innerText = "It's a draw!";
return true;
}
return false;
}
function handleClick(index) {
if (!cells[index]) {
cells[index] = currentPlayer;
document.getElementById(`cell-${index}`).innerText = currentPlayer;
document.getElementById(`cell-${index}`).classList.add("taken");
if (!checkWinner()) {
currentPlayer = currentPlayer === "X" ? "O" : "X";
status.innerText = `Player ${currentPlayer}'s turn`;
}
}
}
function createBoard() {
for (let i = 0; i < 9; i++) {
const cell = document.createElement("div");
cell.classList.add("cell");
cell.id = `cell-${i}`;
cell.addEventListener("click", () => handleClick(i));
board.appendChild(cell);
}
}
createBoard();
</script>
-
Notifications
You must be signed in to change notification settings - Fork 0
Usha2007-feb/tic-tac-toe
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
About
No description, website, or topics provided.
Resources
Stars
Watchers
Forks
Releases
No releases published
Packages 0
No packages published