-
Notifications
You must be signed in to change notification settings - Fork 2
/
test.html
119 lines (107 loc) · 3.53 KB
/
test.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
<!DOCTYPE html>
<html>
<head>
<title>Tic Tac Toe</title>
<style>
/* Add your CSS styles here */
td{
width: 60px;
height: 60px;
border: 1px solid black;
}
</style>
</head>
<body>
<h1 id="turn">Player X's Turn</h1>
<table id="board">
<tr>
<td onclick="makeMove(0, 0)"></td>
<td onclick="makeMove(0, 1)"></td>
<td onclick="makeMove(0, 2)"></td>
</tr>
<tr>
<td onclick="makeMove(1, 0)"></td>
<td onclick="makeMove(1, 1)"></td>
<td onclick="makeMove(1, 2)"></td>
</tr>
<tr>
<td onclick="makeMove(2, 0)"></td>
<td onclick="makeMove(2, 1)"></td>
<td onclick="makeMove(2, 2)"></td>
</tr>
</table>
<script>
// JavaScript code goes here
var board = [
['', '', ''],
['', '', ''],
['', '', '']
];
var currentPlayer = 'X';
function makeMove(row, col) {
// Check if the cell is empty
if (board[row][col] === '') {
// Set the current player's symbol on the board
board[row][col] = currentPlayer;
// Update the cell with the current player's symbol
document.getElementById('board').rows[row].cells[col].innerHTML = currentPlayer;
// Check for a win
if (checkWin(currentPlayer)) {
document.getElementById('turn').innerHTML = 'Player ' + currentPlayer + ' wins!';
setTimeout(resetBoard, 1000); // Wait for 1 second and then reset the board
} else {
// Switch players
currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
document.getElementById('turn').innerHTML = "Player " + currentPlayer + "'s Turn";
}
}
}
function checkWin(player) {
// Check rows
for (var i = 0; i < 3; i++) {
if (
board[i][0] === player &&
board[i][1] === player &&
board[i][2] === player
) {
return true;
}
}
// Check columns
for (var j = 0; j < 3; j++) {
if (
board[0][j] === player &&
board[1][j] === player &&
board[2][j] === player
) {
return true;
}
}
// Check diagonals
if (
(board[0][0] === player && board[1][1] === player && board[2][2] === player) ||
(board[0][2] === player && board[1][1] === player && board[2][0] === player)
) {
return true;
}
return false;
}
function resetBoard() {
// Clear the board
board = [
['', '', ''],
['', '', ''],
['', '', '']
];
// Clear the cell contents
var cells = document.getElementById('board').getElementsByTagName('td');
for (var i = 0; i < cells.length; i++) {
cells[i].innerHTML = '';
}
// Reset the current player
currentPlayer = 'X';
document.getElementById('turn').innerHTML = "Player " + currentPlayer + "'s Turn";
}
</script>
</body>
</html>