Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
jajbshjahavahh
GitHub Repository: jajbshjahavahh/Gojo-Satoru
Path: blob/master/lib/tictactoe.js
2591 views
1
//═══════════════════════════════════════════════════════//
2
//If you want to recode, reupload
3
//or copy the codes/script,
4
//pls give credit
5
//no credit? i will take action immediately
6
//© 2022 Xeon Bot Inc. Cheems Bot MD
7
//Thank you to Lord Buddha, Family and Myself
8
//════════════════════════════//
9
class TicTacToe {
10
constructor(playerX = 'x', playerO = 'o') {
11
this.playerX = playerX
12
this.playerO = playerO
13
this._currentTurn = false
14
this._x = 0
15
this._o = 0
16
this.turns = 0
17
}
18
19
get board() {
20
return this._x | this._o
21
}
22
23
get currentTurn() {
24
return this._currentTurn ? this.playerO : this.playerX
25
}
26
27
get enemyTurn() {
28
return this._currentTurn ? this.playerX : this.playerO
29
}
30
31
static check(state) {
32
for (let combo of [7, 56, 73, 84, 146, 273, 292, 448])
33
if ((state & combo) === combo)
34
return !0
35
return !1
36
}
37
38
/**
39
* ```js
40
* TicTacToe.toBinary(1, 2) // 0b010000000
41
* ```
42
*/
43
static toBinary(x = 0, y = 0) {
44
if (x < 0 || x > 2 || y < 0 || y > 2) throw new Error('invalid position')
45
return 1 << x + (3 * y)
46
}
47
48
/**
49
* @param player `0` is `X`, `1` is `O`
50
*
51
* - `-3` `Game Ended`
52
* - `-2` `Invalid`
53
* - `-1` `Invalid Position`
54
* - ` 0` `Position Occupied`
55
* - ` 1` `Sucess`
56
* @returns {-3|-2|-1|0|1}
57
*/
58
turn(player = 0, x = 0, y) {
59
if (this.board === 511) return -3
60
let pos = 0
61
if (y == null) {
62
if (x < 0 || x > 8) return -1
63
pos = 1 << x
64
} else {
65
if (x < 0 || x > 2 || y < 0 || y > 2) return -1
66
pos = TicTacToe.toBinary(x, y)
67
}
68
if (this._currentTurn ^ player) return -2
69
if (this.board & pos) return 0
70
this[this._currentTurn ? '_o' : '_x'] |= pos
71
this._currentTurn = !this._currentTurn
72
this.turns++
73
return 1
74
}
75
76
/**
77
* @returns {('X'|'O'|1|2|3|4|5|6|7|8|9)[]}
78
*/
79
static render(boardX = 0, boardO = 0) {
80
let x = parseInt(boardX.toString(2), 4)
81
let y = parseInt(boardO.toString(2), 4) * 2
82
return [...(x + y).toString(4).padStart(9, '0')].reverse().map((value, index) => value == 1 ? 'X' : value == 2 ? 'O' : ++index)
83
}
84
85
/**
86
* @returns {('X'|'O'|1|2|3|4|5|6|7|8|9)[]}
87
*/
88
render() {
89
return TicTacToe.render(this._x, this._o)
90
}
91
92
get winner() {
93
let x = TicTacToe.check(this._x)
94
let o = TicTacToe.check(this._o)
95
return x ? this.playerX : o ? this.playerO : false
96
}
97
}
98
99
new TicTacToe().turn
100
101
module.exports = TicTacToe
102