Skip to content

← Back to Home

Game Engine

The core game engine that handles game logic, move validation, and the chess engine decision-making.

Related Components: Hardware Control | Vision System | Communication | UI

Overview

The Game Engine component is responsible for:

  • Game State Management - Maintaining board positions and game history
  • Move Validation - Ensuring all moves follow chess rules
  • Chess engine Decision Making - Generating computer player moves
  • Game Outcome Detection - Detecting checkmate, stalemate, and draw conditions
  • Choosing difficulty level - Easy, medium or hard

Module Documentation

Main Entry Point

The main application entry point that initializes the entire system.

Main entry point for CNChess application.Initializes game components including the chess engine, control system, camera, communication interface, and PyQt UI. Manages application lifecycle and cleanup.

Chess Game Engine

The core chess game logic and state management system. It uses python chess library and Stockfish chess engine at various difficulties.

CNChess

Source code in python/CNChess.py
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
class CNChess:

    board: chess.Board
    computer_color: chess.Color
    player_color: chess.Color
    next_computer_move: chess.Move
    next_player_move: chess.Move

    stockfish_path: str = "/usr/games/stockfish"  # Adjust path as necessary
    stockfish_depth: int = 10
    computer: stockfish.Stockfish

    def __init__(self):
        """Initialize CNChess game instance with board, colors, and difficulty settings.

        Args:
            None

        Return:
            None
        """
        self.board = chess.Board()
        self.computer_color = chess.BLACK
        self.player_color = chess.WHITE
        self.next_computer_move = None
        self.next_player_move = None
        self.computer = stockfish.Stockfish(path=self.stockfish_path, depth=self.stockfish_depth)
        self.MEDIUM_ELO = 1350
        self.MEDIUM_DEPTH = 1
        self.HARD_ELO = 2000
        self.HARD_DEPTH = 10
        self.IMPOSSIBLE_ELO = 3000
        self.IMPOSSIBLE_DEPTH = 20
        self.difficulty = "easy"
        self.time_control = 0  # None means no time limit, or time in minutes


    def set_elo(self, elo: int):
        """Set ELO rating for computer opponent.

        Args:
            elo (int): ELO rating value.

        Return:
            None
        """
        self.computer.set_elo_rating(elo)

    def set_depth(self, depth: int):
        """Set search depth for computer AI engine.

        Args:
            depth (int): Search depth value.

        Return:
            None
        """
        self.computer.set_depth(depth)

    def set_difficulty(self, difficulty: str):
        """Set the difficulty level of the computer opponent. Valid values are 'easy', 'medium', and 'hard'."""

        if difficulty not in ["easy", "medium", "hard", "impossible"]:
            raise ValueError("Invalid difficulty level. Must be 'easy', 'medium', 'hard', or 'impossible'.")
        self.difficulty = difficulty
        elo = self.MEDIUM_ELO if difficulty == "medium" else self.HARD_ELO if difficulty == "hard" else self.IMPOSSIBLE_ELO
        depth = self.MEDIUM_DEPTH if difficulty == "medium" else self.HARD_DEPTH if difficulty == "hard" else self.IMPOSSIBLE_DEPTH

        self.set_elo(elo)
        self.set_depth(depth)

    def get_time_control(self)-> int | None:
        """Return the current time control setting.

        Args:
            None

        Return:
            int | None: Time limit in minutes per player, or None if no time limit.
        """
        return self.time_control    

    def set_time_control(self, time_minutes: int | None):
        """Set the time control for the game.

        Args:
            time_minutes (int | None): Time limit in minutes per player, or None for no time limit.

        Return:
            None
        """
        self.time_control = time_minutes

    def set_player_color(self, color: chess.Color):
        """Set player color (WHITE/BLACK) and computer color as opposite.

        Args:
            color (chess.Color): Player's color (chess.WHITE or chess.BLACK).

        Return:
            None
        """
        self.player_color = color
        self.computer_color = not color

    def get_player_color(self):
        """Return the player's color.

        Args:
            None

        Return:
            chess.Color: Player's color (chess.WHITE or chess.BLACK).
        """
        return self.player_color

    def get_legal_moves_from_square(self, square):
        """Return list of legal moves from a given square.

        Args:
            square (str): Square in algebraic notation (e.g., 'e2').

        Return:
            list[chess.Move]: List of legal moves from the specified square.
        """
        square_index = chess.parse_square(square)
        legal_moves = [move for move in self.board.legal_moves if move.from_square == square_index]
        return legal_moves

    def set_player_move(self, move):
        """Store the next player move to be executed.

        Args:
            move (chess.Move): The move to store.

        Return:
            None
        """
        self.next_player_move = move

    def set_computer_move(self, move):
        """Store the next computer move to be executed.

        Args:
            move (chess.Move): The move to store.

        Return:
            None
        """
        self.next_computer_move = move

    def get_player_move(self):
        """Return stored player move.

        Args:
            None

        Return:
            chess.Move: Stored player move.
        """
        return self.next_player_move

    def get_computer_move(self):
        """Return stored computer move.

        Args:
            None

        Return:
            chess.Move: Stored computer move.
        """
        return self.next_computer_move

    def get_next_best_move(self):
        """Calculate and return the best move for computer based on difficulty level.

        Args:
            None

        Return:
            chess.Move: Best move for computer, or null move if none available.
        """
        self.computer.set_fen_position(self.board.fen())
        if self.difficulty == "easy":
            captured_moves = list(self.board.generate_legal_captures())
            if captured_moves:
                move = captured_moves[random.randrange(len(captured_moves))]
            else:
                legal_moves = list(self.board.generate_legal_moves())
                move = legal_moves[random.randrange(len(legal_moves))]
            return move
        else:
            best_move_uci = self.computer.get_best_move()
        if best_move_uci:
            return chess.Move.from_uci(best_move_uci)
        else:
            return chess.Move.null()    

    def check_game_outcome(self):
        """Check if game is over and return winner or draw status.

        Args:
            None

        Return:
            str: "white" or "black" for winner, "draw" for draw, None if game ongoing.
        """
        game_outcome = self.board.outcome()
        if game_outcome:
            if game_outcome.termination == Termination.CHECKMATE:
                winner_color = "white" if game_outcome.winner == chess.WHITE else "black"
                return winner_color
            else:
                return "draw"
        else:
            return None 
    def get_material_evaluation(self, color):
        """Calculate material score for a given color based on pieces on board.

        Args:
            color (chess.Color): Color to evaluate (chess.WHITE or chess.BLACK).

        Return:
            int: Material evaluation score.
        """
        piece_values = {
            chess.PAWN: 1,
            chess.KNIGHT: 3,
            chess.BISHOP: 3,
            chess.ROOK: 5,
            chess.QUEEN: 9,
            chess.KING: 0
        }
        evaluation = 0
        for piece, value in piece_values.items():
            pieces = self.board.pieces(piece, color)
            evaluation += len(pieces) * value
        return evaluation      

    def make_move(self, move):
        """Execute a move on the board.

        Args:
            move (chess.Move): Move to execute.

        Return:
            None
        """
        self.board.push(move)    

    def get_board_state(self):
        """Return FEN string representation of current board state.

        Args:
            None

        Return:
            str: FEN notation of board state.
        """
        return self.board.fen()

    def validate_move(self, move):
        """Check if a move is legal in current board position.

        Args:
            move (chess.Move): Move to validate.

        Return:
            bool: True if move is legal, False otherwise.
        """
        return self.board.is_legal(move)

    def check_game_over(self):
        """Check if game is over (checkmate, stalemate, or insufficient material).

        Args:
            None

        Return:
            bool: True if game is over, False otherwise.
        """
        return self.board.is_game_over()

    def reset_game(self):
        """Reset board to starting position.

        Args:
            None

        Return:
            None
        """
        print("Resetting the game...")
        self.board.reset()

    def get_turn(self):
        """Return whose turn it is to move.

        Args:
            None

        Return:
            str: "white" or "black" indicating current turn.
        """
        turn = self.board.turn
        return "white" if turn == chess.WHITE else "black"

    def get_board(self):
        """Return the chess.Board object.

        Args:
            None

        Return:
            chess.Board: Current chess board instance.
        """
        return self.board

    def is_promotion_move(self, move):
        """Determine if a move is a pawn promotion.

        Args:
            move (chess.Move): Move to check.

        Return:
            bool: True if move is a pawn promotion, False otherwise.
        """
        white_promotion = (chess.square_rank(move.to_square) == 7 and
                          chess.square_rank(move.from_square) == 6 and
                          self.board.piece_at(move.from_square).piece_type == chess.PAWN and
                          self.board.piece_at(move.from_square).color == chess.WHITE)
        black_promotion = (chess.square_rank(move.to_square) == 0 and
                          chess.square_rank(move.from_square) == 1 and
                          self.board.piece_at(move.from_square).piece_type == chess.PAWN and
                          self.board.piece_at(move.from_square).color == chess.BLACK)
        return white_promotion or black_promotion            

