-
Notifications
You must be signed in to change notification settings - Fork 90
/
Tic_Tac_Toe.js
69 lines (63 loc) · 1.4 KB
/
Tic_Tac_Toe.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
class TicTacToe {
constructor() {
this.matrix = [];
for (var i = 0; i < 3; i++) {
this.matrix[i] = [];
for (var j = 0; j < 3; j++) {
this.matrix[i][j] = "-";
}
}
}
validToken(token) {
if (token == "X" || token == "0" || token == "-") {
return true;
}
console.log("Token is invalid");
return false;
}
addToken(x, y, token) {
// Check valid positions
if (this.validToken(token)) {
this.matrix[x][y] = token;
}
}
printBoard() {
console.log("-------");
for (var row = 0; row < 3; row++) {
console.log(
this.matrix[row][0] +
"|" +
this.matrix[row][1] +
"|" +
this.matrix[row][2]
); // Check new line;
}
console.log("------- \n");
}
isBoardFull() {
for (var row = 0; row < 3; row++) {
for (var col = 0; col < 3; col++) {
if (this.matrix[row][col] === "-") {
console.log("Is not full");
return false;
}
}
}
console.log("Is full");
return true;
}
makeMove(str) {
if (this.isBoardFull()) {
throw "Error Board is Full";
}
for (var row = 0; row < 3; row++) {
for (var col = 0; col < 3; col++) {
if (this.matrix[row][col] === "-") {
this.addToken(row, col, str);
return true;
}
}
}
}
}
module.exports.TicTacToe = TicTacToe;