📅  最后修改于: 2023-12-03 15:20:37.779000             🧑  作者: Mango
Tic-Tac-Toe is a classic two-player game that is easy to learn but difficult to master. In this JavaScript program, we have created a basic Tic-Tac-Toe game that you can play in the browser.
To use this program, simply open the index.html
file in your web browser. You will see a 3x3 grid where you can click to make your move. The game alternates between X and O. The first player to get three in a row (horizontally, vertically, or diagonally) wins the game.
The game is implemented using JavaScript and HTML. The HTML file contains a 3x3 grid of div elements that are styled using CSS. The JavaScript file handles the game logic, such as keeping track of whose turn it is and checking for a winner.
Here is an example of the game board HTML code:
<div id="board">
<div class="square" id="0"></div>
<div class="square" id="1"></div>
<div class="square" id="2"></div>
<div class="square" id="3"></div>
<div class="square" id="4"></div>
<div class="square" id="5"></div>
<div class="square" id="6"></div>
<div class="square" id="7"></div>
<div class="square" id="8"></div>
</div>
The JavaScript code uses the addEventListener
method to add a click event listener to each square on the game board. When a square is clicked, the handleClick
function is called, which changes the text of the square to either X or O, depending on whose turn it is.
Here is an excerpt from the JavaScript code that handles a player's move:
function handleClick(event) {
const square = event.target;
const squareIndex = parseInt(square.id);
if (board[squareIndex] !== '') {
return; // square is already taken
}
board[squareIndex] = currentPlayer;
square.textContent = currentPlayer;
if (checkForWinner()) {
// game is over
gameOver();
} else if (checkForDraw()) {
// game is a draw
gameDraw();
} else {
// continue game
changePlayer();
}
}
The checkForWinner
and checkForDraw
functions check if the game has been won or is a draw, respectively. If the game is over, the gameOver
or gameDraw
functions are called to display a message to the user. If the game is not over, the changePlayer
function is called to switch to the next player's turn.
In conclusion, this JavaScript program demonstrates the basics of creating a Tic-Tac-Toe game in the browser. With some additional styling and functionality, this game could be expanded into a more advanced version of Tic-Tac-Toe.