Tic Tac Toe Game: Play Online for Free - HTML, CSS, JavaScript
Tic Tac Toe Game
This is a simple Tic Tac Toe game built using HTML, CSS, and JavaScript.
Instructions
- The game is played on a 3x3 grid.
- Player 1 is 'X' and player 2 is 'O'.
- Players take turns placing their marks on the grid.
- The first player to get 3 of their marks in a row (vertically, horizontally, or diagonally) wins the game.
- If all 9 squares are filled and no player has 3 in a row, the game is a draw.
Code
Here is the HTML code for the game:
<!DOCTYPE html>
<html>
<head>
<title>Tic Tac Toe</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1>Tic Tac Toe</h1>
<div class="container">
<div class="cell" id="1"></div>
<div class="cell" id="2"></div>
<div class="cell" id="3"></div>
<div class="cell" id="4"></div>
<div class="cell" id="5"></div>
<div class="cell" id="6"></div>
<div class="cell" id="7"></div>
<div class="cell" id="8"></div>
<div class="cell" id="9"></div>
</div>
<script src="script.js"></script>
</body>
</html>
Here is the CSS code for the game:
.container {
display: flex;
flex-wrap: wrap;
width: 300px;
margin: 0 auto;
}
.cell {
width: 100px;
height: 100px;
border: 1px solid black;
box-sizing: border-box;
font-size: 72px;
text-align: center;
line-height: 100px;
cursor: pointer;
}
.cell:hover {
background-color: #eee;
}
Here is the JavaScript code for the game:
const cells = document.querySelectorAll('.cell');
let currentPlayer = 'X';
cells.forEach(cell => {
cell.addEventListener('click', () => {
cell.textContent = currentPlayer;
if (checkWin()) {
alert(currentPlayer + ' wins!');
reset();
} else if (checkDraw()) {
alert('Draw!');
reset();
} else {
currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
}
})
})
function checkWin() {
const rows = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[1, 4, 7],
[2, 5, 8],
[3, 6, 9],
[1, 5, 9],
[3, 5, 7]
];
for (let i = 0; i < rows.length; i++) {
if (cells[rows[i][0] - 1].textContent === currentPlayer &&
cells[rows[i][1] - 1].textContent === currentPlayer &&
cells[rows[i][2] - 1].textContent === currentPlayer) {
return true;
}
}
return false;
}
function checkDraw() {
return [...cells].every(cell => {
return cell.textContent === 'X' || cell.textContent === 'O';
})
}
function reset() {
cells.forEach(cell => {
cell.textContent = '';
})
currentPlayer = 'X';
}
Enjoy playing Tic Tac Toe!
原文地址: https://www.cveoy.top/t/topic/lnln 著作权归作者所有。请勿转载和采集!