-
Notifications
You must be signed in to change notification settings - Fork 0
/
scripts.js
85 lines (83 loc) · 2.09 KB
/
scripts.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
var divElement = document.querySelector('div'),
tableElement = document.querySelector('table');
var Game = {
start() {
this.field = [
['', '', ''],
['', '', ''],
['', '', '']
];
this.currentPlayer = 'X';
this.isFinished = false;
this.round = 0;
this.render();
},
nextPlayer() {
this.currentPlayer = this.currentPlayer === 'X' ? 'O' : 'X';
},
setField(line, column) {
if (!this.isFinished && this.field[line][column] === '') {
this.field[line][column] = this.currentPlayer;
this.nextPlayer();
this.round++;
this.render();
}
},
isGameOver() {
var field = this.field,
rows = 3,
cols = 3,
totalRow = 0,
totalCol = 0;
for (var i = 0; i < rows; i++) {
totalCol = 0;
totalRow = 0;
for (var j = 0; j < rows; j++) {
if (field[i][j] === 'X') {
totalRow++;
}
if (field[i][j] === 'O') {
totalRow--;
}
if (field[j][i] === 'X') {
totalCol++;
}
if (field[j][i] === 'O') {
totalCol--;
}
}
if (totalRow === 3 || totalCol === 3) {
return 'X';
}
if (totalRow === -3 || totalCol === -3) {
return 'O';
}
}
if (field[0][0] !== '' && field[0][0] === field[1][1] && field[1][1] === field[2][2]) {
return field[0][0];
}
if (field[0][2] !== '' && field[0][2] === field[1][1] && field[1][1] === field[2][0]) {
return field[0][2];
}
if (this.round === 9) {
return 'Ninguém';
}
},
render() {
var winner = this.isGameOver();
divElement.textContent = winner ? `Vencedor: ${winner}` : `Jogador atual: ${this.currentPlayer}`;
if (winner) {
this.isFinished = true;
}
var template = '';
this.field.forEach((line, lineIndex) => {
template += '<tr>';
line.forEach((column, columnIndex) => {
template += `<td onclick="Game.setField(${lineIndex}, ${columnIndex})">${column}</td>`;
})
template += '</tr>'
});
tableElement.innerHTML = template;
}
}
Game.start();