-
Notifications
You must be signed in to change notification settings - Fork 366
Expand file tree
/
Copy pathfenToJson.ts
More file actions
170 lines (150 loc) · 4.73 KB
/
Copy pathfenToJson.ts
File metadata and controls
170 lines (150 loc) · 4.73 KB
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
// file: fenToJson.ts
import type { FileData, FileFormat, FormatHandler } from "../FormatHandler.ts";
import CommonFormats, { Category } from "src/CommonFormats.ts";
import { BLACK, KING, QUEEN, SQUARES, WHITE, type Color, type PieceSymbol, type Square } from 'chess.js';
// same as .board() on chess.js
type BoardSquare = {
square: Square;
type: PieceSymbol;
color: Color;
} | null;
type Game = {
board: BoardSquare[][],
turn: Color,
castling: {
[WHITE]: {
[KING]: boolean;
[QUEEN]: boolean;
},
[BLACK]: {
[KING]: boolean;
[QUEEN]: boolean;
},
},
epSquare: Square | null,
halfMoves: number,
moveNumber: number,
};
function isSquare(value: string): value is Square { // ts is cool
return (SQUARES as string[]).includes(value);
}
function isPieceSymbol(value: string): value is PieceSymbol {
return "pnbrqk".includes(value);
}
class fenToJsonHandler implements FormatHandler {
public name: string = "fenToJson";
public supportedFormats: FileFormat[] = [
{
name: "Forsyth–Edwards Notation",
format: "fen",
extension: "fen",
mime: "application/vnd.chess-fen",
from: true,
to: true,
internal: "fen",
category: Category.TEXT,
lossless: true
},
CommonFormats.JSON.builder("json").allowTo().allowFrom().markLossless(),
];
public ready: boolean = false;
async init () {
this.ready = true;
}
async doConvert (
inputFiles: FileData[],
inputFormat: FileFormat,
outputFormat: FileFormat
): Promise<FileData[]> {
const outputFiles: FileData[] = [];
for (const inputFile of inputFiles) {
const input = new TextDecoder().decode(inputFile.bytes).trim();
let output;
if (inputFormat.internal === "fen") {
const [boardFen, turn, castling, epSquare, halfMoves, moveNumber] = input.split(" ");
let board: BoardSquare[][] = [];
let currentSquare = 0;
for (const rowFen of boardFen.split("/")) {
const row: BoardSquare[] = [];
for (const char of rowFen) {
if (char >= '0' && char <= '9') {
row.push(...Array(Number(char)).fill(null));
currentSquare += Number(char);
} else {
const type = char.toLowerCase();
row.push({
square: SQUARES[currentSquare],
color: char >= 'A' && char <= 'Z' ? WHITE : BLACK,
type: isPieceSymbol(type) ? type : 'p'
});
currentSquare += 1;
}
}
board.push(row);
}
const game: Game = {
board,
turn: turn === 'w' ? WHITE : BLACK,
castling: {
[WHITE]: {
[KING]: castling.includes('K'),
[QUEEN]: castling.includes('Q'),
},
[BLACK]: {
[KING]: castling.includes('k'),
[QUEEN]: castling.includes('q'),
},
},
epSquare: isSquare(epSquare) ? epSquare : null,
halfMoves: Number(halfMoves),
moveNumber: Number(moveNumber)
};
output = JSON.stringify(game);
} else if (inputFormat.internal === "json") {
const game: Game = JSON.parse(input);
let fen: string[] = [];
let boardFen: string[] = [];
for (const row of game.board) {
let rowFen = [];
let emptyCounter = 0;
for (const square of row) {
if (!square) {
emptyCounter++;
continue;
}
if (emptyCounter > 0) {
rowFen.push(String(emptyCounter));
emptyCounter = 0;
}
rowFen.push(
square.color === WHITE
? square.type.toUpperCase()
: square.type.toLowerCase()
);
}
if (emptyCounter > 0) {
rowFen.push(String(emptyCounter));
}
boardFen.push(rowFen.join(''));
}
fen.push(boardFen.join('/'));
fen.push(game.turn);
const castling =
(game.castling[WHITE][KING] ? 'K' : '')
+ (game.castling[WHITE][QUEEN] ? 'Q' : '')
+ (game.castling[BLACK][KING] ? 'k' : '')
+ (game.castling[BLACK][QUEEN] ? 'q' : '');
fen.push(castling !== '' ? castling : '-');
fen.push(game.epSquare ?? '-');
fen.push(String(game.halfMoves));
fen.push(String(game.moveNumber));
output = fen.join(' ');
}
const bytes = new TextEncoder().encode(output);
const name = inputFile.name.replace(/\.[^.]+$/, "") + `.${outputFormat.extension}`;
outputFiles.push({ name, bytes });
}
return outputFiles;
}
}
export default fenToJsonHandler;