Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#CSS #487

Open
polamreddykavyasree opened this issue Jan 27, 2025 · 0 comments
Open

#CSS #487

polamreddykavyasree opened this issue Jan 27, 2025 · 0 comments

Comments

@polamreddykavyasree
Copy link

const cells = document.querySelectorAll('.cell');
const statusDiv = document.querySelector('.status');
const resetBtn = document.getElementById('resetBtn');
let currentPlayer = 'X';
let board = Array(9).fill(null);
let isGameOver = false;

const winningCombinations = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6],
];

function handleClick(event) {
const index = event.target.dataset.index;
if (!board[index] && !isGameOver) {
board[index] = currentPlayer;
event.target.textContent = currentPlayer;
if (checkWinner()) {
statusDiv.textContent = Player ${currentPlayer} wins!;
isGameOver = true;
} else if (board.every(cell => cell)) {
statusDiv.textContent = 'It's a draw!';
isGameOver = true;
} else {
currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
}
}
}

function checkWinner() {
return winningCombinations.some(combination => {
return combination.every(index => board[index] === currentPlayer);
});
}

function resetGame() {
board = Array(9).fill(null);
cells.forEach(cell => (cell.textContent = ''));
currentPlayer = 'X';
isGameOver = false;
statusDiv.textContent = '';
}

cells.forEach(cell => cell.addEventListener('click', handleClick));
resetBtn.addEventListener('click', resetGame);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant