-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.js
138 lines (124 loc) · 2.84 KB
/
utils.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
const _ = require('lodash')
const areSameColor = (piece1, piece2) => {
return (piece1 > 0 && piece2 > 0) || (piece1 < 0 && piece2 < 0)
}
const isValidPosition = (pos) => {
return !(pos[0] < 0 || pos[0] > 7 || pos[1] < 0 || pos[1] > 7)
}
const getElement = (board, pos) => {
if (!isValidPosition(pos)) {
return
}
return board[pos[0]][pos[1]]
}
const setElement = (board, pos, ele) => {
if (!isValidPosition(pos)) {
return
}
board[pos[0]][pos[1]] = ele
}
const getOffsetPos = (pos, offset) => {
return [
pos[0] - offset[1],
pos[1] + offset[0]
]
}
const getColorByPos = (board, piecePos) => {
const piece = getElement(board, piecePos)
if (piece > 0) return 1
else if (piece < 0) return -1
else return 0
}
const getPositions = (board, piece) => {
let positions = []
for (let i = 0; i < 8; i++) {
for (let j = 0; j < 8; j++) {
if (board[i][j] === piece) {
positions.push([i, j])
}
}
}
return positions
}
const checkIfSamePosition = (pos1, pos2) => {
return pos1[0] === pos2[0] && pos1[1] === pos2[1]
}
const includesPosition = (positions, pos) => {
return _.findIndex(positions, eachPos => checkIfSamePosition(eachPos, pos)) !== -1
}
const getColorName = val => {
let color;
if (val > 0) color = 'white';
else if (val < 0) color = 'black';
else color = 'none';
return color;
}
const getColorValByName = name => {
if (!name) return 0;
name = name.toLowerCase();
if (name === 'white') return 1;
else if (name === 'black') return -1;
else return 0;
}
const getPieceName = val => {
let piece;
val = Math.abs(val);
switch (val) {
case 1:
piece = 'pawn';
break;
case 2:
piece = 'rook';
break;
case 3:
piece = 'knight';
break;
case 4:
piece = 'bishop';
break;
case 5:
piece = 'queen';
break;
case 6:
piece = 'king';
break;
default:
piece = 'none';
break;
}
return piece;
}
const getPieceValByName = piece => {
if (!piece) return 0;
piece = piece.toLowerCase();
switch (piece) {
case 'pawn':
return 1;
case 'rook':
return 2;
case 'knight':
return 3;
case 'bishop':
return 4;
case 'queen':
return 5;
case 'king':
return 6;
default:
return 0;
}
}
module.exports = {
areSameColor,
getElement,
setElement,
getOffsetPos,
getColorByPos,
getPositions,
checkIfSamePosition,
includesPosition,
getColorName,
getColorValByName,
getPieceName,
getPieceValByName,
}