__init__()

Initialize CNChess game instance with board, colors, and difficulty settings.

Return

None

Source code in python/CNChess.py
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
def __init__(self):
    """Initialize CNChess game instance with board, colors, and difficulty settings.

    Args:
        None

    Return:
        None
    """
    self.board = chess.Board()
    self.computer_color = chess.BLACK
    self.player_color = chess.WHITE
    self.next_computer_move = None
    self.next_player_move = None
    self.computer = stockfish.Stockfish(path=self.stockfish_path, depth=self.stockfish_depth)
    self.MEDIUM_ELO = 1350
    self.MEDIUM_DEPTH = 1
    self.HARD_ELO = 2000
    self.HARD_DEPTH = 10
    self.IMPOSSIBLE_ELO = 3000
    self.IMPOSSIBLE_DEPTH = 20
    self.difficulty = "easy"
    self.time_control = 0  # None means no time limit, or time in minutes

check_game_outcome()

Check if game is over and return winner or draw status.

Return

str: "white" or "black" for winner, "draw" for draw, None if game ongoing.

Source code in python/CNChess.py
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
def check_game_outcome(self):
    """Check if game is over and return winner or draw status.

    Args:
        None

    Return:
        str: "white" or "black" for winner, "draw" for draw, None if game ongoing.
    """
    game_outcome = self.board.outcome()
    if game_outcome:
        if game_outcome.termination == Termination.CHECKMATE:
            winner_color = "white" if game_outcome.winner == chess.WHITE else "black"
            return winner_color
        else:
            return "draw"
    else:
        return None 

