Sure! Below is a simple implementation of a Tic Tac Toe game that supports both single-player (against the computer) and two-player modes. The game features a minimal and clean GUI using HTML, CSS, and JavaScript. You can copy the entire code into a single .html file and open it in your browser to play.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Tic Tac Toe</title>
<style>
body {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
font-family: Arial, sans-serif;
background-color: #f0f0f0;
}
h1 {
margin-bottom: 20px;
}
.mode-selection {
margin-bottom: 20px;
}
.mode-selection button {
padding: 10px 20px;
margin: 0 10px;
font-size: 16px;
cursor: pointer;
}
.game {
display: none;
flex-direction: column;
align-items: center;
}
.board {
display: grid;
grid-template-columns: repeat(3, 100px);
grid-template-rows: repeat(3, 100px);
gap: 5px;
}
.cell {
width: 100px;
height: 100px;
background-color: #fff;
display: flex;
align-items: center;
justify-content: center;
font-size: 48px;
cursor: pointer;
border: 2px solid #333;
}
.cell:hover {
background-color: #e0e0e0;
}
.status {
margin-top: 20px;
font-size: 18px;
}
.restart {
margin-top: 10px;
padding: 8px 16px;
font-size: 16px;
cursor: pointer;
}
</style>
</head>
<body>
<h1>Tic Tac Toe</h1>
<div class="mode-selection">
<button id="singlePlayerBtn">Single Player</button>
<button id="twoPlayerBtn">Two Players</button>
</div>
<div class="game">
<div class="board" id="board">
<!-- 9 cells -->
<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>
<div class="status" id="status">Player X's turn</div>
<button class="restart" id="restartBtn">Restart</button>
</div>
<script>
const singlePlayerBtn = document.getElementById('singlePlayerBtn');
const twoPlayerBtn = document.getElementById('twoPlayerBtn');
const gameDiv = document.querySelector('.game');
const board = document.getElementById('board');
const cells = document.querySelectorAll('.cell');
const statusDiv = document.getElementById('status');
const restartBtn = document.getElementById('restartBtn');
let boardState = ['', '', '', '', '', '', '', '', ''];
let currentPlayer = 'X';
let gameActive = true;
let isSinglePlayer = false;
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]
];
singlePlayerBtn.addEventListener('click', () => startGame(true));
twoPlayerBtn.addEventListener('click', () => startGame(false));
restartBtn.addEventListener('click', restartGame);
cells.forEach(cell => {
cell.addEventListener('click', handleCellClick);
});
function startGame(singlePlayer) {
isSinglePlayer = singlePlayer;
gameDiv.style.display = 'flex';
document.querySelector('.mode-selection').style.display = 'none';
updateStatus();
if (isSinglePlayer && currentPlayer === 'O') {
computerMove();
}
}
function handleCellClick(e) {
const index = e.target.getAttribute('data-index');
if (boardState[index] !== '' || !gameActive) return;
makeMove(index, currentPlayer);
if (checkWinner()) {
endGame(`${currentPlayer} wins!`);
return;
} else if (boardState.every(cell => cell !== '')) {
endGame("It's a draw!");
return;
}
switchPlayer();
if (isSinglePlayer && currentPlayer === 'O' && gameActive) {
computerMove();
}
}
function makeMove(index, player) {
boardState[index] = player;
document.querySelector(`.cell[data-index='${index}']`).textContent = player;
}
function switchPlayer() {
currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
updateStatus();
}
function updateStatus() {
statusDiv.textContent = `${currentPlayer}'s turn`;
}
function endGame(message) {
statusDiv.textContent = message;
gameActive = false;
}
function checkWinner() {
for (let condition of winningConditions) {
const [a, b, c] = condition;
if (boardState[a] && boardState[a] === boardState[b] && boardState[a] === boardState[c]) {
return true;
}
}
return false;
}
function restartGame() {
boardState = ['', '', '', '', '', '', '', '', ''];
cells.forEach(cell => cell.textContent = '');
currentPlayer = 'X';
gameActive = true;
statusDiv.textContent = `${currentPlayer}'s turn`;
if (isSinglePlayer && currentPlayer === 'O') {
computerMove();
}
}
// Simple AI: chooses a random empty cell
function computerMove() {
setTimeout(() => { // Delay for better UX
const emptyIndices = boardState.map((val, idx) => val === '' ? idx : null).filter(val => val !== null);
if (emptyIndices.length === 0 || !gameActive) return;
const randomIndex = emptyIndices[Math.floor(Math.random() * emptyIndices.length)];
makeMove(randomIndex, currentPlayer);
if (checkWinner()) {
endGame(`${currentPlayer} wins!`);
return;
} else if (boardState.every(cell => cell !== '')) {
endGame("It's a draw!");
return;
}
switchPlayer();
}, 500);
}
</script>
</body>
</html>
How It Works
-
HTML Structure:
- The page includes a title, mode selection buttons (
Single Player and Two Players), the game board, status display, and a restart button.
- The game board is a 3x3 grid made using CSS Grid, with each cell represented by a
div with the class cell and a data-index attribute to identify its position.
-
CSS Styling:
- The styling is kept minimal and clean, centered on the page with a simple color scheme.
- Cells have hover effects to indicate they are clickable.
-
JavaScript Functionality:
- Mode Selection: The user selects between single-player and two-player modes. In single-player mode, the computer plays as 'O'.
- Game State Management: The
boardState array keeps track of the current state of the board.
- Event Listeners: Clicking on a cell triggers the
handleCellClick function which manages player moves.
- Win Checking: After each move, the game checks if there's a winner or if it's a draw.
- Computer Move: In single-player mode, the computer selects a random empty cell after the human player makes a move.
- Restart Functionality: The
restartGame function resets the game to its initial state.
Enhancements
This implementation uses a simple random move selection for the computer. For a more challenging AI, you can implement the Minimax algorithm, which allows the computer to choose optimal moves.
Running the Game
-
Create an HTML File:
- Open your preferred text editor and create a new file named
tic-tac-toe.html.
-
Paste the Code:
- Copy the entire code provided above and paste it into the
tic-tac-toe.html file.
-
Open in Browser:
- Save the file and open it with your web browser (e.g., Chrome, Firefox).
-
Play the Game:
- Choose between single-player or two-player mode and start playing!
Feel free to customize the styles or enhance the functionality as you like. Enjoy your game!