Tic Tac Toe Game: Play Online - Free HTML Game
Tic Tac Toe Game
This is a simple tic-tac-toe game built using HTML, CSS and JavaScript. You can play it right in your browser!
Game Rules
- The game is played on a 3x3 grid.
- Player 1 is 'X' and player 2 is 'O'.
- Players take turns putting their marks in empty squares.
- The first player to get 3 of their marks in a row (up, down, across, or diagonally) is the winner.
- If all 9 squares are full and no player has 3 marks in a row, the game is a draw.
Game Interface
To play the game, simply click on an empty square to place your mark. The game will automatically alternate between player 1 and player 2.
Here is the HTML code for the game interface:
<!DOCTYPE html>
<html>
<head>
<title>Tic Tac Toe Game</title>
<style type="text/css">
table {
border-collapse: collapse;
margin: auto;
}
td {
border: 1px solid black;
height: 80px;
width: 80px;
text-align: center;
font-size: 50px;
font-weight: bold;
cursor: pointer;
}
</style>
</head>
<body>
<table>
<tr>
<td id="0"></td>
<td id="1"></td>
<td id="2"></td>
</tr>
<tr>
<td id="3"></td>
<td id="4"></td>
<td id="5"></td>
</tr>
<tr>
<td id="6"></td>
<td id="7"></td>
<td id="8"></td>
</tr>
</table>
<script type="text/javascript">
var currentPlayer = 1;
var board = ['', '', '', '', '', '', '', '', ''];
var winningPatterns = [[0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [2,4,6]];
var gameEnded = false;
function squareClicked(square) {
if (board[square.id] == '' && !gameEnded) {
if (currentPlayer == 1) {
square.innerHTML = 'X';
board[square.id] = 'X';
currentPlayer = 2;
} else {
square.innerHTML = 'O';
board[square.id] = 'O';
currentPlayer = 1;
}
checkWin();
}
}
function checkWin() {
for (var i = 0; i < winningPatterns.length; i++) {
var pattern = winningPatterns[i];
if (board[pattern[0]] == board[pattern[1]] && board[pattern[1]] == board[pattern[2]] && board[pattern[0]] != '') {
gameEnded = true;
alert('Player ' + currentPlayer + ' wins!');
break;
}
}
if (!gameEnded && board.indexOf('') == -1) {
gameEnded = true;
alert('Draw!');
}
}
var squares = document.getElementsByTagName('td');
for (var i = 0; i < squares.length; i++) {
squares[i].addEventListener('click', function() { squareClicked(this); });
}
</script>
</body>
</html>
Conclusion
This is a basic implementation of the tic-tac-toe game using HTML, CSS and JavaScript. You can further improve the game by adding more features and functionalities, such as:
- A two-player mode where two people can play on the same computer
- A single-player mode where you can play against a computer AI
- A way to keep track of the score
- A reset button to start a new game
- Different visual themes and designs
原文地址: https://www.cveoy.top/t/topic/lnkR 著作权归作者所有。请勿转载和采集!