check_game_over()

Check if game is over (checkmate, stalemate, or insufficient material).

Return

bool: True if game is over, False otherwise.

Source code in python/CNChess.py
279
280
281
282
283
284
285
286
287
288
def check_game_over(self):
    """Check if game is over (checkmate, stalemate, or insufficient material).

    Args:
        None

    Return:
        bool: True if game is over, False otherwise.
    """
    return self.board.is_game_over()

get_board()

Return the chess.Board object.

Return

chess.Board: Current chess board instance.

Source code in python/CNChess.py
314
315
316
317
318
319
320
321
322
323
def get_board(self):
    """Return the chess.Board object.

    Args:
        None

    Return:
        chess.Board: Current chess board instance.
    """
    return self.board

get_board_state()

Return FEN string representation of current board state.

Return

str: FEN notation of board state.

Source code in python/CNChess.py
257
258
259
260
261
262
263
264
265
266
def get_board_state(self):
    """Return FEN string representation of current board state.

    Args:
        None

    Return:
        str: FEN notation of board state.
    """
    return self.board.fen()

get_computer_move()

Return stored computer move.

Return

chess.Move: Stored computer move.

Source code in python/CNChess.py
169
170
171
172
173
174
175
176
177
178
def get_computer_move(self):
    """Return stored computer move.

    Args:
        None

    Return:
        chess.Move: Stored computer move.
    """
    return self.next_computer_move

