-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.js
More file actions
122 lines (95 loc) · 2.45 KB
/
main.js
File metadata and controls
122 lines (95 loc) · 2.45 KB
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
const squares = document.querySelectorAll(".square");
const txtTurn = document.getElementById("txtTurn");
let turn = 0;
let move = 0;
let board = [
["1", "2", "3"],
["4", "5", "6"],
["7", "8", "9"],
];
let options = ["X", "O"];
squares.forEach((square) => {
square.addEventListener("click", () => {
square.innerText = getSymbol(turn);
// The id of each div square is his coordinate on the boad
let [row, col] = square.id.split(",");
// Disable the click for preventing double click on a square
square.style.pointerEvents = "none";
board[row][col] = options[turn];
if (hasWinned()) {
declareEndGame(turn, { isStalemate: false });
} else if (isLastMove()) {
declareEndGame(turn, { isStalemate: true });
}
if (turn == 0) turn++;
else turn--;
move++;
txtTurn.innerText = "Turno de las " + options[turn];
});
});
function getSymbol(turn) {
return options[turn];
}
function hasWinned() {
// Check rows
for (let i = 0; i < 3; i++) {
console.log(board);
let firstRow = board[i][0];
let secondRow = board[i][1];
let thirRow = board[i][2];
console.log(`${firstRow}, ${secondRow}, ${thirRow}`);
if (areEquals(firstRow, secondRow, thirRow)) {
return true;
}
}
// Check cols
for (let i = 0; i < 3; i++) {
console.log(board);
let firstCol = board[0][i];
let secondCol = board[1][i];
let thirdCol = board[2][i];
console.log(`${firstCol}, ${secondCol}, ${thirdCol}`);
if (areEquals(firstCol, secondCol, thirdCol)) {
return true;
}
}
// Right diagonal
let firstCord = board[0][0];
let secondCord = board[1][1];
let thirdCord = board[2][2];
if (areEquals(firstCord, secondCord, thirdCord)) return true;
// Left diagonal
firstCord = board[0][2];
secondCord = board[1][1];
thirdCord = board[2][0];
if (areEquals(firstCord, secondCord, thirdCord)) return true;
return false;
}
function isLastMove() {
return move == 8;
}
function declareEndGame(turn, { isStalemate }) {
if (isStalemate) {
alert("Empate!");
} else {
alert(`Han ganado las ${options[turn]}`);
}
txtTurn.innerText = "Turno de las X";
resetGame();
}
function resetGame() {
squares.forEach((square) => {
square.innerHTML = "";
square.style.pointerEvents = "auto";
});
board = [
["1", "2", "3"],
["4", "5", "6"],
["7", "8", "9"],
];
move = 0;
turn = 0;
}
function areEquals(a, b, c) {
return a === b && a === c;
}