How to Build a Beautiful and Responsive Tic-Tac-Toe Game with HTML, CSS, and JavaScript
Tic-Tac-Toe is one of the simplest and most popular games that many of us have enjoyed playing at some point in our lives. It’s a great project for learning web development as it involves a combination of HTML, CSS, and JavaScript. In this tutorial, we’ll walk you through how to create a responsive and visually appealing Tic-Tac-Toe game that can be played on any device, including mobile phones.
What You’ll Learn
- How to create a basic Tic-Tac-Toe game using HTML, CSS, and JavaScript.
- How to make the game responsive for mobile devices.
- How to add colors and hover effects to improve the design and user experience.
- How to implement a simple AI bot that plays as "O."
Setting Up the HTML
We’ll start by creating the basic structure of our Tic-Tac-Toe game. In this case, we’ll need an HTML file to contain the grid, game status, and a reset button. Here's the structure:
<!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 Game</title><link rel="stylesheet" href="styles.css"></head><body><div class="container"><h1>Tic-Tac-Toe</h1><div id="board" 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><p id="status">Player X's Turn</p><button id="reset">Reset Game</button></div><script src="script.js"></script></body></html>
Styling with CSS
Once the structure is in place, let’s add some style to make the game visually appealing and responsive. Here’s the updated CSS code that provides a clean, modern design with hover effects and colors.
body {
font-family: 'Arial', sans-serif;margin: 0;padding: 0;display: flex;justify-content: center;align-items: center;height: 100vh;background-color: #f4f7fc;}.container {text-align: center;background-color: #ffffff;border-radius: 10px;box-shadow: 0px 10px 20px rgba(0, 0, 0, 0.1);padding: 30px;width: 100%;max-width: 450px;}h1 {margin-bottom: 20px;color: #2c3e50;font-size: 2rem;letter-spacing: 2px;font-weight: 600;}#board {display: grid;grid-template-columns: repeat(3, 1fr);gap: 10px;margin: 0 auto;width: 90%;max-width: 400px;}.cell {width: 100%;padding-top: 100%;background-color: #ecf0f1;border: 2px solid #bdc3c7;position: relative;cursor: pointer;transition: background-color 0.3s ease;border-radius: 8px;}.cell:hover {background-color: #dcdfe1;}.cell span {position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);font-size: 2.5rem;font-weight: bold;color: #34495e;transition: color 0.3s ease;}#reset {margin-top: 20px;padding: 12px 30px;font-size: 1.2rem;background-color: #3498db;color: #ffffff;border: none;border-radius: 8px;cursor: pointer;transition: background-color 0.3s ease;}#reset:hover {background-color: #2980b9;}#status {margin-top: 10px;font-size: 1.2rem;font-weight: bold;color: #2c3e50;text-transform: uppercase;}
Game Logic with JavaScript
Now, let’s add the JavaScript code that makes the game functional. The main logic includes:
- Switching between players "X" and "O."
- Detecting the winner or a draw.
- Allowing the "O" player (the bot) to play automatically after the "X" player makes their move.
// script.js
const cells = document.querySelectorAll(".cell");const statusText = document.querySelector("#status");const resetButton = document.querySelector("#reset");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],];// Handle clicks on cellsfunction handleCellClick(event) {const cell = event.target;const index = cell.dataset.index;if (boardState[index] !== "" || !gameActive || currentPlayer === "O") return;boardState[index] = currentPlayer;cell.innerHTML = `<span>${currentPlayer}</span>`;checkWinner();if (gameActive) switchPlayer();}// Check for a winnerfunction checkWinner() {for (const condition of winningConditions) {const [a, b, c] = condition;if (boardState[a] && boardState[a] === boardState[b] && boardState[a] === boardState[c]) {statusText.textContent = `Player ${currentPlayer} Wins! π`;gameActive = false;return;}}if (!boardState.includes("")) {statusText.textContent = "It's a Draw!";gameActive = false;return;}}// Switch playersfunction switchPlayer() {if (gameActive) {currentPlayer = currentPlayer === "X" ? "O" : "X";statusText.textContent = `Player ${currentPlayer}'s Turn`;if (currentPlayer === "O") {setTimeout(botMove, 500); // Simulate bot thinking}}}// Bot move (O player) - Selects random empty cellfunction botMove() {const emptyCells = boardState.map((value, index) => value === "" ? index : null).filter(index => index !== null);if (emptyCells.length > 0) {const randomIndex = emptyCells[Math.floor(Math.random() * emptyCells.length)];boardState[randomIndex] = "O";cells[randomIndex].innerHTML = `<span>O</span>`;checkWinner();if (gameActive) switchPlayer();}}// Reset the gamefunction resetGame() {boardState = ["", "", "", "", "", "", "", "", ""];currentPlayer = "X";gameActive = true;statusText.textContent = `Player ${currentPlayer}'s Turn`;cells.forEach((cell) => (cell.innerHTML = ""));}// Add event listenerscells.forEach((cell) => cell.addEventListener("click", handleCellClick));resetButton.addEventListener("click", resetGame);// Initialize gamestatusText.textContent = `Player ${currentPlayer}'s Turn`;
Project Download Using
Conclusion
With just HTML, CSS, and JavaScript, you can build a fully functional Tic-Tac-Toe game that looks great and works on both desktop and mobile screens. By adding hover effects, colors, and a bot to play as "O," you can make the game more interactive and enjoyable.
This project can be expanded in various ways:
- You could improve the bot’s AI to make it smarter (e.g., blocking winning moves).
- You could add an option to play against another human player.
- You could even add sound effects or animations to make the game even more fun!
By practicing with projects like this, you’ll get better at using core web development technologies and building more complex applications. Happy coding! π
Comments
Post a Comment