Return list of legal moves from a given square.

Parameters:

Name Type Description Default
square str

Square in algebraic notation (e.g., 'e2').

required
Return

list[chess.Move]: List of legal moves from the specified square.

Source code in python/CNChess.py
123
124
125
126
127
128
129
130
131
132
133
134
def get_legal_moves_from_square(self, square):
    """Return list of legal moves from a given square.

    Args:
        square (str): Square in algebraic notation (e.g., 'e2').

    Return:
        list[chess.Move]: List of legal moves from the specified square.
    """
    square_index = chess.parse_square(square)
    legal_moves = [move for move in self.board.legal_moves if move.from_square == square_index]
    return legal_moves

get_material_evaluation(color)

Calculate material score for a given color based on pieces on board.

Parameters:

Name Type Description Default
color Color

Color to evaluate (chess.WHITE or chess.BLACK).

required
Return

int: Material evaluation score.

Source code in python/CNChess.py
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
def get_material_evaluation(self, color):
    """Calculate material score for a given color based on pieces on board.

    Args:
        color (chess.Color): Color to evaluate (chess.WHITE or chess.BLACK).

    Return:
        int: Material evaluation score.
    """
    piece_values = {
        chess.PAWN: 1,
        chess.KNIGHT: 3,
        chess.BISHOP: 3,
        chess.ROOK: 5,
        chess.QUEEN: 9,
        chess.KING: 0
    }
    evaluation = 0
    for piece, value in piece_values.items():
        pieces = self.board.pieces(piece, color)
        evaluation += len(pieces) * value
    return evaluation      

get_next_best_move()

Calculate and return the best move for computer based on difficulty level.

Return

chess.Move: Best move for computer, or null move if none available.

Source code in python/CNChess.py
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
def get_next_best_move(self):
    """Calculate and return the best move for computer based on difficulty level.

    Args:
        None

    Return:
        chess.Move: Best move for computer, or null move if none available.
    """
    self.computer.set_fen_position(self.board.fen())
    if self.difficulty == "easy":
        captured_moves = list(self.board.generate_legal_captures())
        if captured_moves:
            move = captured_moves[random.randrange(len(captured_moves))]
        else:
            legal_moves = list(self.board.generate_legal_moves())
            move = legal_moves[random.randrange(len(legal_moves))]
        return move
    else:
        best_move_uci = self.computer.get_best_move()
    if best_move_uci:
        return chess.Move.from_uci(best_move_uci)
    else:
        return chess.Move.null()    

get_player_color()

Return the player's color.

Return

chess.Color: Player's color (chess.WHITE or chess.BLACK).

Source code in python/CNChess.py
112
113
114
115
116
117
118
119
120
121
def get_player_color(self):
    """Return the player's color.

    Args:
        None

    Return:
        chess.Color: Player's color (chess.WHITE or chess.BLACK).
    """
    return self.player_color

get_player_move()

Return stored player move.

Return

chess.Move: Stored player move.

Source code in python/CNChess.py
158
159
160
161
162
163
164
165
166
167
def get_player_move(self):
    """Return stored player move.

    Args:
        None

    Return:
        chess.Move: Stored player move.
    """
    return self.next_player_move

get_time_control()

Return the current time control setting.

Return

int | None: Time limit in minutes per player, or None if no time limit.

