Create javascript code that creates a tic tac toe game
- User
Create javascript code that creates a tic tac toe game
Assistant
Tic Tac Toe Game in JavaScript
Below is a simple implementation of a Tic Tac Toe game using JavaScript, HTML, and CSS. This code creates a 3x3 grid game board where two players, 'X' and 'O', take turns marking a square. The game checks for a winner after each move and announces the result.
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Tic Tac Toe</title> <link rel="stylesheet" href="style.css"> </head> <body> <h1>Tic Tac Toe</h1> <div class="game-board"> <div class="row"> <div class="cell" id="cell-0"></div> <div class="cell" id="cell-1"></div> <div class="cell" id="cell-2"></div> </div> <div class="row"> <div class="cell" id="cell-3"></div> <div class="cell" id="cell-4"></div> <div class="cell" id="cell-5"></div> </div> <div class="row"> <div class="cell" id="cell-6"></div> <div class="cell" id="cell-7"></div> <div class="cell" id="cell-8"></div> </div> </div> <div id="result"></div> <button id="reset-btn">Reset Game</button> <script src="script.js"></script> </body> </html>style.css
body { font-family: Arial, sans-serif; text-align: center; } .game-board { display: inline-block; margin-top: 20px; } .row { display: flex; } .cell { width: 60px; height: 60px; border: 1px solid #000; display: flex; justify-content: center; align-items: center; font-size: 24px; cursor: pointer; } .cell:hover { background-color: #f0f0f0; } #result { margin-top: 20px; font-size: 18px; } #reset-btn { margin-top: 10px; padding: 10px 20px; font-size: 16px; cursor: pointer; }script.js
document.addEventListener('DOMContentLoaded', () => { const cells = document.querySelectorAll('.cell'); const resultDiv = document.getElementById('result'); const resetBtn = document.getElementById('reset-btn'); let currentPlayer = 'X'; let gameBoard = ['', '', '', '', '', '', '', '', '']; let gameOver = false; // Function to handle player move const handleMove = (index) => { if (gameOver || gameBoard[index] !== '') return; gameBoard[index] = currentPlayer; cells[index].innerText = currentPlayer; // Check for a winner checkWinner(); // Switch player currentPlayer = currentPlayer === 'X' ? 'O' : 'X'; }; // Function to check for a winner const checkWinner = () => { const winConditions = [ [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 condition of winConditions) { const [a, b, c] = condition; if (gameBoard[a] !== '' && gameBoard[a] === gameBoard[b] && gameBoard[a] === gameBoard[c]) { gameOver = true; resultDiv.innerText = `Player ${gameBoard[a]} wins!`; return; } } // Check for a draw if (!gameBoard.includes('')) { gameOver = true; resultDiv.innerText = 'It\'s a draw!'; } }; // Add event listeners to cells cells.forEach((cell, index) => { cell.addEventListener('click', () => handleMove(index)); }); // Reset game button handler resetBtn.addEventListener('click', () => { gameOver = false; currentPlayer = 'X'; gameBoard = ['', '', '', '', '', '', '', '', '']; resultDiv.innerText = ''; cells.forEach(cell => cell.innerText = ''); }); });How It Works:
- Game Structure: The game board is a 3x3 grid represented by 9
divelements with the classcell. Each cell is uniquely identified by anidfromcell-0tocell-8. - JavaScript Logic:
handleMove(index): Updates the game state when a cell is clicked. It checks if the game is over or if the cell is already occupied. If not, it updates thegameBoardarray and the UI.checkWinner(): Checks all possible win conditions after each move. If a player has won, it announces the winner and setsgameOvertotrue. If all cells are filled without a winner, it's a draw.- Event Listeners: Added to each cell to listen for clicks, triggering the
handleMovefunction with the cell's index. - Reset Button: Resets the game state, the UI, and starts a new game.
To Run the Game:
- Create three files:
index.html,style.css, andscript.js. - Copy the respective code into each file.
- Open
index.htmlin a web browser.
Now, you can play Tic Tac Toe by clicking on the cells. Players alternate between 'X' and 'O'. The game announces the winner or a draw and allows resetting the game with the "Reset Game" button. Enjoy!
- Game Structure: The game board is a 3x3 grid represented by 9
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.