Simulate typing on a virtual typewriter
by velo_ninja
HTML
<div id="game-board">
<div id="row-0">
<div id="cell-0" class="cell"></div>
<div id="cell-1" class="cell"></div>
<div id="cell-2" class="cell"></div>
</div>
<div id="row-1">
<div id="cell-3" class="cell"></div>
<div id="cell-4" class="cell"></div>
<div id="cell-5" class="cell"></div>
</div>
<div id="row-2">
<div id="cell-6" class="cell"></div>
<div id="cell-7" class="cell"></div>
<div id="cell-8" class="cell"></div>
</div>
</div>
<button id="reset-btn">Reset Game</button>
<p id="result"></p>
CSS
#game-board {
display: flex;
flex-direction: column;
align-items: center;
}
#row-0, #row-1, #row-2 {
display: flex;
}
.cell {
width: 50px;
height: 50px;
border: 1px solid #ccc;
display: flex;
justify-content: center;
align-items: center;
font-size: 24px;
cursor: pointer;
}
.cell:hover {
background-color: #f0f0f0;
}
#reset-btn {
margin-top: 20px;
}
#result {
font-size: 18px;
margin-top: 10px;
}
JavaScript
let currentPlayer = 'X';
let gameBoard = ['', '', '', '', '', '', '', '', ''];
let gameOver = false;
document.querySelectorAll('.cell').forEach((cell, index) => {
cell.addEventListener('click', () => {
if (gameOver || gameBoard[index] !== '') return;
gameBoard[index] = currentPlayer;
cell.innerText = currentPlayer;
checkWinner();
currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
});
});
document.getElementById('reset-btn').addEventListener('click', resetGame);
function checkWinner() {
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]
];
for (const combination of winningCombinations) {
if (gameBoard[combination[0]] !== '' &&
gameBoard[combination[0]] === gameBoard[combination[1]] &&
gameBoard[combination[0]] === gameBoard[combination[2]]) {
document.getElementById('result').innerText = `Player ${gameBoard[combination[0]]} wins!`;
gameOver = true;
return;
}
}
if (!gameBoard.includes('')) {
document.getElementById('result').innerText = 'It\'s a draw!';
gameOver = true;
}
}
function resetGame() {
currentPlayer = 'X';
gameBoard = ['', '', '', '', '', '', '', '', ''];
gameOver = false;
document.querySelectorAll('.cell').forEach(cell => cell.innerText = '');
document.getElementById('result').innerText = '';
}