forked from tuhinpal/WhatsBot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchess.ts
213 lines (185 loc) · 5.7 KB
/
chess.ts
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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
//jshint esversion:8
// code generated by chatgpt, fixed by wcyat
import whatsapp, { Client, Message } from "whatsapp-web.js";
import { Command } from "../types/command.js";
const { MessageMedia } = whatsapp;
import { Chess } from "chess.js";
import { spawn } from "child_process";
import db from "../db/index.js";
import ChessImageGenerator from "@newyork.anthonyng/chess-image-generator";
const execute = async (client: Client, msg: Message, args: string[]) => {
const chat = await msg.getChat();
const chatId = chat.id._serialized;
const command = args[0];
const chessDoc = await db("chess").coll.findOne({ chatId });
const mode =
(await db("chats").coll.findOne({ chatId }))?.chess?.mode ||
(chat.isGroup ? "pvp" : "pvc");
const fen = chessDoc?.fen;
if (command === "start") {
if (fen) {
await db("chess").coll.deleteOne({ chatId });
}
const chess = new Chess();
await db("chess").coll.insertOne({ chatId, fen: chess.fen() });
client.sendMessage(chatId, "New Chess game started.");
printBoard(client, chatId, chess);
return;
}
if (command === "move") {
const chess = new Chess(fen);
const move = args.slice(1).join(" ");
try {
chess.move(move);
client.sendMessage(
chatId,
`${
chess.moveNumber() % 2 ? "White" : "Black"
} played: ${chess.moveNumber()}. ${move}`,
);
// printBoard(client, chatId, chess);
if (chess.isGameOver()) {
const result = chess.isCheckmate() ? "Checkmate!" : "Stalemate!";
client.sendMessage(chatId, result + " Game over.");
return await db("chess").coll.deleteOne({ chatId });
}
if (mode === "pvc") {
await makeComputerMove(client, chatId, chess, chessDoc.depth || 15);
}
printBoard(client, chatId, chess);
if (chess.isGameOver()) {
const result = chess.isCheckmate() ? "Checkmate!" : "Stalemate!";
client.sendMessage(chatId, result + " Game over.");
return await db("chess").coll.deleteOne({ chatId });
}
await db("chess").coll.updateOne(
{ chatId },
{ $set: { fen: chess.fen() } },
);
return;
} catch {
client.sendMessage(
chatId,
"Invalid move. Please provide a valid move in algebraic notation (e.g., e2e4).",
);
return;
}
}
if (command === "depth") {
const depth = parseInt(args[1]);
if (isNaN(depth) || depth < 10 || depth > 20) {
client.sendMessage(chatId, "Invalid depth. Valid depths are 10-20.");
return;
}
await db("chess").coll.updateOne({ chatId }, { $set: { depth } });
client.sendMessage(chatId, "Depth set to " + depth);
return;
}
if (command === "pvp") {
await db("chats").coll.updateOne(
{ chatId },
{ $set: { "chess.mode": "pvp" } },
{ upsert: true },
);
return await client.sendMessage(chatId, "Mode set to pvp.");
}
if (command === "pvc") {
await db("chats").coll.updateOne(
{ chatId },
{ $set: { "chess.mode": "pvc" } },
{ upsert: true },
);
return await client.sendMessage(chatId, "Mode set to pvc.");
}
client.sendMessage(
chatId,
`*Chess Game Commands*:
• Start a game: \`!chess start\`
• Make a move: \`!chess move [move]\`
• Help: \`!chess help\`
• Set mode:
• \`!chess pvp\`
• \`!chess pvc\``,
);
};
const printBoard = async (client: Client, chatId: string, chess: Chess) => {
const imageGenerator = new ChessImageGenerator();
await imageGenerator.loadFEN(chess.fen());
const image: Buffer = await imageGenerator.generateBuffer();
try {
client.sendMessage(
chatId,
new MessageMedia("image/png", image.toString("base64"), chess.fen()),
);
} catch {}
};
const makeComputerMove = async (
client: Client,
chatId: string,
chess: Chess,
depth = 15,
) => {
const fen = chess.fen();
const bestMove: string = await getBestMove(fen, depth);
if (bestMove) {
chess.move(bestMove);
client.sendMessage(chatId, "Computer played: " + bestMove);
} else {
client.sendMessage(chatId, "Computer failed to make a move.");
}
};
async function getBestMove(fen: string, depth = 15): Promise<string> {
return await new Promise((resolve, reject) => {
const stockfishPath = "/usr/games/stockfish";
const stockfish = spawn(stockfishPath);
const moves: string[] = [];
let movesLength = 0;
let bestMove = "";
stockfish.stdout.on("data", (data) => {
const output: string = data.toString();
output.split("\n").forEach((line) => {
if (line.includes("bestmove")) {
const parts = line.split(" ");
bestMove = parts[1].trim();
moves.push(bestMove);
// resolve(bestMove);
}
});
});
stockfish.stdout.on("exit", (code) => {
if (code !== 0) {
reject(`Stockfish exited with code ${code}.`);
}
// resolve(bestMove);
});
stockfish.stdin.write("uci\n");
stockfish.stdin.write(`position fen ${fen}\n`);
stockfish.stdin.write(`go depth ${depth}\n`);
// stockfish.stdin.write("quit\n");
(async () => {
while (movesLength !== moves.length || moves.length == 0) {
movesLength = moves.length;
await new Promise((resolve) => setTimeout(resolve, 1000));
}
resolve(moves[moves.length - 1]);
})();
});
}
const command: Command = {
name: "chess",
command: "!chess",
description: "Play a game of Chess!",
commandType: "plugin",
isDependent: false,
help: `*Chess Game Commands*:
• Start a game: \`!chess start\`
• Make a move: \`!chess move [move]\`
• Help: \`!chess help\`
• Set mode:
• \`!chess pvp\`
• \`!chess pvc\`
`,
execute,
public: true,
};
export default command;