If you haven’t read Project Kasparov Part 1, I suggest you follow this link.
All my web projects were written in jQuery till now (except the timer, which was Angular 1.0). I was hearing a lot of praise for react in Hacker News and Reddit. I wanted to learn react so badly, but I couldn’t think of any fun project that needed it. I could upgrade some of the older ones, but I wanted to try something new.
Facebook’s React tutorial is a basic Tic-Tac-Toe game with some over the top features like time-travel, mainly intended to teach best practices for state management. I did the tutorial, but couldn’t get the hang of it.
So it decided to make a chess web app in React. I thought it’d be easier because I just did an App with a Game Pattern.
I have to thank jhlywa for the Amazing chess.js without which this app wouldn’t exist. Chess.js cover everything from move generation/validation, piece placement/movement, and check/checkmate/draw detection.
The AI at this point was just A random move generator, which selects a move at random from Chess.js’s list of valid next moves.
I followed a similar design pattern to the Tic-Tac-Toe app. Everything, including the ability to time-travel to an older move, was implemented. I reused some of chssbot’s code: the rendering and FEN to CHEQ_TT.TTF mapping.
- Finally, I wanted to do AI. The best Chess AI in javascript was stockfish.
-
Stockfish-js is an emscripten port of the stockfish chess engine. (Emscripten being a c[++] to javascript compiler.) This enables one to run one of the strongest chess engines available without downloads or plugins in a web browser
Unfortunately, Stockfish.js caused my NPM dev setup to crash every time I imported it, or <script> tagged it. The file was 1.12 MB in size due to the rulebook which came embedded in the JS file.
Stockfish-js is designed to run in a web-worker, which can be created like this:
var stockfish = new Worker('stockfish.js');
Input the current Board state (FEN):
sf.postMessage(position fen ${this.state.historicalStates[this.state.boardIndex]}
)
Input (standard UCI commands) to the engine is posted as a message to the worker:
{% highlight javascript %}
engine.postMessage('go depth 15'); // 15 is from 0-20 difficuilty levels?
{% endhighlight %}
The output of the engine is again posted as a message, to receive it you need to install an event handler:
{% highlight javascript %}
engine.onmessage = function(event) { //display the move from event.data };
{% endhighlight %}
The UI was done with the help of React Material-UI, which I used in many of my projects from then.
Try React-Chess now