Board Game - Tic Tac Toe
by SonicBear35137 lines2.5 KB
<!DOCTYPE html>
<html>
<head>
<title>Board Game - Tic Tac Toe</title>
<style>
body {
margin: 0;
font-family: Arial;
background: #1e1e1e;
color: white;
text-align: center;
}
h1 {
margin-top: 20px;
}
#board {
display: grid;
grid-template-columns: repeat(3, 100px);
grid-template-rows: repeat(3, 100px);
gap: 5px;
justify-content: center;
margin-top: 30px;
}
.cell {
width: 100px;
height: 100px;
background: #333;
font-size: 40px;
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
}
.cell:hover {
background: #444;
}
#status {
margin-top: 20px;
font-size: 20px;
}
button {
margin-top: 15px;
padding: 10px;
font-size: 16px;
}
</style>
</head>
<body>
<h1>🎮 Tic Tac Toe</h1>
<div id="board"></div>
<div id="status">Player X's turn</div>
<button onclick="resetGame()">Restart</button>
<script>
const board = document.getElementById("board");
const status = document.getElementById("status");
let currentPlayer = "X";
let gameState = ["", "", "", "", "", "", "", "", ""];
let gameActive = true;
const winConditions = [
[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 createBoard() {
board.innerHTML = "";
gameState.forEach((cell, index) => {
let div = document.createElement("div");
div.classList.add("cell");
div.dataset.index = index;
div.innerText = cell;
div.addEventListener("click", handleClick);
board.appendChild(div);
});
}
function handleClick(e) {
let index = e.target.dataset.index;
if (gameState[index] !== "" || !gameActive) return;
gameState[index] = currentPlayer;
e.target.innerText = currentPlayer;
checkWinner();
currentPlayer = currentPlayer === "X" ? "O" : "X";
if (gameActive) {
status.innerText = "Player " + currentPlayer + "'s turn";
}
}
function checkWinner() {
for (let condition of winConditions) {
let [a,b,c] = condition;
if (
gameState[a] &&
gameState[a] === gameState[b] &&
gameState[a] === gameState[c]
) {
status.innerText = "Player " + currentPlayer + " wins 🎉";
gameActive = false;
return;
}
}
if (!gameState.includes("")) {
status.innerText = "It's a draw!";
gameActive = false;
}
}
function resetGame() {
gameState = ["", "", "", "", "", "", "", "", ""];
currentPlayer = "X";
gameActive = true;
status.innerText = "Player X's turn";
createBoard();
}
createBoard();
</script>
</body>
</html>Game Source: Board Game - Tic Tac Toe
Creator: SonicBear35
Libraries: none
Complexity: moderate (137 lines, 2.5 KB)
The full source code is displayed above on this page.
Remix Instructions
To remix this game, copy the source code above and modify it. Add a ARCADELAB header at the top with "remix_of: board-game-tic-tac-toe-sonicbear35" to link back to the original. Then publish at arcadelab.ai/publish.