-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtic-tac-toe.html
109 lines (100 loc) · 3.19 KB
/
tic-tac-toe.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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tic-Tac-Toe</title>
<style>
body {
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f0f0f0;
}
.board {
display: grid;
grid-template-columns: repeat(3, 100px);
grid-template-rows: repeat(3, 100px);
gap: 5px;
}
.cell {
width: 100px;
height: 100px;
background-color: #fff;
display: flex;
justify-content: center;
align-items: center;
font-size: 2em;
cursor: pointer;
}
.cell:hover {
background-color: #e0e0e0;
}
.status {
margin-top: 20px;
text-align: center;
}
</style>
</head>
<body>
<div>
<div class="board" id="board">
<div class="cell" data-index="0"></div>
<div class="cell" data-index="1"></div>
<div class="cell" data-index="2"></div>
<div class="cell" data-index="3"></div>
<div class="cell" data-index="4"></div>
<div class="cell" data-index="5"></div>
<div class="cell" data-index="6"></div>
<div class="cell" data-index="7"></div>
<div class="cell" data-index="8"></div>
</div>
<div class="status" id="status"></div>
</div>
<script>
const board = document.getElementById('board');
const statusDisplay = document.getElementById('status');
let boardState = ["", "", "", "", "", "", "", "", ""];
let currentPlayer = "X";
let gameActive = true;
const winningConditions = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6]
];
function handleCellClick(event) {
const clickedCell = event.target;
const clickedCellIndex = parseInt(clickedCell.getAttribute('data-index'));
if (boardState[clickedCellIndex] !== "" || !gameActive) {
return;
}
boardState[clickedCellIndex] = currentPlayer;
clickedCell.textContent = currentPlayer;
if (checkWin()) {
statusDisplay.textContent = `Player ${currentPlayer} wins!`;
gameActive = false;
return;
}
if (boardState.every(cell => cell !== "")) {
statusDisplay.textContent = "It's a draw!";
gameActive = false;
return;
}
currentPlayer = currentPlayer === "X" ? "O" : "X";
}
function checkWin() {
return winningConditions.some(condition => {
return condition.every(index => boardState[index] === currentPlayer);
});
}
board.addEventListener('click', handleCellClick);
</script>
</body>
</html>