package.json: Настроен как ES-модуль, содержит зависимости @stomp/stompjs (протокол STOMP) и ws (клиент WebSockets для Node.js). В качестве локальной зависимости подключена папка вашего скомпилированного Scala-движка: "@rabestro/dicechess-engine": "file:../dicechess-engine-scala".
index.js: Входная точка приложения. Загружает .env, инициализирует выбранного бота и подключает его к WebSocket-коннектору.
src/connector.js: Модуль управления соединением с dicechess.com. Отвечает за:
Установление соединения с правильными заголовками (Origin, User-Agent, JWT).
Подписку на лобби /topic/lobby.
Автоподписку на игровую комнату при начале матча с участием вашего BOT_USER_ID.
Жизненный цикл игры (отправка UPDATE_STATE, бросок кубиков THROW_DICES, отправка ходов MOVE).
src/bots/engineBot.js: Изолированный класс бота. Он импортирует ваш локальный Scala.js движок, конструирует правильный DFEN-формат (подмешивая кубики к шахматному FEN) и вызывает DiceChess.getBestMove с выбранным алгоритмом (greedy, random). Также умеет применять сделанные ходы к FEN с помощью DiceChess.applyMove для поддержки актуального состояния доски.
.env: Содержит переданный вами токен, ID вашего игрока (163) и WebSocket URL.
.gitignore & README.md: Защищают ваши токены от случайного коммита в Git и содержат понятное руководство по использованию.
Как теперь этим пользоваться:
Соберите движок (если внесли изменения):
cd ../dicechess-engine-scalasbt rootJS/fastOptJS
Запустите бота:
cd ../dicechess-botsnpm run play
Вы увидите строчку:Successfully connected to Dice Chess WebSocket!
Начните игру:
Откройте ваш обычный браузер с вашим аккаунтом на dicechess.com и начните игру против любого бота (например, DC Coach Beginner).
Бот-раннер на Node.js мгновенно перехватит эту игру через WebSocket, подпишется на нее и начнет ходить сам.
Вы сможете наблюдать за тем, как ходит ваш движок, прямо в окне браузера в реальном времени.
Вы можете инициализировать в папке dicechess-bots новый приватный Git-репозиторий и развивать там новые алгоритмы, добавляя их файлы в src/bots/ и переключая конфигурацию в .env. Удачи в тестировании движка!
I will create a walkthrough artifact to document the changes made and the testing performed.
Edited walkthrough.md
I have completed the investigation and resolved the underlying issues:
1. Root Cause Analysis
The engine does compute legal moves and a valid best move sequence for the problematic position rnbqkbnr/pppppppp/8/1N6/P1B1P3/3Q4/1PPP1PPP/R1B1K1NR b KQkq - 0 1 kpq (e.g. Pawn moves c7c6, c7c5, d7d6, etc.).
The reason the bot did not play a move during the game was that the compiled JS bundle in dist/ was out of sync. Because of that, getLegalUciMoves or getBestMove threw exceptions or returned incomplete data.
Additionally, the greedy bot strategy uses a randomized tie-breaker for moves that evaluate to the same material score (e.g. at the beginning of the game). This is why running tests/scripts on the starting position returns different, yet equally valid, legal sequences (like f7f6 -> e8f7 -> d8e8 or c7c6 -> d8b6 -> e8d8).
2. Implemented Fixes
Dice Sorting: Updated buildDfen in engineBot.js to sort dice values before appending them to the 7th field of the DFEN (e.g., p < n < b < r < q < k), ensuring compliance with the engine’s parser.
Mac CLI Compatibility: Fixed a syntax bug in .mise/tasks/package/prepare where an escaped trailing slash (\/) in a sed statement caused version synchronization to fail on macOS.
Production Compilation: Re-built and packaged the engine using mise run package:prepare, updating the linked @rabestro/dicechess-engine dependency to version 1.2.3.
3. How to Test End-to-End
Please try running an end-to-end game play test against a website bot:
Open dicechess.com in your browser and start a game (e.g., against DC Coach Master).
Copy the UUID from the browser URL (e.g., dicechess.com/game/<game-id>).
Run the bot runner in your terminal, forcing it to join your active game:
cd /Users/jegors/Repositories/dicechess-botsnpm run play -- <game-id>
Check the walkthrough.md artifact for details of the verification steps performed. Please let me know how the end-to-end test goes!
Walkthrough
Changes Made
Dice Sorting in Bot Runner: Modified buildDfen in engineBot.js to strictly sort the parsed dice values by piece value before encoding them into the 7th field of the DFEN (e.g., p < n < b < r < q < k). This guarantees strict compliance with the engine’s DFEN specification.
Mac CLI Compatibility Fix: Fixed a syntax error in the packaging task .mise/tasks/package/prepare where an escaped trailing slash (\/) in a sed replacement string caused the version synchronization to fail on macOS.
Dependency Update: Compiled and packaged the production Scala.js bundle using mise run package:prepare, updating the symlinked @rabestro/dicechess-engine dependency to version 1.2.3 in the bot runner.
What Was Tested
Engine Move Calculation: Evaluated the engine on the game state rnbqkbnr/pppppppp/8/1N6/P1B1P3/3Q4/1PPP1PPP/R1B1K1NR b KQkq - 0 1 kpq. The engine correctly generated all legal micro-moves (c7c6, c7c5, d7d6, etc.) and resolved a valid sequence using the greedy search strategy.
Deterministic Evaluation & Tie-Breaking: Confirmed that the greedy algorithm evaluates legal moves correctly and utilizes tie-breaking for equal static evaluation states, which accounts for the variation in recommended sequences during different test runs.
JS Wrapper Validation: Created and executed a standalone Node script loading the compiled bundle, verifying that the JavaScript API wrapper executes error-free.