-
Notifications
You must be signed in to change notification settings - Fork 2
/
script.user.js
68 lines (59 loc) · 1.97 KB
/
script.user.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
// ==UserScript==
// @name Lichess Bot
// @description Fully automated lichess bot
// @author Nuro
// @match *://lichess.org/*
// @run-at document-start
// @grant none
// @require https://cdn.jsdelivr.net/gh/NuroC/stockfish.js/stockfish.js
// ==/UserScript==
let chessEngine;
let currentFen = "";
let bestMove;
let webSocketWrapper = null;
function initializeChessEngine() {
chessEngine = window.STOCKFISH();
}
function interceptWebSocket() {
let webSocket = window.WebSocket;
const webSocketProxy = new Proxy(webSocket, {
construct: function (target, args) {
let wrappedWebSocket = new target(...args);
webSocketWrapper = wrappedWebSocket;
wrappedWebSocket.addEventListener("message", function (event) {
let message = JSON.parse(event.data);
console.log(message)
if (message.d && typeof message.d.fen === "string" && typeof message.v === "number") {
currentFen = message.d.fen;
let isWhitesTurn = message.v % 2 == 0;
if (isWhitesTurn) {
currentFen += " w";
} else {
currentFen += " b";
}
calculateMove();
}
});
return wrappedWebSocket;
}
});
window.WebSocket = webSocketProxy;
}
function calculateMove() {
chessEngine.postMessage("position fen " + currentFen);
chessEngine.postMessage("go depth 1");
}
function setupChessEngineOnMessage() {
chessEngine.onmessage = function (event) {
if (event && event.includes("bestmove")) {
bestMove = event.split(" ")[1];
webSocketWrapper.send(JSON.stringify({
t: "move",
d: { u: bestMove, b: 1, l: 100, a: 1 }
}));
}
};
}
initializeChessEngine();
interceptWebSocket();
setupChessEngineOnMessage();