-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtic-tac-toe.html
142 lines (128 loc) · 3.3 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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tic Tac Toe</title>
</head>
<body>
<a href="gaming.html">Back to Home</a>
<section>
<p id="scoreX"></p>
<style>
table{
border-collapse: collapse;
}
td{
border: 2px solid black;
width: 150px;
height: 150px;
font-size: xx-large;
font-weight: 900;
cursor: pointer;
text-align: center;
}
table tr:first-child td{
border-top:none ;
}
table tr:last-child td{
border-bottom:none ;
}
table tr td:first-child{
border-left: none;
}
table tr td:last-child{
border-right: none;
}
section{
display: flex;
}
body{
display: flex;
justify-content: center;
background: linear-gradient(to right,#ef395b,#f14d45,#c83383,#340bae);
}
</style>
<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>
<p id="scoreO"></p>
</section>
<script>
let player="X";
let score = {x: 0, o:0 };
const winCom = [
[0,1,2],
[3,4,5],
[6,7,8],
[0,3,6],
[1,4,7],
[2,5,8],
[0,4,8],
[2,4,6],
];
const cells = document.querySelectorAll(".cell");
cells.forEach(cell => {
cell.addEventListener("click", handleClick);
});
startGame();
function startGame(){
const scoreX = document.getElementById("scoreX");
const scoreO = document.getElementById("scoreO");
scoreX.innerText = `Player X score: ${score.x}`;
scoreO.innerText = `Player O score: ${score.o}`;
cells.forEach((cell) => (cell.innerText = ""));
}
function handleClick(e){
if(e.target.innerText ==""){
e.target.innerText=player;
checkWinner();
switchPlayer();
}
}
function checkWinner()
{
const matched = winCom.some((comb) =>
comb.every((ci) => cells[ci].innerText==player)
);
console.log(matched);
if(matched){
alert(`Player ${player}: YOU WON !!`);
if (player == "X"){
score.x +=1;
}
else{
score.o +=1;
}
score.X=3;
startGame();
}else{
const cellsArray = Array.from(cells);
if(cellsArray.every((cell) => cell.innerText != ""))
{
alert(" MATCH DRAW !!");
startGame();
}
}
}
function switchPlayer(){
player=player=="X" ? "0" : "X";
}
</script>
</body>
</html>