r/learnprogramming • u/Voltrim • 24d ago
A Chess Program In Python using PySide6 (Qt for Python).
I made two-player (without Bot) Chess in Python using the Python bindings for Qt called PySide6. The program takes checks into account, including castling, pawn promotions and En Passant moves as well as whether the board is in Checkmate state or Stalemate state.
Here is the Github Repo for it:
I recently wanted to extend this program by adding a Chess bot using traditional approaches such as minimax, not AI-driven ones. I would love any advice regarding whether it is possible to do so with the current structure of the code and if not, then any changes needed to enable or facilitate the process.
Additionally, since Python is slow, any advice regarding writing the performance critical parts of the chess bot in C or PyPy would be appreciated.
Thanks!
3
u/PabloDons 24d ago
The current structure seems to make it pretty easy. Your chesspieces class already has ways to check every legal move, keeps board state and has a method for making a move. You are having the gui call these methods and you can just make the bot call them too. Piece of cake.
I'm not really sure what you mean by not AI-driven though. With minimax, you need to score an outcome and you can only work with some maximum depth. Chess logically only has 3 possible outcomes of a game: 1, 0, -1. But you have to play out the entire game before getting a score. You can try encode chess theory into logic using raw python I guess. That's the only thing I can think of. Maybe taking pieces gives you score to begin with. Your chess bot would be quite terrible though.
Chess AI has always been a machine learning algorithm, typically deep neutral networks for the best performing ones like fish and alphachess. These take board state and predict the score that minimax runs on top of. DNNs perform really well in Python so you don't have to do much except have some VRAM to work with.
2
u/MultiUserDungeonDev 24d ago
Cool! Stared
1
u/[deleted] 22d ago
https://chessprogramming.org/
https://www.gnu.org/software/chess/
I don't mean to hurt, but the UI is the easy part. The interesting and difficult part is the chess engine: evaluation function, minimax, alpha-beta pruning... You will also have to deal with databases of openings and endgames.
I had a Java project back in university, but it was with Hex game, much easier (though still tricky to do well).
Oh, by the way, that's right, you will need C or C++ for the engine. The simplest is to write the engine as a separate program, and connect to it with the UI. The the UI could as well be a web app.
1
u/LochsideArb 5d ago
Python's GIL makes single-threaded CPU heavy tasks like minimax slow regardless of numpy. If you want real speedups, use multiprocessing to bypass the GIL or write the evaluation function in C.