-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
92 lines (83 loc) · 2.72 KB
/
script.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
var playerAturn = null;
var displayText = document.getElementsByTagName("h2")[1];
var allFields = document.getElementsByTagName("td");
var turns = allFields.length;
function start () {
document.getElementsByTagName("button")[0].setAttribute("disabled", true);
clearBoard();
addListeners();
displaySwitch();
}
function addListeners() {
for (var i=0; i<turns; i++){
allFields[i].addEventListener("click", setSymbol);
}
}
function displaySwitch() {
playerAturn = !playerAturn;
if (playerAturn) {
displayText.innerText = "Player A's turn. Place X.";
} else {displayText.innerText = "Player B's turn. Place O.";}
}
function setSymbol(){
if (playerAturn) {this.innerHTML = '<img src="x.png" width="64px" height="64px" alt="X">';
} else {this.innerHTML = '<img src="o.png" width="64px" height="64px" alt="O">';}
this.removeEventListener("click", setSymbol);
turns -= 1;
checkWin();
}
function checkWin(){
for (var i=0; i<3; i++){
if (allFields[3*i].innerHTML != "" && //rows
allFields[3*i+0].innerHTML == allFields[3*i+1].innerHTML &&
allFields[3*i+1].innerHTML == allFields[3*i+2].innerHTML){
displayWin();
return;
}
if (allFields[0+i].innerHTML != "" && //cols
allFields[0+i].innerHTML == allFields[3+i].innerHTML &&
allFields[3+i].innerHTML == allFields[6+i].innerHTML){
displayWin();
return;
}
if (allFields[0].innerHTML != "" &&
allFields[0].innerHTML == allFields[4].innerHTML &&
allFields[4].innerHTML == allFields[8].innerHTML){
displayWin();
return;
}
if (allFields[2].innerHTML != "" &&
allFields[2].innerHTML == allFields[4].innerHTML &&
allFields[4].innerHTML == allFields[6].innerHTML){
displayWin();
return;
}
}
checkEndGame();
}
function checkEndGame() {
if (turns == 0) {
displayText.innerText = "Draw. Nobody wins.";
removeListeners();
} else {
displaySwitch();
}
}
function displayWin(){
if (playerAturn) {
displayText.innerText = "Player A wins!";
} else {displayText.innerText = "Player B wins!";}
removeListeners();
}
function removeListeners(){
for (var i=0; i<allFields.length; i++){
allFields[i].removeEventListener("click", setSymbol);
document.getElementsByTagName("button")[0].removeAttribute("disabled", true);
}
}
function clearBoard(){
turns = allFields.length;
for (var i=0; i<turns; i++){
allFields[i].innerHTML = "";
}
}