r/learnprogramming • • 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:

https://github.com/Solar-Stacer/Chess

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 Upvotes

11 comments sorted by

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.

1

u/Voltrim 21d ago

Thanks! Well, I never knew that minimax is actually machine learning lol. I actualy do want to code the bot using minimax. I guess when I said, "AI-driven" I meant using neural networks like reinforcement learning where you use PyTorch and such. When I said "traditional", i meant minimax. Obviously, I have no clue about anything pertaining to AL/ML so please excuse my ineptitude.

However, how would I go about implementing the minimax algorithm tho? I do not want to use any libraries and Python is a slow language. Performance here is critical so how would I do this? Write my own C extension using C? Use Cython? I do use custom classes in my project, like ChessPieceClass and they have methods that needs to be accessed so interfacing custom classes to C does seem a little complicated.

1

u/PabloDons 21d ago

Depends what you're trying to do. If you're going for ML, then it doesn't matter. The minimax algorithm will be a tiny fraction of the runtime and optimizing it only gives you tiny marginal performance.

I wouldn't use C or Cython as extensions. You might as well rewrite your script to C at that point. Doing python extensions is really complex and it really is the most useless skill ever. Back when I was doing ML, I played with that same idea a lot, but ultimately I got more out of clever use of numpy than I did from using C or Cython. The trick is to replace loops with numpy

1

u/Voltrim 21d ago

The trick is to replace loops with numpy.

My board representation is a 2D list with references to custom classes. Changing them to numpy arrays would not work because NumPy is optimized for array computations with numbers as elements. How do you suggest to use numpy for this to work?

1

u/PabloDons 21d ago

Numpy is quite powerful, you'd be surprised. But your board pieces are already enum, numbers work just fine there. And there's a bunch of clever linear algebra you can employ.

But I'm not just talking about the board, I'm talking about the chess bot algorithm

1

u/Voltrim 21d ago

My board pieces are not enums tho. The ChessBoardClassheader is:

class ChessBoardClass(list[list[Piece | None]])

Noneindicates empty space. Piece is an alias for ChessPieceClass which is a custom base object where all the other pieces inherit from. To get all the legal moves for a piece, it needs to call the piece's getLegalPositionsInMatrix which calls other functions that are very specific to the piece.

I only use the ChessPieceTypeEnum for printing the matrix not for discerning the type of the piece. For that I use isinstance() function since every piece can be differentiated by class.

Minimax requires getting all the legal moves that a piece can make in a given board config, which means it requires calling getLegalPositionsInMatrix for every piece that it is evaluating. This is what makes this very complicated. Even when writing the bot in C, it requires interfacing with Python objects and calling the latter's methods.

1

u/PabloDons 18d ago

Gotcha, my bad, I missed that when skimming the code. But I don't recommend getting to deep into performance optimization anyways, it's a rabbit hole. A common mistake is premature optimization. You could end up spending many many hours doing something that will only give you fractional speedup. Just get your project over the finish line and look into making it better after you find out what exactly is holding it back

Anyways for getting legal positions, linear algebra really can solve it. With a few clever matrix multiplications, you can throw numpy at it and it'll be much faster. It's a daunting task if you've never done it before though so I understand if you'd rather focus on getting the project into a working state first.

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.