JavaScript Project – Tic Tac Toe Game Graphical Version
Full Stack Web Development Courses with Real-time projects Start Now!!
Program 1
<!DOCTYPE html>
<html>
<head>
<title>Tic Tac Toe</title>
<script>
// Matrix (2 D Array)
let board = [
[' ', ' ', ' '],
[' ', ' ', ' '],
[' ', ' ', ' ']
];
let currentPlayer = 'X';
let gameOver = false;
function drawBoard() {
let html = "<table border='1' cellpadding='20' bgcolor=yellow>";
for (let i = 0; i < 3; i++)
{
html += "<tr>";
for (let j = 0; j < 3; j++)
{
html += `<td onclick="makeMove(${i},${j})" style="width: 60px; height: 60px; text-align: center; font-size: 24px;">${board[i][j]}</td>`;
}
html += "</tr>";
}
html += "</table>";
document.getElementById("game").innerHTML = html;
}
function makeMove(row, col)
{
if (gameOver || board[row][col] !== ' ') return;
board[row][col] = currentPlayer;
drawBoard();
if (checkWin(currentPlayer)) {
document.getElementById("status").innerText = `Player ${currentPlayer} wins!`;
gameOver = true;
} else if (isBoardFull())
{
document.getElementById("status").innerText = "It's a draw!";
gameOver = true;
} else {
currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
document.getElementById("status").innerText = `Player ${currentPlayer}'s turn`;
}
}
function checkWin(p) {
for (let i = 0; i < 3; i++) {
if (board[i][0] === p && board[i][1] === p && board[i][2] === p) return true; // row
if (board[0][i] === p && board[1][i] === p && board[2][i] === p) return true; //column
}
if (board[0][0] === p && board[1][1] === p && board[2][2] === p) return true; // digonal
if (board[0][2] === p && board[1][1] === p && board[2][0] === p) return true; // digonal
return false;
}
function isBoardFull() {
for (let row of board) {
if (row.includes(' ')) return false;
}
return true;
}
function resetGame()
{
board =
[[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']
];
currentPlayer = 'X';
gameOver = false;
document.getElementById("status").innerText = `Player ${currentPlayer}'s turn`;
drawBoard();
}
window.onload = function ()
{
drawBoard();
document.getElementById("status").innerText = `Player ${currentPlayer}'s turn`;
};
</script>
</head>
<body bgcolor="blue">
<center>
<h2>Tic Tac Toe</h2>
<div id="game"></div>
<p id="status"></p>
<button onclick="resetGame()">Restart Game</button>
</center>
</body>
</html>
Did you like our efforts? If Yes, please give DataFlair 5 Stars on Google

