o1-preview-2024-09-12· OpenAI
WildChat-4.8M (AI2)
Create tic tac toe program in javascript that runs in web browser, embed in html
- User
Create tic tac toe program in javascript that runs in web browser, embed in html
- Assistant
Create tic tac toe program in javascript that runs in web browser, embed in html
Here's a simple Tic Tac Toe game implemented in JavaScript, embedded within an HTML file. This code creates a playable Tic Tac Toe game in the browser.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Tic Tac Toe</title>
<style>
/* Basic styling for the game */
body {
font-family: Arial, sans-serif;
text-align: center;
}
#game {
display: inline-block;
margin: 20px auto;
}
.cell {
width: 60px;
height: 60px;
font-size: 48px;
display: inline-block;
border: 1px solid #000;
line-height: 60px;
vertical-align: top;
cursor: pointer;
}
#status {
margin: 20px;
font-size: 24px;
}
#reset {
margin: 20px;
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
}
</style>
</head>
<body>
<h1>Tic Tac Toe</h1>
<div id="status"></div>
<div id="game">
<!-- Cells will be generated by JavaScript -->
</div>
<button id="reset">Reset Game</button>
<script>
// Select elements from the DOM
const gameBoard = document.getElementById('game');
const statusDisplay = document.getElementById('status');
const resetButton = document.getElementById('reset');
// Game variables
let gameActive = true;
let currentPlayer = "X";
let gameState = ["", "", "", "", "", "", "", "", ""];
// Winning combinations
const winningConditions = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6]
];
// Messages
const winningMessage = () => `Player ${currentPlayer} has won!`;
const drawMessage = () => `Game ended in a draw!`;
const currentPlayerTurn = () => `It's ${currentPlayer}'s turn`;
// Initialize the game
createGameBoard();
statusDisplay.textContent = currentPlayerTurn();
resetButton.addEventListener('click', handleResetGame);
// Create the game board
function createGameBoard() {
for (let i = 0; i < 9; i++) {
const cell = document.createElement('div');
cell.className = 'cell';
cell.setAttribute('data-cell-index', i);
cell.addEventListener('click', handleCellClick);
gameBoard.appendChild(cell);
}
}
// Handle cell clicks
function handleCellClick(event) {
const clickedCell = event.target;
const clickedCellIndex = parseInt(clickedCell.getAttribute('data-cell-index'));
// Check if the cell is already filled or the game is inactive
if (gameState[clickedCellIndex] !== "" || !gameActive) {
return;
}
// Update game state and UI
handleCellPlayed(clickedCell, clickedCellIndex);
handleResultValidation();
}
// Update the cell with the current player's symbol
function handleCellPlayed(clickedCell, index) {
gameState[index] = currentPlayer;
clickedCell.textContent = currentPlayer;
}
// Check for a win or draw
function handleResultValidation() {
let roundWon = false;
for (let i = 0; i < winningConditions.length; i++) {
const winCondition = winningConditions[i];
let a = gameState[winCondition[0]];
let b = gameState[winCondition[1]];
let c = gameState[winCondition[2]];
if (a === '' || b === '' || c === '') {
continue;
}
if (a === b && b === c) {
roundWon = true;
break;
}
}
if (roundWon) {
statusDisplay.textContent = winningMessage();
gameActive = false;
return;
}
// Check for a draw
let roundDraw = !gameState.includes("");
if (roundDraw) {
statusDisplay.textContent = drawMessage();
gameActive = false;
return;
}
// Switch to the other player
handlePlayerChange();
}
// Switch players
function handlePlayerChange() {
currentPlayer = currentPlayer === "X" ? "O" : "X";
statusDisplay.textContent = currentPlayerTurn();
}
// Reset the game
function handleResetGame() {
gameActive = true;
currentPlayer = "X";
gameState = ["", "", "", "", "", "", "", "", ""];
statusDisplay.textContent = currentPlayerTurn();
document.querySelectorAll('.cell').forEach(cell => cell.textContent = "");
}
</script>
</body>
</html>
To use this code:
.html extension, for example, tic-tac-toe.html.Explanation of the Code:
<body> contains a heading, a status display, the game board (<div id="game">), and a reset button.<style> tag within the <head>. They define the appearance of the game board, cells, and other elements.currentPlayer), whether the game is active (gameActive), and the current state of the board (gameState).createGameBoard(): Dynamically creates the 9 cells for the game board.handleCellClick(): Processes a cell click, updates the game state, and checks for a win or draw.handleCellPlayed(): Updates the clicked cell with the current player's symbol.handleResultValidation(): Checks the game state for a win or draw and updates the status display accordingly.handlePlayerChange(): Switches the active player.handleResetGame(): Resets the game to its initial state.Feel free to customize the styles or enhance the game logic as desired!
Not yet included in a published release.