-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcore.js
84 lines (69 loc) · 2.22 KB
/
core.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
// Groupby function
// https://stackoverflow.com/a/34890276
function groupBy (xs, key) {
return xs.reduce(function(rv, x) {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
};
// Verifica o resultado
function checkResult (gameHistory) {
const xHistory = gameHistory.filter(function(entry) {
return entry[0] === 'X';
});
const oHistory = gameHistory.filter(function(entry) {
return entry[0] === 'O';
});
const xResult = checkPlayerResult(xHistory);
const oResult = checkPlayerResult(oHistory);
if (!xResult && !oResult && gameHistory.length >= 9) {
if (typeof setWinner !== 'undefined') setWinner();
return 'D';
}
if (xResult) {
return 'X';
} else if (oResult) {
return 'O';
}
return false;
}
// Verifica o resultado do jogador
function checkPlayerResult (history) {
if (history.length === 0) return;
const player = history[0][0];
const entries = history.map(function(entry) {
return entry.substring(1);
});
const rowCount = groupBy(entries, 0);
const colCount = groupBy(entries, 1);
// Verificando se o jogador ganhou em linha
for (let i in rowCount) {
if (rowCount[i].length === 3) {
if (typeof setWinner !== 'undefined') setWinner(player, rowCount[i]);
return player;
}
}
// Verificando se o jogador ganhou em coluna
for (let i in colCount) {
if (colCount[i].length === 3) {
if (typeof setWinner !== 'undefined') setWinner(player, colCount[i]);
return player;
}
}
// Verificando se o jogador ganhou em diagonal
if (entries.includes('A1') && entries.includes('B2') && entries.includes('C3')) {
if (typeof setWinner !== 'undefined') setWinner(player, ['A1', 'B2', 'C3']);
return player;
}
// Verificando se o jogador ganhou em diagonal
else if (entries.includes('A3') && entries.includes('B2') && entries.includes('C1')) {
if (typeof setWinner !== 'undefined') setWinner(player, ['A3', 'B2', 'C1']);
return player;
}
return false;
}
if (typeof module !== 'undefined') {
module.exports = {
checkResult: checkResult
}
}