Upload files to "/"
This commit is contained in:
@@ -0,0 +1,76 @@
|
||||
const board = Array.from(document.querySelectorAll('.cell'));
|
||||
const status = document.getElementById('status');
|
||||
const resetBtn = document.getElementById('resetBtn');
|
||||
|
||||
let currentPlayer = 'X';
|
||||
let gameActive = true;
|
||||
let gameState = ['', '', '', '', '', '', '', '', ''];
|
||||
|
||||
const winningConditions = [
|
||||
[0, 1, 2], [3, 4, 5], [6, 7, 8], // rows
|
||||
[0, 3, 6], [1, 4, 7], [2, 5, 8], // columns
|
||||
[0, 4, 8], [2, 4, 6] // diagonals
|
||||
];
|
||||
|
||||
const winningMessage = () => `Player ${currentPlayer} wins!`;
|
||||
const drawMessage = () => `Game ended in a draw!`;
|
||||
const currentPlayerTurn = () => `Player ${currentPlayer}'s turn`;
|
||||
|
||||
status.innerHTML = currentPlayerTurn();
|
||||
|
||||
function handleCellClick(e) {
|
||||
const cell = e.target;
|
||||
const cellIndex = parseInt(cell.getAttribute('data-index'));
|
||||
|
||||
if (gameState[cellIndex] !== '' || !gameActive) {
|
||||
return;
|
||||
}
|
||||
|
||||
gameState[cellIndex] = currentPlayer;
|
||||
cell.innerHTML = currentPlayer;
|
||||
cell.classList.add(currentPlayer.toLowerCase());
|
||||
|
||||
if (checkWin()) {
|
||||
status.innerHTML = winningMessage();
|
||||
gameActive = false;
|
||||
return;
|
||||
}
|
||||
|
||||
if (checkDraw()) {
|
||||
status.innerHTML = drawMessage();
|
||||
gameActive = false;
|
||||
return;
|
||||
}
|
||||
|
||||
currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
|
||||
status.innerHTML = currentPlayerTurn();
|
||||
}
|
||||
|
||||
function checkWin() {
|
||||
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]) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function checkDraw() {
|
||||
return !gameState.includes('');
|
||||
}
|
||||
|
||||
function resetGame() {
|
||||
currentPlayer = 'X';
|
||||
gameActive = true;
|
||||
gameState = ['', '', '', '', '', '', '', '', ''];
|
||||
status.innerHTML = currentPlayerTurn();
|
||||
|
||||
board.forEach(cell => {
|
||||
cell.innerHTML = '';
|
||||
cell.classList.remove('x', 'o');
|
||||
});
|
||||
}
|
||||
|
||||
board.forEach(cell => cell.addEventListener('click', handleCellClick));
|
||||
resetBtn.addEventListener('click', resetGame);
|
||||
Reference in New Issue
Block a user