-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
118 lines (113 loc) · 2.8 KB
/
index.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
<html>
<head>
<meta charset="UTF-8">
<title>Tic Tac Toe</title>
<style>
*{
margin: 0;
padding: 0;
}
#Game{
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
}
#Grid{
display: grid;
align-content: space-evenly;
justify-content: space-evenly;
grid-template-rows: repeat(3,31%);
grid-template-columns: repeat(3,31%);
width: 400px;
height: 400px;
border: 2px solid black;
background: #cfcfcf;
}
button.cell{
font-weight: bold;
font-size: 80px;
}
#Game span.Title{
font-family: Arial Black;
font-weight: bold;
font-size: 40px;
}
#Game span[id=Message]{
font-family: Century Gothic;
font-weight: bold;
font-size: 30px;
color: red;
}
</style>
</head>
<body>
<div id="Game">
<span class="Title">Tic Tac Toe</span>
<div id="Grid">
<button class="cell"/></button>
<button class="cell"/></button>
<button class="cell"/></button>
<button class="cell"/></button>
<button class="cell"/></button>
<button class="cell"/></button>
<button class="cell"/></button>
<button class="cell"/></button>
<button class="cell"/></button>
</div><br>
<span id="Message"></span>
</div>
<script type="text/javascript">
const player = ["X","O"];
const grid = document.getElementById("Grid");
const cell = grid.querySelectorAll(".cell");
var current = 0;
function makeMove(event,elem){
if(elem.innerText == ""){ //Valid
if(!hasWon(cell)){
elem.innerText = player[current];
current = (current + 1) % 2;
}
}
if(hasWon(cell)){
document.querySelector("span[id=Message]").innerText = hasWon(cell) + " has won the game!";
}else if(!isEmpty()){
document.querySelector("span[id=Message]").innerText = "The game ended with DRAW!";
}
}
function isEmpty(){
let empty = false;
cell.forEach(c => {
if(c.innerText == "") {
empty = true;
}
})
return empty;
}
function hasWon(cell){
let p = player[1 - current];
for(let i=0;i<9;i++){
if(i == 0 || i == 3 || i == 6){
if(cell[i].innerText == p && cell[i+1].innerText == p && cell[i+2].innerText == p) // Horizontal check
return p;
}
if(i == 0 || i == 2){
let j = (i==0) ? 0 : 2;
if(cell[i].innerText == p && cell[i+4-j].innerText == p && cell[i+8-j*2].innerText == p) // Diagonal check
return p;
}
if(i == 0 || i == 1 || i == 2){
if(cell[i].innerText == p && cell[i+3].innerText == p && cell[i+6].innerText == p) // Vertical check
return p;
}
}
return undefined;
}
cell.forEach((elem) => {
elem.setAttribute("onclick","makeMove(event,this)");
})
</script>
</body>
</html>