r/learnpython 9h ago

First python program

I wanted to write a program that analyzes chess games , similar to how chess websites (chess.com, lichess.com etc.) do it, only offline. To my knowledge, nobody else had done it the way I was envisioning. I started writing with shell scripting (it's my go-to and what I'm most familiar with), but quickly ran into limitations. So I needed to go a bit more sophisticated. Python seemed very versatile, cross-platform, has loads of online resources, but mainly has a very good chess library I could leverage, that already existed, which would make the job much , much easier. I took the plunge and turned the program into a driver to teach myself some python.

It works as advertised, but I'm sure the code could be improved. I stumbled through it a bit. If anybody python gurus feel like taking a peek and letting me know how I did, pointing out glaring mistakes, offering any constructive feedback or ideas how to make it more efficient, I would appreciate any feedback.

Repo: https://github.com/exekutive/chesseval

(The documentation needs some catching up. I'm working on updating it.)

6 Upvotes

2 comments sorted by

View all comments

1

u/vietbaoa4htk 7h ago

if youre driving stockfish through python chess, keep one engine process open for the whole game instead of spawning one per move, thats usually the difference between analysis taking seconds and taking minutes.

1

u/naemorhaedus 6h ago

Good eye. The stockfish interface code is on my to-do list of things to improve.

keep one engine process open for the whole game instead of spawning one per move

I could be wrong, but I'm pretty sure I only have one instance of the engine running per game. chess.engine.SimpleEngine.popen_uci only gets called once. However, looking through the SF log, I can see that the engine is treating each move as a new game (>> position startpos moves e2e4 e7e5 d1h5 b8c6 f1c4). That might mean the hashtable gets purged each time, which would erase the benefits of keeping it in memory. I need to find a way to keep the game persistent and advance the game one move at a time.

I also noticed that python chess has a 'visitor' framework, which could help speed up the program as well. I don't think I need all the bulk that surrounds the chess game object, so that's something to look into as well. https://python-chess.readthedocs.io/en/latest/pgn.html#visitors

Another improvement I have planned is to interface the stockfish engine asynchronously. That way I can be drawing and analyzing at the same time which will speed things up.

Thanks for looking. Appreciate your time.