Chess with Random AI: Playing Against a Random Number Generator
Chess rule enforcement is somewhere around a thousand lines of edge cases. Castling rights. En passant. Pawn promotion. Stalemate detection. I did not want to write that code. I wanted a playable chess game with a GUI and an opponent, and python-chess gave me all the rules for free. The rest was wiring up tkinter and an AI whose strategic depth is a coin flip.
The Interface Takes Two Clicks
Click a piece to select it. Click a square to move it. The python-chess library validates legality, tracks castling and en passant rights, and detects checkmate. The canvas redraws by mapping every piece on the internal board to a PNG image. The coordinate system required one transformation: tkinter uses a top-left origin, chess uses bottom-left for rank one. A single 7-row subtraction handled it.
The graphics are minimal. Light green and light gray squares. A red border on the selected piece. No move highlights. No legal move indicators. No feedback for illegal clicks. The interface assumes you already know the rules.
The AI Decides by Coin Flip
The AI generates every legal move available to Black and picks one with random.choice. It does not evaluate position. It does not look ahead. It does not capture pieces when advantageous or avoid hanging its queen. It plays the same way a toddler would if the toddler knew the movement rules but nothing about strategy.
Games end quickly. Black blunders pieces on every turn. The only way to lose as White is to ignore the board entirely.
Random Positions Keep It Fresh
Every game starts with all thirty two pieces scattered randomly across the sixty four squares. Pawns on the back rank. Kings adjacent. Both sides in check simultaneously. The python-chess library accepts any valid board state, so the position works even if it violates every opening principle.
The randomization means no two games look the same, which masks how simple the AI actually is. Each game feels different because the context changed, not because the opponent got smarter.
There is no undo. No restart button. No move history. The winner label is centered red text that says "White Wins!" or "Black Wins!" and nothing else. It crashes if the images folder is missing. I did not handle that.
The library handled the complexity. I handled the interface and the randomness. That trade was worth one file and one evening.