o1-mini-2024-09-12· OpenAI
WildChat-4.8M (AI2)
Write a tic tac toe game in HTML, CSS, and JS
- User
Write a tic tac toe game in HTML, CSS, and JS
- Assistant
Write a tic tac toe game in HTML, CSS, and JS
Sure! Below is a complete Tic Tac Toe game implementation using HTML, CSS, and JavaScript. You can copy the entire code into a single .html file and open it in your browser to play the game.
<!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>
<style>
/* Reset some default browser styles */
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
display: flex;
height: 100vh;
justify-content: center;
align-items: center;
background-color: #f0f0f0;
font-family: Arial, sans-serif;
}
.game-container {
text-align: center;
}
h1 {
margin-bottom: 20px;
color: #333;
}
.board {
display: grid;
grid-template-columns: repeat(3, 100px);
grid-template-rows: repeat(3, 100px);
gap: 5px;
margin: 0 auto 20px;
}
.cell {
background-color: #fff;
border: 2px solid #333;
display: flex;
justify-content: center;
align-items: center;
font-size: 2.5rem;
cursor: pointer;
transition: background-color 0.3s;
}
.cell:hover {
background-color: #e0e0e0;
}
.message {
margin-bottom: 20px;
font-size: 1.2rem;
color: #333;
}
.restart-button {
padding: 10px 20px;
font-size: 1rem;
background-color: #333;
color: #fff;
border: none;
cursor: pointer;
border-radius: 5px;
transition: background-color 0.3s;
}
.restart-button:hover {
background-color: #555;
}
/* Highlight winning cells */
.winner {
background-color: #90ee90 !important;
}
</style>
</head>
<body>
<div class="game-container">
<h1>Tic Tac Toe</h1>
<div class="message" id="message">Player X's turn</div>
<div class="board" id="board">
<div class="cell" data-index="0"></div>
<div class="cell" data-index="1"></div>
<div class="cell" data-index="2"></div>
<div class="cell" data-index="3"></div>
<div class="cell" data-index="4"></div>
<div class="cell" data-index="5"></div>
<div class="cell" data-index="6"></div>
<div class="cell" data-index="7"></div>
<div class="cell" data-index="8"></div>
</div>
<button class="restart-button" id="restartButton">Restart Game</button>
</div>
<script>
const board = document.getElementById('board');
const cells = document.querySelectorAll('.cell');
const message = document.getElementById('message');
const restartButton = document.getElementById('restartButton');
let currentPlayer = 'X';
let gameActive = true;
let boardState = ["", "", "", "", "", "", "", "", ""];
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]
];
// Function to handle cell clicks
function handleCellClick(e) {
const clickedCell = e.target;
const cellIndex = parseInt(clickedCell.getAttribute('data-index'));
if (boardState[cellIndex] !== "" || !gameActive) {
return;
}
updateCell(clickedCell, cellIndex);
checkResult();
}
// Update the UI and state
function updateCell(cell, index) {
boardState[index] = currentPlayer;
cell.textContent = currentPlayer;
}
// Switch player turns
function switchPlayer() {
currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
message.textContent = `Player ${currentPlayer}'s turn`;
}
// Check for win or draw
function checkResult() {
let roundWon = false;
for (let i = 0; i < winningConditions.length; i++) {
const [a, b, c] = winningConditions[i];
if (boardState[a] && boardState[a] === boardState[b] && boardState[a] === boardState[c]) {
roundWon = true;
highlightWinningCells(a, b, c);
break;
}
}
if (roundWon) {
message.textContent = `Player ${currentPlayer} wins!`;
gameActive = false;
return;
}
if (!boardState.includes("")) {
message.textContent = `It's a draw!`;
gameActive = false;
return;
}
switchPlayer();
}
// Highlight winning cells
function highlightWinningCells(a, b, c) {
cells[a].classList.add('winner');
cells[b].classList.add('winner');
cells[c].classList.add('winner');
}
// Reset the game
function resetGame() {
currentPlayer = 'X';
gameActive = true;
boardState = ["", "", "", "", "", "", "", "", ""];
message.textContent = `Player ${currentPlayer}'s turn`;
cells.forEach(cell => {
cell.textContent = "";
cell.classList.remove('winner');
});
}
// Add event listeners to cells
cells.forEach(cell => cell.addEventListener('click', handleCellClick));
// Add event listener to restart button
restartButton.addEventListener('click', resetGame);
</script>
</body>
</html>
HTML Structure:
<h1>): Displays the title "Tic Tac Toe".<div id="message">): Shows whose turn it is or the game result.<div id="board">): A grid of 9 cells, each represented by a <div> with the class cell and a data-index attribute to identify its position.<button id="restartButton">): Allows players to reset the game at any time.CSS Styling:
.winner class highlights the winning combination.JavaScript Functionality:
currentPlayer: Tracks whose turn it is ('X' or 'O').gameActive: Indicates if the game is ongoing.boardState: An array representing the current state of the board.handleCellClick: Manages the logic when a cell is clicked, updates the state, and checks for a win or draw.resetGame: Resets all state variables and UI elements to start a new game.updateCell: Updates the clicked cell with the current player's symbol.switchPlayer: Switches the turn to the next player.Setup:
.html extension, for example, tic-tac-toe.html.Run the Game:
Gameplay:
Enjoy playing Tic Tac Toe!
Not yet included in a published release.
checkResulthighlightWinningCells: Adds a highlight to the cells that form the winning combination.