Source code in python/CNChess.py
78
79
80
81
82
83
84
85
86
87
def get_time_control(self)-> int | None:
    """Return the current time control setting.

    Args:
        None

    Return:
        int | None: Time limit in minutes per player, or None if no time limit.
    """
    return self.time_control    

get_turn()

Return whose turn it is to move.

Return

str: "white" or "black" indicating current turn.

Source code in python/CNChess.py
302
303
304
305
306
307
308
309
310
311
312
def get_turn(self):
    """Return whose turn it is to move.

    Args:
        None

    Return:
        str: "white" or "black" indicating current turn.
    """
    turn = self.board.turn
    return "white" if turn == chess.WHITE else "black"

is_promotion_move(move)

Determine if a move is a pawn promotion.

Parameters:

Name Type Description Default
move Move

Move to check.

required
Return

bool: True if move is a pawn promotion, False otherwise.

Source code in python/CNChess.py
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
def is_promotion_move(self, move):
    """Determine if a move is a pawn promotion.

    Args:
        move (chess.Move): Move to check.

    Return:
        bool: True if move is a pawn promotion, False otherwise.
    """
    white_promotion = (chess.square_rank(move.to_square) == 7 and
                      chess.square_rank(move.from_square) == 6 and
                      self.board.piece_at(move.from_square).piece_type == chess.PAWN and
                      self.board.piece_at(move.from_square).color == chess.WHITE)
    black_promotion = (chess.square_rank(move.to_square) == 0 and
                      chess.square_rank(move.from_square) == 1 and
                      self.board.piece_at(move.from_square).piece_type == chess.PAWN and
                      self.board.piece_at(move.from_square).color == chess.BLACK)
    return white_promotion or black_promotion            

make_move(move)

Execute a move on the board.

Parameters:

Name Type Description Default
move Move

Move to execute.

required
Return

None

Source code in python/CNChess.py
246
247
248
249
250
251
252
253
254
255
def make_move(self, move):
    """Execute a move on the board.

    Args:
        move (chess.Move): Move to execute.

    Return:
        None
    """
    self.board.push(move)    

reset_game()

Reset board to starting position.

Return

None

Source code in python/CNChess.py
290
291
292
293
294
295
296
297
298
299
300
def reset_game(self):
    """Reset board to starting position.

    Args:
        None

    Return:
        None
    """
    print("Resetting the game...")
    self.board.reset()

set_computer_move(move)

Store the next computer move to be executed.

Parameters:

Name Type Description Default
move Move

The move to store.

required
Return

None

Source code in python/CNChess.py
147
148
149
150
151
152
153
154
155
156
def set_computer_move(self, move):
    """Store the next computer move to be executed.

    Args:
        move (chess.Move): The move to store.

    Return:
        None
    """
    self.next_computer_move = move

set_depth(depth)

Set search depth for computer AI engine.

Parameters:

Name Type Description Default
depth int

Search depth value.

required
Return

None

Source code in python/CNChess.py
55
56
57
58
59
60
61
62
63
64
def set_depth(self, depth: int):
    """Set search depth for computer AI engine.

    Args:
        depth (int): Search depth value.

    Return:
        None
    """
    self.computer.set_depth(depth)

set_difficulty(difficulty)

Set the difficulty level of the computer opponent. Valid values are 'easy', 'medium', and 'hard'.

Source code in python/CNChess.py
66
67
68
69
70
71
72
73
74
75
76
def set_difficulty(self, difficulty: str):
    """Set the difficulty level of the computer opponent. Valid values are 'easy', 'medium', and 'hard'."""

    if difficulty not in ["easy", "medium", "hard", "impossible"]:
        raise ValueError("Invalid difficulty level. Must be 'easy', 'medium', 'hard', or 'impossible'.")
    self.difficulty = difficulty
    elo = self.MEDIUM_ELO if difficulty == "medium" else self.HARD_ELO if difficulty == "hard" else self.IMPOSSIBLE_ELO
    depth = self.MEDIUM_DEPTH if difficulty == "medium" else self.HARD_DEPTH if difficulty == "hard" else self.IMPOSSIBLE_DEPTH

    self.set_elo(elo)
    self.set_depth(depth)

