-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtictactoe.js
82 lines (62 loc) · 2.38 KB
/
tictactoe.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
class TicTacToe {
constructor(element){
this._element = element;
this._gameOver = true;
};
startGame(player1, player2){
if(!player1 || !player2){
return;
}
this._grid = [
[GridType.EMPTY, GridType.EMPTY, GridType.EMPTY],
[GridType.EMPTY, GridType.EMPTY, GridType.EMPTY],
[GridType.EMPTY, GridType.EMPTY, GridType.EMPTY],
];
this._playerType = GridType.O;
this._activePlayer = player1;
this._passivePlayer = player2;
this._gameOver = false;
this._activePlayer.notify(this._playerType, this._grid, GameState.ONGOING);
this.render();
};
selectCell(col, row){
if(this._grid[col][row] == GridType.EMPTY && !this._gameOver){
this._grid[col][row] = this._playerType;
if(GameUtils.IsWinningMove(this._grid, this._playerType)){
this._gameOver = true;
this._activePlayer.notify(this._playerType, this._grid, GameState.WIN);
this._passivePlayer.notify(this._playerType, this._grid, GameState.LOSE);
} else if (GameUtils.AllValidMoves(this._grid).length == 0 ) {
this._gameOver = true;
this._activePlayer.notify(this._playerType, this._grid, GameState.DRAW);
this._passivePlayer.notify(this._playerType, this._grid, GameState.DRAW);
} else {
this.togglePlayer();
this._activePlayer.notify(this._playerType, this._grid, GameState.ONGOING);
}
this.render();
}
};
togglePlayer(){
if(this._playerType == GridType.O){
this._playerType = GridType.X;
} else {
this._playerType = GridType.O;
}
// Swap players
this._activePlayer = [this._passivePlayer, this._passivePlayer = this._activePlayer][0];
};
render(){
let container = $('<table>');
this._grid.map((grid, col) => {
let tr = $('<tr>');
grid.map((cell, row) => {
let td = $('<td col="'+col+'" row="'+row+'">'+GameUtils.RenderGrid(cell)+'</td>');
td.click(() => this.selectCell(col, row));
tr.append(td);
});
container.append(tr);
});
this._element.html(container);
};
};