-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
71 lines (68 loc) · 1.86 KB
/
main.js
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
var grid = [];
//1 = cross; -1 = circle;
var next = 1;
var winner = 0;
var lockInput = false;
function newGame() {
document.getElementById("board").innerHTML="";
document.getElementById("newGame").classList.remove("bBtn");
const fieldTemplate = '<div id="%x-%y"><button class="field" onclick="clickField(%x,%y)"> </button></div>';
grid = [];
winner = 0;
lockInput=false;
for (let y = 0; y < 3; y++) {
var row = [];
for (let x = 0; x < 3; x++) {
row.push(0);
document.getElementById("board").innerHTML+=fieldTemplate.replaceAll("%x",x).replaceAll("%y",y);
//col.push(fieldTemplate.replace("%x",x).replace("%y",y));
};
grid.push(row);
}
//console.log(grid);
}
function clickField(x,y) {
if(lockInput)return;
grid[y][x]=next==1?1:-1;
document.getElementById(x+"-"+y).classList.add(grid[y][x]==1?"cross":"circle");
document.getElementById(x+"-"+y).innerHTML="";
next=next==1?-1:1;
checkWin();
}
function checkWin() {
var wC = 0;
// horizontal
for(let row of grid){
wC = 0;
row.forEach(c=>{wC=wC+c});
if(wC==3||wC==-3){
winner=wC==3?1:-1;
win();
return;
};
}
// vertical
for(let x = 0; x < 3; x++){
wC = grid[0][x]+grid[1][x]+grid[2][x];
if(wC==3||wC==-3){
winner=wC==3?1:-1;
win();
return;
};
}
// diagonal
for(let i = 0; i < 2; i++){
wC=grid[0+(i*2)][0]+grid[1][1]+grid[2-(i*2)][2];
if(wC==3||wC==-3){
winner=wC==3?1:-1;
win();
return;
};
}
}
function win() {
lockInput=true;
console.log("Winner: " + winner);
document.getElementById("newGame").classList.add("bBtn");
setTimeout(()=>{alert(`${winner==1?"X":"O"} wins!`)},100);
}