How to Create a Tic Tac Toe Game in HTML: A Simple Guide
Tic Tac Toe Game
To create a Tic Tac Toe game in HTML, follow these steps:
- First, create a 3x3 grid using the HTML table tag.
<table>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
- Add a class to each table cell, so that it can be identified in JavaScript. You can name the class anything you like, but for this example, we will name it 'cell'.
<table>
<tr>
<td class='cell'></td>
<td class='cell'></td>
<td class='cell'></td>
</tr>
<tr>
<td class='cell'></td>
<td class='cell'></td>
<td class='cell'></td>
</tr>
<tr>
<td class='cell'></td>
<td class='cell'></td>
<td class='cell'></td>
</tr>
</table>
- Create a JavaScript function that will detect when a cell is clicked, and change the content to an 'X' or 'O' depending on whose turn it is. You can use a variable to keep track of whose turn it is.
<script>
var turn = 'X';
function play(cell) {
cell.innerHTML = turn;
turn = (turn == 'X') ? 'O' : 'X';
}
</script>
- Add an onclick event to each cell that calls the play function when clicked.
<table>
<tr>
<td class='cell' onclick='play(this)'></td>
<td class='cell' onclick='play(this)'></td>
<td class='cell' onclick='play(this)'></td>
</tr>
<tr>
<td class='cell' onclick='play(this)'></td>
<td class='cell' onclick='play(this)'></td>
<td class='cell' onclick='play(this)'></td>
</tr>
<tr>
<td class='cell' onclick='play(this)'></td>
<td class='cell' onclick='play(this)'></td>
<td class='cell' onclick='play(this)'></td>
</tr>
</table>
- Add some CSS to style the game board and cells.
<style>
table {
border-collapse: collapse;
margin: auto;
}
td {
border: 1px solid black;
width: 50px;
height: 50px;
font-size: 30px;
text-align: center;
vertical-align: middle;
cursor: pointer;
}
</style>
With these steps, you should have a functioning Tic Tac Toe game in HTML!
原文地址: https://www.cveoy.top/t/topic/lnkM 著作权归作者所有。请勿转载和采集!