Building a Smart Tic-Tac-Toe Game with JavaScript and AI
Building a Tic-Tac-Toe Game with JavaScript
Tic-Tac-Toe is a classic game that has entertained people for generations. In this blog, we will walk you through how to build a Tic-Tac-Toe game using HTML, CSS, and JavaScript. The game will feature both a two-player mode and an AI-powered single-player mode.
Technologies Used
- HTML: To structure the game layout.
- CSS: To style the board and buttons.
- JavaScript: To handle game logic and AI moves.
Project Features
- Two-Player Mode: Allows two human players to take turns.
- AI Mode: Uses the Minimax algorithm to make the AI unbeatable.
- Interactive UI: Players can click on cells to make their moves.
- Winning and Draw Detection: The game announces the winner or a draw at the end.
Game Structure
The game consists of a 3x3 grid where players take turns marking X
and O
. The first player to align three symbols horizontally, vertically, or diagonally wins the game.
Step-by-Step Breakdown
1. Setting Up the HTML Structure
We start by creating a simple layout with buttons to choose between two-player mode and playing against the AI. The game board consists of nine clickable cells.
<!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="styles.css">
</head>
<body>
<h1>Tic-Tac-Toe</h1>
<div class="options">
<button id="twoPlayers">Two Players</button>
<button id="playWithAI">Play with AI</button>
</div>
<div class="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>
<div class="message"></div>
<script src="script.js"></script>
</body>
</html>
2. Styling the Game Board with CSS
We use CSS to style the board and buttons, ensuring a visually appealing interface.
body {
font-family: Arial, sans-serif;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
min-height: 100vh;
background-color: #f0f0f0;
margin: 0;
}
.board {
display: grid;
grid-template-columns: repeat(3, 100px);
grid-gap: 5px;
}
.cell {
width: 100px;
height: 100px;
background-color: #fff;
border: 2px solid #333;
display: flex;
align-items: center;
justify-content: center;
font-size: 60px;
cursor: pointer;
}
3. Implementing Game Logic with JavaScript
JavaScript is used to manage the game state, detect wins, and allow the AI to make moves.
Handling Player Moves
document.addEventListener('DOMContentLoaded', function () {
const board = document.querySelector('.board');
const cells = document.querySelectorAll('.cell');
const message = document.querySelector('.message');
const twoPlayersButton = document.getElementById('twoPlayers');
const playWithAIButton = document.getElementById('playWithAI');
let currentPlayer = 'X';
let gameBoard = ['', '', '', '', '', '', '', '', ''];
let gameActive = false;
let vsAI = false;
function startGame() {
gameActive = true;
gameBoard = ['', '', '', '', '', '', '', '', ''];
currentPlayer = 'X';
message.textContent = 'Player X\'s turn';
cells.forEach(cell => {
cell.textContent = '';
});
}
twoPlayersButton.addEventListener('click', function () {
vsAI = false;
startGame();
});
playWithAIButton.addEventListener('click', function () {
vsAI = true;
startGame();
});
cells.forEach((cell, index) => {
cell.addEventListener('click', () => {
if (gameBoard[index] === '' && gameActive) {
gameBoard[index] = currentPlayer;
cells[index].textContent = currentPlayer;
checkWinner();
currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
if (vsAI && currentPlayer === 'O' && gameActive) {
setTimeout(aiMove, 500);
}
}
});
});
});
Implementing AI using Minimax Algorithm
The AI uses the Minimax algorithm to determine the best possible move.
function aiMove() {
let bestMove;
let bestScore = -Infinity;
for (let i = 0; i < gameBoard.length; i++) {
if (gameBoard[i] === '') {
gameBoard[i] = 'O';
let score = minimax(gameBoard, 0, false);
gameBoard[i] = '';
if (score > bestScore) {
bestScore = score;
bestMove = i;
}
}
}
cells[bestMove].click();
}
Game Output
Here’s how the game looks when AI wins:
Conclusion
With just HTML, CSS, and JavaScript, you can create a fully functional Tic-Tac-Toe game. The AI ensures a challenging single-player experience, while the two-player mode lets you enjoy the game with friends. Try expanding this project by adding animations, sound effects, or even a multiplayer feature using WebSockets!
Happy coding!
Comments
Post a Comment