Code for tic-tac-toe game…(Noughts and crosses or XOX)…

Code With Gp
4 min readJan 9, 2025

--

Output Looks like...

These codes work together to create a fully functional and playable game.

This code creates a Tic-Tac-Toe game where you can play against the computer.

HTML

The HTML structure sets up the game board and a simple interface for the user.

<!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 with AI</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<h1>Tic Tac Toe</h1>
<div id="game">
<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">Your turn (X)</p>
<button id="restart">Restart Game</button>
</div>
<script src="script.js"></script>
</body>
</html>

CSS

The CSS adds styling, including a gradient background, hover effects, and animations to make the game visually appealing. The design is clean, with smooth transitions and a modern look.

 body {
font-family: 'Arial', sans-serif;
background: linear-gradient(135deg, #2b5876, #4e4376);
color: white;
margin: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
overflow: hidden;
}

.container {
text-align: center;
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.3);
border-radius: 15px;
padding: 20px;
background-color: #ffffff10;
backdrop-filter: blur(8px);
border: 1px solid rgba(255, 255, 255, 0.2);
}

h1 {
margin-bottom: 20px;
}

#game {
display: grid;
grid-template-columns: repeat(3, 100px);
gap: 10px;
margin: 0 auto 20px;
}

.cell {
width: 100px;
height: 100px;
background-color: #fff;
color: #4e4376;
border-radius: 10px;
display: flex;
align-items: center;
justify-content: center;
font-size: 36px;
font-weight: bold;
cursor: pointer;
transition: transform 0.2s, background-color 0.3s;
}

.cell:hover {
background-color: #f4f4f4;
transform: scale(1.05);
}

.cell.taken {
pointer-events: none;
}

#status {
font-size: 18px;
margin: 10px 0;
}

#restart {
padding: 10px 20px;
font-size: 16px;
background-color: #4e4376;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s;
}

#restart:hover {
background-color: #6a6180;
}

Java script

The JavaScript handles the game logic and makes the computer a challenging opponent by using the minimax algorithm.

const cells = document.querySelectorAll('.cell');
const statusText = document.getElementById('status');
const restartBtn = document.getElementById('restart');
let board = ['', '', '', '', '', '', '', '', ''];
let isComputerX = true; // Alternates computer's role between X and O
let currentPlayer, computerPlayer;

const winningCombos = [
[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 initializeGame() {
currentPlayer = isComputerX ? 'O' : 'X';
computerPlayer = isComputerX ? 'X' : 'O';
board = ['', '', '', '', '', '', '', '', ''];
cells.forEach(cell => {
cell.textContent = '';
cell.classList.remove('taken');
});
statusText.textContent = `Your turn (${currentPlayer})`;
if (currentPlayer === computerPlayer) {
setTimeout(bestMove, 500);
}
}

function checkWinner(player) {
return winningCombos.some(combo =>
combo.every(index => board[index] === player)
);
}

function isDraw() {
return board.every(cell => cell !== '');
}

function bestMove() {
let bestScore = -Infinity;
let move;

for (let i = 0; i < board.length; i++) {
if (board[i] === '') {
board[i] = computerPlayer;
let score = minimax(board, 0, false);
board[i] = '';
if (score > bestScore) {
bestScore = score;
move = i;
}
}
}
board[move] = computerPlayer;
cells[move].textContent = computerPlayer;
cells[move].classList.add('taken');
if (checkWinner(computerPlayer)) {
statusText.textContent = `Computer (${computerPlayer}) Wins!`;
endGame();
} else if (isDraw()) {
statusText.textContent = "It's a Draw!";
} else {
currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
statusText.textContent = `Your turn (${currentPlayer})`;
}
}

function minimax(board, depth, isMaximizing) {
if (checkWinner(computerPlayer)) return 10 - depth; // Computer wins
if (checkWinner(currentPlayer)) return depth - 10; // Player wins
if (isDraw()) return 0; // Draw

if (isMaximizing) {
let bestScore = -Infinity;
for (let i = 0; i < board.length; i++) {
if (board[i] === '') {
board[i] = computerPlayer;
let score = minimax(board, depth + 1, false);
board[i] = '';
bestScore = Math.max(score, bestScore);
}
}
return bestScore;
} else {
let bestScore = Infinity;
for (let i = 0; i < board.length; i++) {
if (board[i] === '') {
board[i] = currentPlayer;
let score = minimax(board, depth + 1, true);
board[i] = '';
bestScore = Math.min(score, bestScore);
}
}
return bestScore;
}
}

function handleCellClick(e) {
const cell = e.target;
const index = cell.dataset.index;

if (board[index] === '' && currentPlayer !== computerPlayer) {
board[index] = currentPlayer;
cell.textContent = currentPlayer;
cell.classList.add('taken');

if (checkWinner(currentPlayer)) {
statusText.textContent = `You (${currentPlayer}) Win!`;
endGame();
} else if (isDraw()) {
statusText.textContent = "It's a Draw!";
} else {
currentPlayer = computerPlayer;
statusText.textContent = `Computer's turn (${computerPlayer})`;
setTimeout(bestMove, 500);
}
}
}

function endGame() {
cells.forEach(cell => cell.classList.add('taken'));
}

restartBtn.addEventListener('click', () => {
isComputerX = !isComputerX; // Alternate roles
initializeGame();
});

cells.forEach(cell => cell.addEventListener('click', handleCellClick));

initializeGame();

In short, HTML builds the game, CSS makes it look nice, and JavaScript makes it functional!

Save the files as index.html, styles.css, and script.js, and test in a browser.

The game is responsive and supports both desktop and mobile devices, ensuring a smooth and enjoyable experience.

— Code with gp…

Sign up to discover human stories that deepen your understanding of the world.

--

--

Responses (1)

Write a response