12 ms·
Building My Own Chess Engine
- segmondy 6y agoI started writing my own chess engine after watching the Queen Gambit and missing chess. I realized I never wrote an engine, have you tried seeing how strong yours is?
- gogopuppygogo 6y agoDepending on your goals, it might be helpful to know that Apple has open sourced their Chess game (under a restrictive license): https://opensource.apple.com/source/Chess/ https://opensource.apple.com/source/Chess/
- Austin_Conlon 6y ago"TODO Nothing. This thing is getting messier, buggier, slower and less maintainable with each release. Time to move on." https://opensource.apple.com/source/Chess/Chess-321/sjeng/TODO.auto.html https://opensource.apple.com/source/Chess/Chess-321/sjeng/TO...
- rav 6y agoThat note is not from Chess.app, but from "Sjeng", a 3rd party dependency vendored into Apple's Chess.app. That notice has been there in all the versions of Chess that are available (from Chess-2.0 to Chess-347). See: https://en.wikipedia.org/wiki/Sjeng_(software) https://en.wikipedia.org/wiki/Sjeng_(software)
- senthilnayagam 6y agoI have couple of half built chess projects, you inspire me to complete them https://github.com/FossterCare/flask-pgn-api https://github.com/FossterCare/flask-pgn-api takes a single PGN file and converts it into MP4 via flask api another idea which I am working on, storing chess games in neo4j as graph data
- zone411 6y ago"Claude Shannon calculated that there are around 10^120 possible games of chess in his seminal paper Programming a Computer for Playing Chess in 1950." I've just finished a weekend project to calculate the number of legal chess positions and there are about 8.8E+45: https://github.com/lechmazur/ChessCounter https://github.com/lechmazur/ChessCounter. For people considering making a chess program, take a look at this message board http://talkchess.com/forum3/index.php http://talkchess.com/forum3/index.php. As the author mentions, python-chess is really nice. The project maintainers are very responsive - a bug I found was fixed within a day.
- ajkjk 6y agoAn engine with a high search depth makes great moves most of the time, but one with a low search depth makes really weirdly bad moves because it misses trivial combinations that go a bit deeper than it looks. So low-difficulty chess programs tend to be very unsatisfying to play against. Something I have always been interested in trying is writing a chess engine that makes human-like moves. So the evaluation function would try to emulate what a human would do, maybe with a few depths of evaluation, instead of playing accurate moves that never miss simple combinations.
- j4yav 6y agoThis is what Maia chess does.
- GreedCtrl 6y agoLink for those that are curious: https://maiachess.com/ https://maiachess.com/ (It got posted on HN too, but I didn't see it get much traction). And you can challenge the bot on lichess: https://lichess.org/@/maia1 https://lichess.org/@/maia1
- ajkjk 6y agoOh, that's awesome. Exactly what I was thinking of.
- PaulJulius 6y agoI've always wanted to do something similar! I've thought about trying to consider the "obviousness" of certain moves, and then only explore those branches with a probability relative to its obviousness. "Obviousness" would take into account things like the last move played ("ah, your pawn is attacking my bishop; I should move it"), and whether the move is a capture, check, or attacks another piece. A forward move for a knight is more obvious than a backward move, as is moving it towards the center of the board, versus moving it to the edge of board. As the depth increases, the probability of exploring a branch decreases. I think it would be pretty easy to scale such a system to make it play better or worse by simply adjusting how much the probability of exploring a branch decreases as the depth increases. Perhaps this could lead to more natural blunders where a line is simply missed? I've also wanted to come up with an evaluation system that scales better with skill level. A position may be +3, but only if you play the next 5 moves exactly correctly. In another position, one move might be +1, and another might be +0.5, but the +0.5 requires four moves of perfect play from your opponent to keep it even. Can these subtleties be expressed clearly? Maybe something like "turns until positional advantage is converted to a clear material advantage." When you're just starting engine evaluations often don't make any sense. I've watched a lot of chess on Twitch lately, and it'd also be cool to have scores for all the relatively-subjective terms that the commentators use: "lots of attacking chances" (just pure count of checks possible in next N moves? percentage of lines that lead to checkmate in next N moves?), "very sharp position" (how many moves drastically change the evaluation?), etc.
- pk2200 6y agoThere was a recent thread about challenging projects every programmer should try, and I think writing a chess engine would be a nice addition to that list. Chess programming is a refreshing change from modern software development, because you don't need any complicated frameworks or libraries, just a basic grasp of the minimax algorithm for searching a game tree. I have fond memories of writing an engine as a fresh college grad - it was my first "big" project and I made every mistake imaginable, but it was great fun and sharpened my coding skills immensely. It's exhilarating to play against your own program and then try to improve it. Highly recommended!
- rgossiaux 6y agoYou could expand this category to an AI for a number of similar games (like checkers and reversi) as well. I've written a double dummy solver for bridge--a program that computes the optimal result of the play of a bridge hand--as a side project and I think it's also a very good choice. A lot of the same tools as chess engine development apply: alpha-beta and the myriad variant search algorithms like MTD(f), transposition tables, heuristics like the killer move heuristic or the countermove heuristic. But you also need to apply some domain specific heuristics and tools, and since the whole thing is performance critical you need to worry about low level optimizations and good multithreading. In the bridge case it's not at all trivial to get something that can even finish at all in a reasonable timespan.
- mxcrossb 6y agoI wrote a chess program in college, and agree that it was fun. But isn’t the whole exercise a bit outdated? Building a chess program now surely would start with deep learning
- alpaca128 6y agoFor me personally such projects are also about having fun, and I just like implementing some of those elegant algorithms and maybe understand them at a deeper level. I don't enjoy pushing data through some intangible neural network and tweaking it nearly as much. Especially if it involves reading through the documentation of some library and the coding is just the boilerplate required to shovel data in. That said, everyone has their own preferences and as long as you are motivated to spend a long time with it you can learn something from it, even if the improvement isn't noticeable immediately.
- cepth 6y agoI have to commend the author for taking on a beast of a task. It's not easy to be learning/relearning chess while also trying to program an engine! I think programming a chess engine that can beat most club players (let's say sub-2000 rating) is not too hard. At that level, human players will make inaccurate moves (as well as blunders at lower ratings). It is however much harder to develop engines that are competing at GM level (~2500+). This wiki has some good high level articles (https://www.chessprogramming.org/Main_Page https://www.chessprogramming.org/Main_Page). Even something like a chess bitboard representation is non-trivial to code. Implementing minimax and comparable algorithms may be straightforward, but the actual evaluation of positions for traditional engines is a distillation of thousands of pieces of expert knowledge. See for example the parameters that can be tweaked in Fritz (http://help.chessbase.com/Fritz/16/Eng/index.html?000038.htm http://help.chessbase.com/Fritz/16/Eng/index.html?000038.htm). If you look at the history of chess engines (https://www.youtube.com/watch?v=wljgxS7tZVE https://www.youtube.com/watch?v=wljgxS7tZVE), by the 1990s and later most of the top chess engines have had masters, international masters, and grandmasters intimately involved with development. For example, Deep Blue had several consulting grandmasters. Rybka (the world's best engine 2007-2010) had IM Vasik Rajlich as primary author and GM Larry Kaufman closely involved with tweaking its evaluation functions. Kaufman also went on to write the (still) very strong engine Komodo (https://ccrl.chessdom.com/ccrl/4040/ https://ccrl.chessdom.com/ccrl/4040/). Traditional chess engines used to have glaring weaknesses like playing poorly in closed positions, being poor at avoiding disadvantageous endgames, etc. By the mid-2000s many of these weaknesses disappeared, but as recently as Fritz 9 there were well known opening sequences where engines could be tricked into playing losing lines.
- jacquesm 6y agoBefore you start writing a whole chess engine I'd suggest you code up a couple of end-game combinations that are known wins so that you get a good idea of what works and what doesn't for data structures and such. Once you can win king, knight, bishop against king reliably you're ready for tougher stuff. Some notes from past efforts: - A simpler but much faster engine will beat a more complex engine any time because the advantage of another ply easily outweighs the advantage of some clever algo. - A 10x10 board with an unreachable edge has some advantages when laid out as a linear array because it allows for much easier memory management (premature optimizations and all that...). On an 8x8 board laid out linearly the edges have no way of limiting piece movement but on a 10x10 you get that for free by putting an 'impossible' value in the unreachable edge fields. Even a knight won't be able to jump that effectively two field wide edge. This turns all legal moves for all pieces into a simple offset rather than a two dimensional affair. - Optimization of engine code is much harder than optimization of the yield function. - It is much better to not generate 'bad' moves than it is to prune them away after a lot of extra work has been done. Colin Wrights' law: 'You can't make computers faster, you can only make them do less work' clearly applies here. - memoization can bring insane speed gains. Good luck!
- computerphage 6y ago- A simpler but much faster engine will beat a more complex engine any time because the advantage of another ply easily outweighs the advantage of some clever algo. Tell that to AlphaZero
- jacquesm 6y agoThere is a bit of a difference between the likes of AlphaZero and what your average hobbyist programmer is going to cook up. Once your toolbox includes bits like 'custom hardware' the equations change. Also: that was still a wicked fast machine in terms of the number of positions evaluated by any normal standard.
- computerphage 6y agoCertainly AlphaZero was run on very fast hardware and lots of it. Nevertheless, I think it shows that the days of "speed is all that matters" is over. It did substantially fewer evals than stockfish and still crushed it. LC0 is the same way. Neural network chess proved that a higher quality, much more expensive, eval (with a very high quantity baseline, to be sure) is a viable strategy for a chess engine.
- nineteen999 6y agoI once wrote a "chess engine" when I was much younger, however as I'm not much of a chess player, it wasn't very good. I encoded all the movement rules for each piece and then programmed the opponent to choose random valid moves. It would pick a random piece, pick a random square to move it to, and if it was considered valid, it would make the move, or pick another square. I think later I reprogrammed it to select 10 random valid moves, and select the one that allowed it to capture the highest value piece. The great thing was that it worked, and it could "play chess". The sad thing was, I am such a bad chess player that it could still actually beat me around 50% of the time by choosing random moves.
- glouwbug 6y agoWhat's funny is that my strategy for chess is randomly moving pieces as well, given I play a little defense when things get close with the queen or rooks.
- jsnell 6y agoThere are much worse strategies in the game than "random". You might find this article amusing: http://tom7.org/chess/weak.pdf http://tom7.org/chess/weak.pdf
- mormegil 6y agoThere is a funny chess variant on F-Droid called Open Chaos Chess <https://github.com/CorruptedArk/open-chaos-chess https://github.com/CorruptedArk/open-chaos-chess> where the players choose what piece should be played but the move is chosen randomly. The first player to lose all pieces loses the game (there are no checks and mates).
- dsteinman 6y agoI wrote a chess game using StockFish, and had it play against another computer player that only made random choices. And what surprised me is how long it would take StockFish to beat the random player.
- thomasahle 6y agoFor people who'd like the joy of seeing their hobby engine face real people, Lichess has a nice system for verified bot accounts: https://lichess.org/team/lichess-bots https://lichess.org/team/lichess-bots I'm personally running bits for sunfish https://github.com/thomasahle/sunfish https://github.com/thomasahle/sunfish and fastchess https://github.com/thomasahle/fastchess https://github.com/thomasahle/fastchess There are way too many stockfish clones on there. I hope more hobby chess engine builders will join in.
- nullsense 6y agoSomeone needs to do one in brainfuck and call it Fuckfish
- healeycodes 6y ago(Author here) I also hope more hobby chess engine builders join the fun on lichess! I recommend playing against https://lichess.org/@/TuroBot https://lichess.org/@/TuroBot which is based on Alan Turing's https://en.wikipedia.org/wiki/Turochamp https://en.wikipedia.org/wiki/Turochamp I debugged my bot by playing it on lichess since I'm so used to the UI/analysis tools.
- toolslive 6y agoThe piece values are quite interesting, N=320, B=330 for example is a good heuristic to compensate lack of better knowledge. However be aware that there are contradictions: B > N, but. Q + B < Q + N Queens just work better with knights.
- Oreb 6y agoFor what it’s worth, John Watson, in his book Modern Chess Strategy, lists the Q+N > Q+B thing as a belief that used to be common in the past, but is proven wrong by modern practice. I’m not nearly strong enough to have an opinion on the matter myself.
- heroku 6y agoI want to write a chess engine without using a search tree. Teaching the computer to look for tactics and specific patterns. I don't expect a super engine, but a decently good engine. Plus it would also be able to comment on the position, telling the tactics it sees. Is this possible?
- unnouinceput 6y agoAbsolutely. Just make a neuronal network that know chess moves and let it play against itself. After ~2 trillion games should be quite trained and will kick anybody's ass. Sure, you'd be long dead by then but that was not your question, yes?
- lixtra 6y agoRaise a child, teach it chess early and hope for the best. It could be ready in 15 years.
- healeycodes 6y agoIt wouldn’t be very strong but you could use the evaluation rules that are used for move ordering (the ones that don’t require prior searching) https://www.chessprogramming.org/Move_Ordering https://www.chessprogramming.org/Move_Ordering
- ludocode 6y agoI wrote a toy chess engine a few weeks ago as well as an example for one of my open source libraries [1]. I was inspired by a video of someone writing one in half an hour [2], so I also assumed it would take a day or two at most. It took more like a week. But it was very satisfying to not be able to beat my engine anymore. I highly recommend that all programmers with even a passing interest in chess spend some time writing an engine. [1] https://github.com/ludocode/pottery/tree/master/examples/pottery/clayfish https://github.com/ludocode/pottery/tree/master/examples/pot... [2] https://youtube.com/watch?v=nzObJ2BpKrk https://youtube.com/watch?v=nzObJ2BpKrk
- bluedino 6y agoOne of the first books I read about BASIC had a checkers game in it. The whole point of the game was to show how recursive algorithms worked (that was the AI, I don't remember any more details on it). One of the exercises at the end of the chapter was, "Improve the checkers program to play chess" Not sure if the author was kidding or not. I don't remember any strong BASIC chess engines, but there were quite a few 8-bit engines that were fairly decent in those days.
- thom 6y agoI’ve said a few times on here that I think studying chess engines is about the best computer science education you could get from a single hobby. Definitely worth trying, and evolving from simple methods to more advanced over time. I do think there’s also a big gap in the market for chess _tooling_ that makes learning and match prep easier. I actually think simpler more interpretable engines can be more useful as tools for humans in many cases. For example instead of increasingly inscrutable neural networks, or explanations of moves that are merely “after 10 moves this happens and it’s bad”, even a simple regression over some human interpretable features can give you an idea why the engine is suggesting a positional move (king safety, piece activity etc). I also think just pure stats and algorithmic stuff would be useful, like finding transpositions between openings, trying to work out what kinds of middle game structures or endgames a player is good or bad at, and navigating a path towards that in your preparation.
- pgt 6y ago15 years ago I made a simple alpha-beta minimax chess engine for a high school Java project. 10 years later it was used in a Minecraft mod called MineChess: https://github.com/theronic/chessmate https://github.com/theronic/chessmate The Internet is wild.
- viseztrance 6y ago>> There are more possible chess games than the number of atoms in the universe. >> This program throws a RecursionError and prints 59691 — the number of different positions the search tree contained when it crashed. All we need to fix this, is another universe to run the program in. To be fair, the recursion limit is not the same thing as running out of memory. You can use a loop to have your program run further than this.
- primitivesuave 6y agoThanks for writing this, I'm sketching out a chess engine for playing the Horde chess variant (https://lichess.org/variant/horde https://lichess.org/variant/horde) and studying the variant more deeply. Standard Stockfish is pretty bad at playing this variant for both white and black, and can be defeated by most competent humans. Great link at the bottom as well for anyone interested in chess programming (https://www.chessprogramming.org/Main_Page https://www.chessprogramming.org/Main_Page)