set_elo(elo)

Set ELO rating for computer opponent.

Parameters:

Name Type Description Default
elo int

ELO rating value.

required
Return

None

Source code in python/CNChess.py
44
45
46
47
48
49
50
51
52
53
def set_elo(self, elo: int):
    """Set ELO rating for computer opponent.

    Args:
        elo (int): ELO rating value.

    Return:
        None
    """
    self.computer.set_elo_rating(elo)

set_player_color(color)

Set player color (WHITE/BLACK) and computer color as opposite.

Parameters:

Name Type Description Default
color Color

Player's color (chess.WHITE or chess.BLACK).

required
Return

None

Source code in python/CNChess.py
100
101
102
103
104
105
106
107
108
109
110
def set_player_color(self, color: chess.Color):
    """Set player color (WHITE/BLACK) and computer color as opposite.

    Args:
        color (chess.Color): Player's color (chess.WHITE or chess.BLACK).

    Return:
        None
    """
    self.player_color = color
    self.computer_color = not color

set_player_move(move)

Store the next player move to be executed.

Parameters:

Name Type Description Default
move Move

The move to store.

required
Return

None

Source code in python/CNChess.py
136
137
138
139
140
141
142
143
144
145
def set_player_move(self, move):
    """Store the next player move to be executed.

    Args:
        move (chess.Move): The move to store.

    Return:
        None
    """
    self.next_player_move = move

set_time_control(time_minutes)

Set the time control for the game.

Parameters:

Name Type Description Default
time_minutes int | None

Time limit in minutes per player, or None for no time limit.

required
Return

None

Source code in python/CNChess.py
89
90
91
92
93
94
95
96
97
98
def set_time_control(self, time_minutes: int | None):
    """Set the time control for the game.

    Args:
        time_minutes (int | None): Time limit in minutes per player, or None for no time limit.

    Return:
        None
    """
    self.time_control = time_minutes

validate_move(move)

Check if a move is legal in current board position.

Parameters:

Name Type Description Default
move Move

Move to validate.

required
Return

bool: True if move is legal, False otherwise.

Source code in python/CNChess.py
268
269
270
271
272
273
274
275
276
277
def validate_move(self, move):
    """Check if a move is legal in current board position.

    Args:
        move (chess.Move): Move to validate.

    Return:
        bool: True if move is legal, False otherwise.
    """
    return self.board.is_legal(move)

Key Features

  • FEN Support - Full Forsyth-Edwards Notation support for board representation
  • Move Legality - Complete validation of chess move rules
  • Game History - Track all moves with ability to undo/redo
  • Chess engine Opponent - Computer player with configurable difficulty (easy, medium or hard)
  • Promotion Handling - Automatic pawn promotion on reach of last rank
  • Check/Checkmate Detection - Real-time detection of game-ending conditions

Architecture

Game Engine
├── Board State (FEN)
├── Move Validation
│   ├── Legal Moves Generator
│   ├── Rule Enforcement
│   └── Special Moves (Castling, En Passant, Promotion)
├── Chess Engine Decision Making
└── Game Outcome
    ├── Checkmate Detection
    └── Draw Detection

Usage Example

from CNChess import CNChess

# Initialize the game
chess_game = CNChess()

# Get current board state
board_state = chess_game.get_board_state()

# Get legal moves for a piece
legal_moves = chess_game.get_legal_moves_from_square('e2')

# Validate and make a move
move = chess.Move.from_uci('e2e4')
if chess_game.validate_move(move):
    chess_game.make_move(move)

# Get chess engine move
best_move = chess_game.get_next_best_move()

Dependencies

  • chess - Python chess library for game logic
  • Python 3.8+ - Core language