Tic Tac Toe Game: Play Online - Free HTML, CSS, JavaScript
Tic Tac Toe Game
Here's a simple Tic Tac Toe game made with HTML, CSS and JavaScript.
HTML
<!DOCTYPE html>
<html>
<head>
<title>Tic Tac Toe</title>
<link rel='stylesheet' type='text/css' href='style.css'>
</head>
<body>
<div class='container'>
<h1>Tic Tac Toe</h1>
<div class='game'>
<div class='cell'></div>
<div class='cell'></div>
<div class='cell'></div>
<div class='cell'></div>
<div class='cell'></div>
<div class='cell'></div>
<div class='cell'></div>
<div class='cell'></div>
<div class='cell'></div>
</div>
<button class='reset'>Reset</button>
</div>
<script type='text/javascript' src='app.js'></script>
</body>
</html>
CSS
.container {
margin: 0 auto;
text-align: center;
}
h1 {
font-size: 48px;
margin-bottom: 30px;
}
.game {
display: inline-block;
margin-right: 30px;
}
.cell {
width: 80px;
height: 80px;
border: 1px solid black;
display: inline-block;
margin-right: -1px;
margin-bottom: -1px;
text-align: center;
font-size: 48px;
line-height: 72px;
cursor: pointer;
}
.row:after {
content: '';
display: block;
clear: both;
}
.reset {
font-size: 24px;
padding: 10px 20px;
border-radius: 5px;
border: none;
background-color: #4CAF50;
color: white;
cursor: pointer;
}
JavaScript
let currentPlayer = 'X';
let gameStatus = ['', '', '', '', '', '', '', '', ''];
const winningCombinations = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6]
];
const cells = document.querySelectorAll('.cell');
const resetButton = document.querySelector('.reset');
cells.forEach(cell => {
cell.addEventListener('click', event => {
const index = Array.from(cells).indexOf(event.target);
if (gameStatus[index] !== '') {
return;
}
gameStatus[index] = currentPlayer;
event.target.textContent = currentPlayer;
checkWin();
currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
});
});
resetButton.addEventListener('click', () => {
cells.forEach(cell => {
cell.textContent = '';
});
gameStatus = ['', '', '', '', '', '', '', '', ''];
});
function checkWin() {
for (let i = 0; i < winningCombinations.length; i++) {
const [a, b, c] = winningCombinations[i];
if (
gameStatus[a] !== '' &&
gameStatus[a] === gameStatus[b] &&
gameStatus[b] === gameStatus[c]
) {
alert(`${currentPlayer} won the game!`);
gameStatus = ['', '', '', '', '', '', '', '', ''];
cells.forEach(cell => {
cell.textContent = '';
});
return;
}
}
}
This is a basic Tic Tac Toe game created using HTML, CSS and JavaScript. The HTML file includes the basic structure of the game, including the game board and the reset button. The CSS file styles the game board and reset button. The JavaScript file handles the logic of the game, including checking for wins and switching player turns.
原文地址: https://www.cveoy.top/t/topic/lnnB 著作权归作者所有。请勿转载和采集!