Skip to content

← Back to Home

User Interface

PyQt6-based graphical interface for game interaction and configuration.

Related Components: Game Engine | Hardware Control | Vision System | Communication

Overview

The User Interface component is responsible for:

  • Game Visualization - Display board state and piece positions
  • User Interaction - Handle move input and game control
  • Settings Management - Configure system parameters
  • Visual Feedback - Show status, timers, and notifications
  • Navigation - Switch between game, settings, and home screens

Game Flow

Home Page (Game Mode Selection)
    ↓
Game Page (Play Chess)
    ├─ Human Move Detection
    ├─ Chess Engine Move Generation
    └─ Board Update/Display
    ↓
End Game Dialog (Result)
    ├─ Play Again → Home Page
    └─ Exit → Application Close
Main Application
├── Home Page
│   ├── Difficulty Choice
│   ├── Color Choice
│   └── Settings Button
├── Game Page
│   ├── Chess Board
│   ├── Move History
│   ├── Chess Clocks
│   ├── Settings Button (Context)
│   ├── Undo Button
│   └── Resign Button
├── Settings Page
│   ├── Core XY Control
│   ├── Camera Calibration and Control
│   └── Magnet Control
└── Dialogs
    ├── Game Over (Win/Draw/Loss)
    ├── Invalid Move Warning
    ├── Promotion Selection
    └── Waiting Indicator

Key Features

  • Responsive Design - Adapts to different screen sizes
  • Drag & Drop Moves - Click pieces and drag to destination
  • Keyboard Shortcuts - Quick access to common functions
  • Undo/Redo - Review and navigate game history
  • Settings Persistence - Save preferences between sessions
  • Error Messages - Clear feedback for user actions
  • Accessible Controls - Large buttons and readable fonts

Styling

The interface uses Material Design theme with custom stylesheet (cnchess_theme.qss) for consistent visual appearance.

Usage Example

from main_ui import MainWindow
from PyQt6.QtWidgets import QApplication
import sys

# Create application
app = QApplication(sys.argv)

# Create main window
window = MainWindow()
window.show()

# Run application
sys.exit(app.exec())

Dependencies

  • PyQt6 - GUI framework
  • PyQt6.QtCore - Core Qt functionality
  • PyQt6.QtGui - Graphics and icons
  • PyQt6.QtWidgets - Widget components
  • Custom stylesheets (QSS files)

Module Documentation

Main UI Application

The primary application window and navigation system.

File for the main window of the application, which contains the home page, the game and the settings page. The main window is responsible for switching between the different pages and managing the overall layout of the application using a QStackedWidget.

MainUI

Bases: QMainWindow

Source code in python/ui/main_ui.py
 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
class MainUI(QMainWindow):

    def __init__(self, chess_model, control, communication, cam):
        """Initialize the main application window with pages and signal connections.

        Args:
            chess_model: Model instance for chess game state management.
            control: Control instance for game control operations.
            communication: Communication instance for hardware communication.
            cam: Camera instance for board capture and analysis.

        Return:
            None
        """
        super().__init__()
        self.chess_model = chess_model
        self.control = control
        self.communication = communication
        self.cam = cam
        self.last_page = "home"
        self._cleaned_up = False

        self.setWindowTitle("CNChess")

        # Load and apply global QSS stylesheet
        qss_path = os.path.join(os.path.dirname(__file__), "cnchess_theme.qss")
        if os.path.exists(qss_path):
            with open(qss_path, "r", encoding="utf-8") as f:
                self.setStyleSheet(f.read())
        else:
            print(f"Warning: QSS theme file not found at {qss_path}")

        # Create the stacked widget to hold the different pages
        self.stacked_widget = QStackedWidget()
        self.setCentralWidget(self.stacked_widget)

        # Create the different pages
        self.home_page = HomeView(chess_model)
        self.game_page = GameView(chess_model,self.control, communication, self.cam)
        self.settings_page = SettingsView(communication, cam)

        # Add the pages to the stacked widget
        self.stacked_widget.addWidget(self.home_page)
        self.stacked_widget.addWidget(self.game_page)
        self.stacked_widget.addWidget(self.settings_page)

        # Connect controller signals to page-switching methods
        self.home_page.home_page_controller.start_game_signal.connect(self.switch_to_game_page)
        self.home_page.home_page_controller.settings_signal.connect(self.switch_to_settings_page)
        self.game_page.game_page_controller.show_settings_signal.connect(self.switch_to_settings_page)
        self.game_page.game_page_controller.return_home_signal.connect(self.switch_to_home_page)
        self.game_page.game_page_controller.take_picture_signal.connect(self.settings_page.update_captured_image)
        self.settings_page.controller.back_button_signal.connect(self.back_button_settings_page)
        self.game_page.game_page_controller.send_gantry_position.connect(self.settings_page.update_coord)

        QShortcut(QKeySequence.StandardKey.Quit, self, activated=self.close)
        QShortcut(QKeySequence("F11"), self, activated=self.toggle_fullscreen)

        self.showFullScreen()

    def toggle_fullscreen(self):
        """Toggle fullscreen mode for the main window.

        Args:
            None

        Return:
            None
        """
        if self.isFullScreen():
            self.showNormal()
        else:
            self.showFullScreen()

    def keyPressEvent(self, event):
        """Handle key presses for fullscreen escape.

        Args:
            event: QKeyEvent instance.

        Return:
            None
        """

        if event.key() == Qt.Key.Key_Escape and self.isFullScreen():
            self.close()
            return
        super().keyPressEvent(event)

    def switch_to_home_page(self):
        """Switch the main window display to the home page and reset the game board.

        Args:
            None

        Return:
            None
        """
        self.last_page = "home"
        self.stacked_widget.setCurrentWidget(self.home_page)
        self.game_page.game_page_controller.reset_board()

    def switch_to_game_page(self):
        """Switch the main window display to the game page and initialize the board.

        Args:
            None

        Return:
            None
        """
        self.last_page = "game"
        self.stacked_widget.setCurrentWidget(self.game_page)
        self.game_page.setup_board()

    def switch_to_settings_page(self):
        """Switch the main window display to the settings page.

        Args:
            None

        Return:
            None
        """
        self.stacked_widget.setCurrentWidget(self.settings_page)
        self.settings_page.update_captured_image()

    def back_button_settings_page(self):
        """Return to the previous page (game or home) from the settings page.

        Args:
            None

        Return:
            None
        """
        if self.last_page == "game":
            self.stacked_widget.setCurrentWidget(self.game_page)
        else:
            self.stacked_widget.setCurrentWidget(self.home_page)    

    def closeEvent(self, event):
        """Handle application window close event and perform cleanup.

        Args:
            event: QCloseEvent instance triggered by window closure.

        Return:
            None
        """
        print("[INFO] Closing application and terminating all threads...")
        self.cleanup_all_threads()
        event.accept()

    def cleanup_all_threads(self):
        """Terminate all worker threads and release resources before closing.

        Args:
            None

        Return:
            None
        """
        if self._cleaned_up:
            return
        self._cleaned_up = True

        # First signal communication shutdown so blocked workers can exit quickly.
        if self.communication is not None:
            try:
                self.communication.shutdown()
            except Exception as e:
                print(f"[WARN] Communication shutdown failed: {e}")

        # Clean up game page threads
        try:
            self.game_page.cleanup_threads()
        except Exception as e:
            print(f"[WARN] Game page cleanup failed: {e}")

        # Clean up settings page threads
        try:
            self.settings_page.cleanup_threads()
        except Exception as e:
            print(f"[WARN] Settings page cleanup failed: {e}")

        # Release camera handle at shutdown.
        if self.cam is not None:
            try:
                self.cam.release()
            except Exception as e:
                print(f"[WARN] Camera release failed: {e}")

    def __del__(self):
        """Destructor to ensure cleanup on object destruction.

        Args:
            None

        Return:
            None
        """
        try:
            self.cleanup_all_threads()
        except Exception:
            pass  # Ignore errors during destruction

__del__()

Destructor to ensure cleanup on object destruction.

Return

None

Source code in python/ui/main_ui.py
208
209
210
211
212
213
214
215
216
217
218
219
220
def __del__(self):
    """Destructor to ensure cleanup on object destruction.

    Args:
        None

    Return:
        None
    """
    try:
        self.cleanup_all_threads()
    except Exception:
        pass  # Ignore errors during destruction

__init__(chess_model, control, communication, cam)

Initialize the main application window with pages and signal connections.

Parameters:

Name Type Description Default
chess_model

Model instance for chess game state management.

required
control

Control instance for game control operations.

required
communication

Communication instance for hardware communication.

required
cam

Camera instance for board capture and analysis.

required
Return

None

Source code in python/ui/main_ui.py
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
def __init__(self, chess_model, control, communication, cam):
    """Initialize the main application window with pages and signal connections.

    Args:
        chess_model: Model instance for chess game state management.
        control: Control instance for game control operations.
        communication: Communication instance for hardware communication.
        cam: Camera instance for board capture and analysis.

    Return:
        None
    """
    super().__init__()
    self.chess_model = chess_model
    self.control = control
    self.communication = communication
    self.cam = cam
    self.last_page = "home"
    self._cleaned_up = False

    self.setWindowTitle("CNChess")

    # Load and apply global QSS stylesheet
    qss_path = os.path.join(os.path.dirname(__file__), "cnchess_theme.qss")
    if os.path.exists(qss_path):
        with open(qss_path, "r", encoding="utf-8") as f:
            self.setStyleSheet(f.read())
    else:
        print(f"Warning: QSS theme file not found at {qss_path}")

    # Create the stacked widget to hold the different pages
    self.stacked_widget = QStackedWidget()
    self.setCentralWidget(self.stacked_widget)

    # Create the different pages
    self.home_page = HomeView(chess_model)
    self.game_page = GameView(chess_model,self.control, communication, self.cam)
    self.settings_page = SettingsView(communication, cam)

    # Add the pages to the stacked widget
    self.stacked_widget.addWidget(self.home_page)
    self.stacked_widget.addWidget(self.game_page)
    self.stacked_widget.addWidget(self.settings_page)

    # Connect controller signals to page-switching methods
    self.home_page.home_page_controller.start_game_signal.connect(self.switch_to_game_page)
    self.home_page.home_page_controller.settings_signal.connect(self.switch_to_settings_page)
    self.game_page.game_page_controller.show_settings_signal.connect(self.switch_to_settings_page)
    self.game_page.game_page_controller.return_home_signal.connect(self.switch_to_home_page)
    self.game_page.game_page_controller.take_picture_signal.connect(self.settings_page.update_captured_image)
    self.settings_page.controller.back_button_signal.connect(self.back_button_settings_page)
    self.game_page.game_page_controller.send_gantry_position.connect(self.settings_page.update_coord)

    QShortcut(QKeySequence.StandardKey.Quit, self, activated=self.close)
    QShortcut(QKeySequence("F11"), self, activated=self.toggle_fullscreen)

    self.showFullScreen()

back_button_settings_page()

Return to the previous page (game or home) from the settings page.

Return

None

Source code in python/ui/main_ui.py
142
143
144
145
146
147
148
149
150
151
152
153
154
def back_button_settings_page(self):
    """Return to the previous page (game or home) from the settings page.

    Args:
        None

    Return:
        None
    """
    if self.last_page == "game":
        self.stacked_widget.setCurrentWidget(self.game_page)
    else:
        self.stacked_widget.setCurrentWidget(self.home_page)    

cleanup_all_threads()

Terminate all worker threads and release resources before closing.

Return

None

Source code in python/ui/main_ui.py
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
def cleanup_all_threads(self):
    """Terminate all worker threads and release resources before closing.

    Args:
        None

    Return:
        None
    """
    if self._cleaned_up:
        return
    self._cleaned_up = True

    # First signal communication shutdown so blocked workers can exit quickly.
    if self.communication is not None:
        try:
            self.communication.shutdown()
        except Exception as e:
            print(f"[WARN] Communication shutdown failed: {e}")

    # Clean up game page threads
    try:
        self.game_page.cleanup_threads()
    except Exception as e:
        print(f"[WARN] Game page cleanup failed: {e}")

    # Clean up settings page threads
    try:
        self.settings_page.cleanup_threads()
    except Exception as e:
        print(f"[WARN] Settings page cleanup failed: {e}")

    # Release camera handle at shutdown.
    if self.cam is not None:
        try:
            self.cam.release()
        except Exception as e:
            print(f"[WARN] Camera release failed: {e}")

closeEvent(event)

Handle application window close event and perform cleanup.

Parameters:

Name Type Description Default
event

QCloseEvent instance triggered by window closure.

required
Return

None

Source code in python/ui/main_ui.py
156
157
158
159
160
161
162
163
164
165
166
167
def closeEvent(self, event):
    """Handle application window close event and perform cleanup.

    Args:
        event: QCloseEvent instance triggered by window closure.

    Return:
        None
    """
    print("[INFO] Closing application and terminating all threads...")
    self.cleanup_all_threads()
    event.accept()

keyPressEvent(event)

Handle key presses for fullscreen escape.

Parameters:

Name Type Description Default
event

QKeyEvent instance.

required
Return

None

Source code in python/ui/main_ui.py
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
def keyPressEvent(self, event):
    """Handle key presses for fullscreen escape.

    Args:
        event: QKeyEvent instance.

    Return:
        None
    """

    if event.key() == Qt.Key.Key_Escape and self.isFullScreen():
        self.close()
        return
    super().keyPressEvent(event)

switch_to_game_page()

Switch the main window display to the game page and initialize the board.

Return

None

Source code in python/ui/main_ui.py
117
118
119
120
121
122
123
124
125
126
127
128
def switch_to_game_page(self):
    """Switch the main window display to the game page and initialize the board.

    Args:
        None

    Return:
        None
    """
    self.last_page = "game"
    self.stacked_widget.setCurrentWidget(self.game_page)
    self.game_page.setup_board()

switch_to_home_page()

Switch the main window display to the home page and reset the game board.

Return

None

Source code in python/ui/main_ui.py
104
105
106
107
108
109
110
111
112
113
114
115
def switch_to_home_page(self):
    """Switch the main window display to the home page and reset the game board.

    Args:
        None

    Return:
        None
    """
    self.last_page = "home"
    self.stacked_widget.setCurrentWidget(self.home_page)
    self.game_page.game_page_controller.reset_board()

switch_to_settings_page()

Switch the main window display to the settings page.

Return

None

Source code in python/ui/main_ui.py
130
131
132
133
134
135
136
137
138
139
140
def switch_to_settings_page(self):
    """Switch the main window display to the settings page.

    Args:
        None

    Return:
        None
    """
    self.stacked_widget.setCurrentWidget(self.settings_page)
    self.settings_page.update_captured_image()

toggle_fullscreen()

Toggle fullscreen mode for the main window.

Return

None

Source code in python/ui/main_ui.py
75
76
77
78
79
80
81
82
83
84
85
86
87
def toggle_fullscreen(self):
    """Toggle fullscreen mode for the main window.

    Args:
        None

    Return:
        None
    """
    if self.isFullScreen():
        self.showNormal()
    else:
        self.showFullScreen()

Game Page

The main game interface where chess is played.

File containing the game page of the application, which is where the user plays the chess game. It contains the chess board, move history, and buttons to undo moves, resign, and start a new game.

AspectRatioWidget

Bases: QWidget

Source code in python/ui/game_page.py
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
class AspectRatioWidget(QWidget):

    def __init__(self, board_widget, parent=None):
        """Create a container that keeps the board widget square.

        Args:
            board_widget (QWidget): The board widget to constrain to a square.
            parent (QWidget | None): Optional parent widget.

        Return:
            None
        """
        super().__init__(parent)
        self.board_widget = board_widget
        self.board_widget.setParent(self) # Make the board a child of this container

    def resizeEvent(self, event):
        """Resize the child board widget to keep a square aspect ratio.

        Args:
            event: Qt resize event.

        Return:
            None
        """

        w = event.size().width()
        h = event.size().height()

        side = min(w, h)

        x = (w - side) // 2
        y = (h - side) // 2

        self.board_widget.setGeometry(x, y, side, side)    
        self.board_widget.update_board(None, resize=True)  # Update the board display on resize

__init__(board_widget, parent=None)

Create a container that keeps the board widget square.

Parameters:

Name Type Description Default
board_widget QWidget

The board widget to constrain to a square.

required
parent QWidget | None

Optional parent widget.

None
Return

None

Source code in python/ui/game_page.py
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
def __init__(self, board_widget, parent=None):
    """Create a container that keeps the board widget square.

    Args:
        board_widget (QWidget): The board widget to constrain to a square.
        parent (QWidget | None): Optional parent widget.

    Return:
        None
    """
    super().__init__(parent)
    self.board_widget = board_widget
    self.board_widget.setParent(self) # Make the board a child of this container

resizeEvent(event)

Resize the child board widget to keep a square aspect ratio.

Parameters:

Name Type Description Default
event

Qt resize event.

required
Return

None

Source code in python/ui/game_page.py
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
def resizeEvent(self, event):
    """Resize the child board widget to keep a square aspect ratio.

    Args:
        event: Qt resize event.

    Return:
        None
    """

    w = event.size().width()
    h = event.size().height()

    side = min(w, h)

    x = (w - side) // 2
    y = (h - side) // 2

    self.board_widget.setGeometry(x, y, side, side)    
    self.board_widget.update_board(None, resize=True)  # Update the board display on resize

ChessBoardWidget

Bases: QWidget

Source code in python/ui/game_page.py
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
class ChessBoardWidget(QWidget):

    squared_clicked_signal = pyqtSignal(int, int)  # Signal to emit when a square is clicked, with row and column info

    def __init__(self):
        """Create the chess board widget.

        Builds an 8x8 grid of clickable squares, loads piece images, and prepares
        an overlay to display robot trajectories.

        Args:
            None

        Return:
            None
        """
        super().__init__()

        self.player_color = chess.WHITE
        self.images = self.load_piece_images()
        self.board = self.fen_to_board_array(chess.STARTING_FEN)
        self.board_layout = QGridLayout()
        self.init_board()
        self.selected_square = None  # Track the currently selected square for move selection
        self.setLayout(self.board_layout)
        self.trajectory_overlay = TrajectoryOverlay(self)
        self.update_board(None, resize=True)  # Initial board setup with correct piece images 

    def init_board(self):
        """Create and layout all square buttons for the board.

        Args:
            None

        Return:
            None
        """

        for row in range(8):
            for col in range(8):

                square_button = GridButton()
                square_button.setMinimumSize(60, 60)  # Set a minimum size for the squares
                square_button.resize(QSize(60,60))  # Set a base size for the squares to maintain aspect ratio
                self.board_layout.addWidget(square_button, row, col)
                self.draw_piece(square_button, self.board[row][col])  # Initialize with empty squares
                square_button.clicked.connect(lambda checked, r=row, c=col: self.handle_square_click(r, c))  # Connect click event with row and column info

        for i in range(8):
            self.board_layout.setRowStretch(i, 1)  # Make rows stretchable
            self.board_layout.setColumnStretch(i, 1)  # Make columns stretchable        

        self.board_layout.setSpacing(0)
        self.board_layout.setVerticalSpacing(0)  # Remove spacing between squares

        self.paint_board()

    def load_piece_images(self):
        """Load piece images from assets directory.
        Args:   
            None
        Return:
            None    
        """
        images = {}
        # Navigate up to python folder, then to chess_assets
        assets_dir = os.path.join(os.path.dirname(__file__), 'assets','chess_assets')

        piece_names = {
            'K': 'white-king', 'Q': 'white-queen', 'R': 'white-rook',
            'B': 'white-bishop', 'N': 'white-knight', 'P': 'white-pawn',
            'k': 'black-king', 'q': 'black-queen', 'r': 'black-rook',
            'b': 'black-bishop', 'n': 'black-knight', 'p': 'black-pawn',
        }

        # Try to load PNG images
        for piece_char, piece_name in piece_names.items():
            path = os.path.join(assets_dir, 'pieces_png', f'{piece_name}.png')
            if os.path.exists(path):
                icon = QIcon(path)
                if not icon.isNull():
                    images[piece_char] = icon

        return images  

    def update_board(self, board_state, resize=False):
        """Update the board display based on the new board state (FEN string).
        Args:
            board_state (str): FEN string representing the current board state.
            resize (bool): True if this update is due to a resize event, False for normal
        Return:
            None    
        """
        if not resize: #If this is a resize event, we don't need to update the board state from the model, just redraw the pieces with the new sizes
            self.board = self.fen_to_board_array(board_state)

        for row in range(8):
            for col in range(8):
                square_button = self.board_layout.itemAtPosition(row, col).widget()
                piece_char = self.board[row][col]
                self.draw_piece(square_button, piece_char)
        self.repaint();

    def draw_piece(self, button, piece_char):
        """Draw the piece on the given square button.
        Args:
            button (QPushButton): The button representing the square to draw on.
            piece_char (str): Character representing the piece to draw (e.g., 'K')
        Return:
            None    
        """

        if piece_char in self.images:
            icon = self.images[piece_char]
            button.setIcon(icon)
            button.setIconSize(button.size())
        else:
            button.setIcon(QIcon())  # Clear the icon for empty squares     

    def fen_to_board_array(self, fen: str):
        """Convert FEN string to 8x8 board array.
        Args:
            fen (str): FEN string representing the board state.
        Return:
            list[list[str]]: 2D list representing the board, where each element is a piece character or '_' for empty squares. 
            The orientation is adjusted based on player color.
        """
        board_str = fen.split(' ')[0]
        rows = board_str.split('/')
        board = []

        for row in rows:
            board_row = []
            for char in row:
                if char.isdigit():
                    board_row.extend(['_'] * int(char))
                else:
                    board_row.append(char)
            board.append(board_row)

        #If black flip the board 
        if not self.player_color :
            #Flip all row
            for i, row in enumerate(board) : 
                row_flip = row[::-1] 
                board[i] = row_flip

            board = board[::-1]

        return board  

    def update_square_highlight(self, row, col):
        """Highlight the selected square and possible move squares.
        Args:
            row (int): Row index of the square to highlight.
            col (int): Column index of the square to highlight.
        Return:
            None
        """
        square_button = self.board_layout.itemAtPosition(row, col).widget()

        square_color = (row + col) % 2
        base_color = LIGHT_SQUARE_COLOR if square_color == 0 else DARK_SQUARE_COLOR

        highlight_color = QColor(base_color).darker(175).name()  # Create a lighter version of the base color for highlighting

        square_button.setStyleSheet(f"background-color: {highlight_color}; border: none;")  

    def handle_square_click(self, row, col):
        """Handle click events on the squares. Emit signal to controller with the clicked square's coordinates.
        Args:            
            row (int): Row index of the clicked square.
            col (int): Column index of
        Return: 
            None    
        """
        self.squared_clicked_signal.emit(row, col)

    def paint_board(self):
        """Paints the squares' board the right color 
        Args:           
            None
        Return:         
            None
        """

        for r in range(8):
            for c in range(8):

                square_button = self.board_layout.itemAtPosition(r, c).widget()
                square_color = (r + c) % 2

                base_color = LIGHT_SQUARE_COLOR if square_color == 0 else DARK_SQUARE_COLOR 

                square_button.setStyleSheet(f"background-color: {base_color}; border: none;")    

        self.update()   

    def resizeEvent(self, event):
        """Handle widget resize by resizing the trajectory overlay.
        Args:
            event: Qt resize event.
        Return:
            None
        """
        super().resizeEvent(event)
        self.trajectory_overlay.setGeometry(0, 0, event.size().width(), event.size().height())
        self.trajectory_overlay.raise_()

    def set_trajectory(self, path):
        """Show the gantry trajectory on the board.
        Args:
            path (list[Command]): List of Command objects representing the move trajectory.
        Return:
            None
        """
        self.trajectory_overlay.set_trajectory(path, self.player_color)

    def clear_trajectory(self):
        """Remove the trajectory overlay.
        Args: 
            None
        Return:
            None    
        """
        self.trajectory_overlay.clear_trajectory()

    def set_player_color(self, player_color):
        """Set player color and update orientation-dependent behavior.
        Args:
            player_color: Player color (typically chess.WHITE or chess.BLACK).
        Return:
            None
        """
        self.player_color = player_color               

__init__()

Create the chess board widget.

Builds an 8x8 grid of clickable squares, loads piece images, and prepares an overlay to display robot trajectories.

Return

None

Source code in python/ui/game_page.py
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
def __init__(self):
    """Create the chess board widget.

    Builds an 8x8 grid of clickable squares, loads piece images, and prepares
    an overlay to display robot trajectories.

    Args:
        None

    Return:
        None
    """
    super().__init__()

    self.player_color = chess.WHITE
    self.images = self.load_piece_images()
    self.board = self.fen_to_board_array(chess.STARTING_FEN)
    self.board_layout = QGridLayout()
    self.init_board()
    self.selected_square = None  # Track the currently selected square for move selection
    self.setLayout(self.board_layout)
    self.trajectory_overlay = TrajectoryOverlay(self)
    self.update_board(None, resize=True)  # Initial board setup with correct piece images 

clear_trajectory()

Remove the trajectory overlay. Args: None Return: None

Source code in python/ui/game_page.py
1518
1519
1520
1521
1522
1523
1524
1525
def clear_trajectory(self):
    """Remove the trajectory overlay.
    Args: 
        None
    Return:
        None    
    """
    self.trajectory_overlay.clear_trajectory()

draw_piece(button, piece_char)

Draw the piece on the given square button. Args: button (QPushButton): The button representing the square to draw on. piece_char (str): Character representing the piece to draw (e.g., 'K') Return: None

Source code in python/ui/game_page.py
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
def draw_piece(self, button, piece_char):
    """Draw the piece on the given square button.
    Args:
        button (QPushButton): The button representing the square to draw on.
        piece_char (str): Character representing the piece to draw (e.g., 'K')
    Return:
        None    
    """

    if piece_char in self.images:
        icon = self.images[piece_char]
        button.setIcon(icon)
        button.setIconSize(button.size())
    else:
        button.setIcon(QIcon())  # Clear the icon for empty squares     

fen_to_board_array(fen)

Convert FEN string to 8x8 board array. Args: fen (str): FEN string representing the board state. Return: list[list[str]]: 2D list representing the board, where each element is a piece character or '_' for empty squares. The orientation is adjusted based on player color.

Source code in python/ui/game_page.py
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
def fen_to_board_array(self, fen: str):
    """Convert FEN string to 8x8 board array.
    Args:
        fen (str): FEN string representing the board state.
    Return:
        list[list[str]]: 2D list representing the board, where each element is a piece character or '_' for empty squares. 
        The orientation is adjusted based on player color.
    """
    board_str = fen.split(' ')[0]
    rows = board_str.split('/')
    board = []

    for row in rows:
        board_row = []
        for char in row:
            if char.isdigit():
                board_row.extend(['_'] * int(char))
            else:
                board_row.append(char)
        board.append(board_row)

    #If black flip the board 
    if not self.player_color :
        #Flip all row
        for i, row in enumerate(board) : 
            row_flip = row[::-1] 
            board[i] = row_flip

        board = board[::-1]

    return board  

handle_square_click(row, col)

Handle click events on the squares. Emit signal to controller with the clicked square's coordinates. Args:
row (int): Row index of the clicked square. col (int): Column index of Return: None

Source code in python/ui/game_page.py
1468
1469
1470
1471
1472
1473
1474
1475
1476
def handle_square_click(self, row, col):
    """Handle click events on the squares. Emit signal to controller with the clicked square's coordinates.
    Args:            
        row (int): Row index of the clicked square.
        col (int): Column index of
    Return: 
        None    
    """
    self.squared_clicked_signal.emit(row, col)

init_board()

Create and layout all square buttons for the board.

Return

None

Source code in python/ui/game_page.py
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
def init_board(self):
    """Create and layout all square buttons for the board.

    Args:
        None

    Return:
        None
    """

    for row in range(8):
        for col in range(8):

            square_button = GridButton()
            square_button.setMinimumSize(60, 60)  # Set a minimum size for the squares
            square_button.resize(QSize(60,60))  # Set a base size for the squares to maintain aspect ratio
            self.board_layout.addWidget(square_button, row, col)
            self.draw_piece(square_button, self.board[row][col])  # Initialize with empty squares
            square_button.clicked.connect(lambda checked, r=row, c=col: self.handle_square_click(r, c))  # Connect click event with row and column info

    for i in range(8):
        self.board_layout.setRowStretch(i, 1)  # Make rows stretchable
        self.board_layout.setColumnStretch(i, 1)  # Make columns stretchable        

    self.board_layout.setSpacing(0)
    self.board_layout.setVerticalSpacing(0)  # Remove spacing between squares

    self.paint_board()

load_piece_images()

Load piece images from assets directory. Args:
None Return: None

Source code in python/ui/game_page.py
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
def load_piece_images(self):
    """Load piece images from assets directory.
    Args:   
        None
    Return:
        None    
    """
    images = {}
    # Navigate up to python folder, then to chess_assets
    assets_dir = os.path.join(os.path.dirname(__file__), 'assets','chess_assets')

    piece_names = {
        'K': 'white-king', 'Q': 'white-queen', 'R': 'white-rook',
        'B': 'white-bishop', 'N': 'white-knight', 'P': 'white-pawn',
        'k': 'black-king', 'q': 'black-queen', 'r': 'black-rook',
        'b': 'black-bishop', 'n': 'black-knight', 'p': 'black-pawn',
    }

    # Try to load PNG images
    for piece_char, piece_name in piece_names.items():
        path = os.path.join(assets_dir, 'pieces_png', f'{piece_name}.png')
        if os.path.exists(path):
            icon = QIcon(path)
            if not icon.isNull():
                images[piece_char] = icon

    return images  

paint_board()

Paints the squares' board the right color Args:
None Return:
None

Source code in python/ui/game_page.py
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
def paint_board(self):
    """Paints the squares' board the right color 
    Args:           
        None
    Return:         
        None
    """

    for r in range(8):
        for c in range(8):

            square_button = self.board_layout.itemAtPosition(r, c).widget()
            square_color = (r + c) % 2

            base_color = LIGHT_SQUARE_COLOR if square_color == 0 else DARK_SQUARE_COLOR 

            square_button.setStyleSheet(f"background-color: {base_color}; border: none;")    

    self.update()   

resizeEvent(event)

Handle widget resize by resizing the trajectory overlay. Args: event: Qt resize event. Return: None

Source code in python/ui/game_page.py
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
def resizeEvent(self, event):
    """Handle widget resize by resizing the trajectory overlay.
    Args:
        event: Qt resize event.
    Return:
        None
    """
    super().resizeEvent(event)
    self.trajectory_overlay.setGeometry(0, 0, event.size().width(), event.size().height())
    self.trajectory_overlay.raise_()

set_player_color(player_color)

Set player color and update orientation-dependent behavior. Args: player_color: Player color (typically chess.WHITE or chess.BLACK). Return: None

Source code in python/ui/game_page.py
1527
1528
1529
1530
1531
1532
1533
1534
def set_player_color(self, player_color):
    """Set player color and update orientation-dependent behavior.
    Args:
        player_color: Player color (typically chess.WHITE or chess.BLACK).
    Return:
        None
    """
    self.player_color = player_color               

set_trajectory(path)

Show the gantry trajectory on the board. Args: path (list[Command]): List of Command objects representing the move trajectory. Return: None

Source code in python/ui/game_page.py
1509
1510
1511
1512
1513
1514
1515
1516
def set_trajectory(self, path):
    """Show the gantry trajectory on the board.
    Args:
        path (list[Command]): List of Command objects representing the move trajectory.
    Return:
        None
    """
    self.trajectory_overlay.set_trajectory(path, self.player_color)

update_board(board_state, resize=False)

Update the board display based on the new board state (FEN string). Args: board_state (str): FEN string representing the current board state. resize (bool): True if this update is due to a resize event, False for normal Return: None

Source code in python/ui/game_page.py
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
def update_board(self, board_state, resize=False):
    """Update the board display based on the new board state (FEN string).
    Args:
        board_state (str): FEN string representing the current board state.
        resize (bool): True if this update is due to a resize event, False for normal
    Return:
        None    
    """
    if not resize: #If this is a resize event, we don't need to update the board state from the model, just redraw the pieces with the new sizes
        self.board = self.fen_to_board_array(board_state)

    for row in range(8):
        for col in range(8):
            square_button = self.board_layout.itemAtPosition(row, col).widget()
            piece_char = self.board[row][col]
            self.draw_piece(square_button, piece_char)
    self.repaint();

update_square_highlight(row, col)

Highlight the selected square and possible move squares. Args: row (int): Row index of the square to highlight. col (int): Column index of the square to highlight. Return: None

Source code in python/ui/game_page.py
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
def update_square_highlight(self, row, col):
    """Highlight the selected square and possible move squares.
    Args:
        row (int): Row index of the square to highlight.
        col (int): Column index of the square to highlight.
    Return:
        None
    """
    square_button = self.board_layout.itemAtPosition(row, col).widget()

    square_color = (row + col) % 2
    base_color = LIGHT_SQUARE_COLOR if square_color == 0 else DARK_SQUARE_COLOR

    highlight_color = QColor(base_color).darker(175).name()  # Create a lighter version of the base color for highlighting

    square_button.setStyleSheet(f"background-color: {highlight_color}; border: none;")  

ChessClock

Bases: QWidget

Chess clock widget with automatic countdown timer.

Source code in python/ui/game_page.py
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
class ChessClock(QWidget):
    """Chess clock widget with automatic countdown timer."""
    outOfTime_signal = pyqtSignal(str)  # Signal to indicate which player ran out of time ("white" or "black")

    def __init__(self, initial_time, clock_label, color="white"):
        """Initialize chess clock with initial time and display label.

        Args:
            initial_time (int): Initial time in seconds.
            clock_label (QLabel): Label widget to display time.
            color (str): Clock color identification ("white" or "black").

        Return:
            None
        """
        super().__init__()
        self.timer = QTimer()
        self.time_left = initial_time
        self.initial_time = initial_time
        self.timer.timeout.connect(self.tick)
        self.clock_label = clock_label
        # Ensure the time text stays centered as the window/label resizes.
        self.clock_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.update_display()
        self.color = color

        self.clock_label.setStyleSheet("""
        background-color: #3b2f2f;
        color: #f3e5ab;
        border: 4px solid #8b5a2b;
        border-radius: 5px;
        padding: 20px;
        font-family: 'Georgia', serif;
        font-size: 32px;
        font-weight: bold;
    """)

    def tick(self):
        """Decrement time and emit signal when time runs out.

        Args:
            None

        Return:
            None
        """
        if self.time_left > 0:
            self.time_left -= 1
            self.update_display()
        elif self.initial_time > 0:  # Only trigger out of time if there was actually a time limit set
            self.timer.stop()
            self.clock_label.setText("00:00")
            self.outOfTime_signal.emit(self.color)   

    def update_display(self):
        """Update clock display with current time.

        Args:
            None

        Return:
            None
        """
        minutes, seconds = divmod(self.time_left, 60)
        self.clock_label.setText(f"{minutes:02d}:{seconds:02d}")

    def toggle_timer(self):
        """Start or stop the chess clock timer.

        Args:
            None

        Return:
            None
        """
        if self.timer.isActive():
            self.timer.stop()
        else:
            self.timer.start(1000)  # Every second

    def reset_clock(self):
        """Reset clock to initial time.

        Args:
            None

        Return:
            None
        """
        self.stop()
        self.time_left = self.initial_time
        self.update_display()

    def stop(self):
        """Stop the timer.

        Args:
            None

        Return:
            None
        """
        if self.timer.isActive():
            self.timer.stop()  

    def set_initial_time(self, new_initial_time):
        """Set a new initial time for the clock and reset it.

        Args:
            new_initial_time (int): New initial time in seconds.
        """
        self.initial_time = new_initial_time   
        self.reset_clock()  # Reset the clock to apply the new initial time      

__init__(initial_time, clock_label, color='white')

Initialize chess clock with initial time and display label.

Parameters:

Name Type Description Default
initial_time int

Initial time in seconds.

required
clock_label QLabel

Label widget to display time.

required
color str

Clock color identification ("white" or "black").

'white'
Return

None

Source code in python/ui/game_page.py
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
def __init__(self, initial_time, clock_label, color="white"):
    """Initialize chess clock with initial time and display label.

    Args:
        initial_time (int): Initial time in seconds.
        clock_label (QLabel): Label widget to display time.
        color (str): Clock color identification ("white" or "black").

    Return:
        None
    """
    super().__init__()
    self.timer = QTimer()
    self.time_left = initial_time
    self.initial_time = initial_time
    self.timer.timeout.connect(self.tick)
    self.clock_label = clock_label
    # Ensure the time text stays centered as the window/label resizes.
    self.clock_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
    self.update_display()
    self.color = color

    self.clock_label.setStyleSheet("""
    background-color: #3b2f2f;
    color: #f3e5ab;
    border: 4px solid #8b5a2b;
    border-radius: 5px;
    padding: 20px;
    font-family: 'Georgia', serif;
    font-size: 32px;
    font-weight: bold;
""")

reset_clock()

Reset clock to initial time.

Return

None

Source code in python/ui/game_page.py
209
210
211
212
213
214
215
216
217
218
219
220
def reset_clock(self):
    """Reset clock to initial time.

    Args:
        None

    Return:
        None
    """
    self.stop()
    self.time_left = self.initial_time
    self.update_display()

set_initial_time(new_initial_time)

Set a new initial time for the clock and reset it.

Parameters:

Name Type Description Default
new_initial_time int

New initial time in seconds.

required
Source code in python/ui/game_page.py
234
235
236
237
238
239
240
241
def set_initial_time(self, new_initial_time):
    """Set a new initial time for the clock and reset it.

    Args:
        new_initial_time (int): New initial time in seconds.
    """
    self.initial_time = new_initial_time   
    self.reset_clock()  # Reset the clock to apply the new initial time      

stop()

Stop the timer.

Return

None

Source code in python/ui/game_page.py
222
223
224
225
226
227
228
229
230
231
232
def stop(self):
    """Stop the timer.

    Args:
        None

    Return:
        None
    """
    if self.timer.isActive():
        self.timer.stop()  

tick()

Decrement time and emit signal when time runs out.

Return

None

Source code in python/ui/game_page.py
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
def tick(self):
    """Decrement time and emit signal when time runs out.

    Args:
        None

    Return:
        None
    """
    if self.time_left > 0:
        self.time_left -= 1
        self.update_display()
    elif self.initial_time > 0:  # Only trigger out of time if there was actually a time limit set
        self.timer.stop()
        self.clock_label.setText("00:00")
        self.outOfTime_signal.emit(self.color)   

toggle_timer()

Start or stop the chess clock timer.

Return

None

Source code in python/ui/game_page.py
195
196
197
198
199
200
201
202
203
204
205
206
207
def toggle_timer(self):
    """Start or stop the chess clock timer.

    Args:
        None

    Return:
        None
    """
    if self.timer.isActive():
        self.timer.stop()
    else:
        self.timer.start(1000)  # Every second

update_display()

Update clock display with current time.

Return

None

Source code in python/ui/game_page.py
183
184
185
186
187
188
189
190
191
192
193
def update_display(self):
    """Update clock display with current time.

    Args:
        None

    Return:
        None
    """
    minutes, seconds = divmod(self.time_left, 60)
    self.clock_label.setText(f"{minutes:02d}:{seconds:02d}")

GamePageController

Bases: QObject

Controller for game page interactions and move execution.

Source code in python/ui/game_page.py
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
class GamePageController(QObject):
    """Controller for game page interactions and move execution."""
    # Define signals for navigation
    show_settings_signal = pyqtSignal()
    start_game_black_signal = pyqtSignal()  # Signal for start of game as black
    return_home_signal = pyqtSignal()
    send_gantry_position = pyqtSignal(float, float, bool)
    take_picture_signal = pyqtSignal()

    def __init__(self, chess_game, view=None, control=None, communication=None, cam=None):
        """Initialize game page controller with chess game and hardware instances.

        Args:
            chess_game: Chess game model instance.
            view (GameView): Game view widget.
            control: Control instance for pathfinding.
            communication: Communication instance for device control.
            cam: Camera instance for board detection.

        Return:
            None
        """
        super().__init__()
        self.chess_game = chess_game
        self.view = view
        self.cam = cam
        self.communication = communication

         # Initialize worker threads
        self.send_path_worker = None
        self.send_path_thread = None
        self.wait_button_worker = None
        self.wait_button_thread = None
        self._is_shutting_down = False

        self.board_widget = self.view.board
        self.board = []
        self.board_positions = []
        board_state = self.chess_game.get_board_state()
        self.board_positions.append(board_state)  # Store the initial board state
        self.board_positions_index = 0
        self.control = control
        self.control.update_board_state(board_state)

        self.selected_piece = None  # Track the currently selected piece for move selection
        self.last_path_was_move = False  # Track if last send_path was a valid move or move reversal
        self.board_widget.squared_clicked_signal.connect(self.handle_square_click)
        self.start_game_black_signal.connect(self.computer_move)
        self.view.white_clock.outOfTime_signal.connect(self.outOfTime)
        self.view.black_clock.outOfTime_signal.connect(self.outOfTime)

    def settings_button_clicked(self):
        """Emit settings signal to navigate to settings page.

        Args:
            None

        Return:
            None
        """
        self.show_settings_signal.emit()

    def quit_game(self):
        """Stop workers and return to home page.

        Args:
            None

        Return:
            None
        """
        self.stop_active_workers()
        self._is_shutting_down = False
        self.return_home_signal.emit()

    def wait_for_thread(self):
        """Wait for any running send_path thread to fully finish.

        Args:
            None

        Return:
            None
        """
        if self.send_path_thread is not None:
            if self.send_path_worker is not None:
                self.send_path_worker.cancel()
            if self.send_path_thread.isRunning():
                self.send_path_thread.quit()
                self.send_path_thread.wait(2000)
            self.send_path_thread = None
            self.send_path_worker = None

    def wait_for_button_thread(self):
        """Wait for any running button-wait thread to fully finish.

        Args:
            None

        Return:
            None
        """
        if self.wait_button_thread is not None:
            if self.wait_button_worker is not None:
                self.wait_button_worker.cancel()
            if self.wait_button_thread.isRunning():
                self.wait_button_thread.quit()
                self.wait_button_thread.wait(2000)
            self.wait_button_thread = None
            self.wait_button_worker = None

    def wait_for_threads(self):
        """Wait for all communication worker threads to finish.
        Args:
            None

        Return:
            None"""
        self.wait_for_thread()
        self.wait_for_button_thread()

    def shutdown(self):
        """Stop async workers and prevent new operations during app shutdown. 
        Args:
            None

        Return:
            None
        """
        self._is_shutting_down = True
        self.stop_active_workers()

    def stop_active_workers(self):
        """Stop current game async operations without locking the controller permanently.
        Args:
            None

        Return:
            None
        """
        self.view.turn_indicator.hide_waiting()
        self.stop_clocks()
        self.wait_for_threads()

    def prepare_for_new_game(self):
        """Re-arm async operations when entering a fresh game.
        Args:
            None

        Return:
            None
        """
        self._is_shutting_down = False
        self.view.turn_indicator.hide_waiting()

    def send_path_async(self, path, is_valid_move=True):
        """Send path to device asynchronously without blocking the UI.

        Args:
            path: The path to send to the device
            is_valid_move: True if this is a valid move path, False if it's a move reversal
        Return:
            None
        """
        if self._is_shutting_down:
            return

        self.last_path_was_move = is_valid_move

        # Wait for any previous thread to finish before starting a new one
        self.wait_for_thread()

        # Create worker and thread (parent=self keeps thread alive)
        self.send_path_worker = SendPathWorker(self.communication, path)
        self.send_path_thread = QThread(parent=self)
        self.send_path_worker.moveToThread(self.send_path_thread)

        # Connect signals
        self.send_path_thread.started.connect(self.send_path_worker.run)
        self.send_path_worker.finished.connect(self.on_send_path_finished)
        self.send_path_worker.finished.connect(self.send_path_thread.quit)
        self.send_path_worker.error.connect(self.on_send_path_error)
        self.send_path_worker.error.connect(self.send_path_thread.quit)

        # Show waiting state and start thread
        self.view.turn_indicator.show_waiting("Sending move to device...\nPlease wait.")
        self.send_path_thread.start()

    def wait_for_button_press_async(self):
        """Wait for physical button press asynchronously without blocking the UI.
        Args:
            None

        Return:
            None
        """
        if self._is_shutting_down:
            return
        self._start_button_wait("Waiting for button press...\nPlease play your move.")

    def _start_button_wait(self, message: str):
        """Internal method to start waiting for button press with a custom message.

        Args:
            message (str): Message to display in the turn indicator while waiting for button press.
        Return:
            None    
        """
        if self._is_shutting_down:
            return

        self.wait_for_button_thread()

        self.wait_button_worker = WaitForButtonWorker(self.communication)
        self.wait_button_thread = QThread(parent=self)
        self.wait_button_worker.moveToThread(self.wait_button_thread)

        self.wait_button_thread.started.connect(self.wait_button_worker.run)
        self.wait_button_worker.finished.connect(self.on_wait_button_finished)
        self.wait_button_worker.finished.connect(self.wait_button_thread.quit)
        self.wait_button_worker.error.connect(self.on_wait_button_error)
        self.wait_button_worker.error.connect(self.wait_button_thread.quit)

        self.view.turn_indicator.show_waiting(message)
        self.wait_button_thread.start()

    def on_send_path_finished(self):
        """Handler when send_path completes successfully.

        Args:
            None

        Return:
            None
        """
        if self._is_shutting_down:
            return
        # Only toggle timers if this was a valid move path, not a move reversal
        if self.last_path_was_move:
            self.view.white_clock.toggle_timer()
            self.view.black_clock.toggle_timer()
            self.wait_for_button_press_async()
        else:
            # This was a move reversal for an invalid move - just wait for next button press
            self._start_button_wait("Invalid move reversed.\nPlease press button to try again.")

    def on_send_path_error(self, error_msg):
        """Handler when send_path encounters an error.

        Args:
            None
        Return:
            None
        """
        if self._is_shutting_down:
            return
        self.view.turn_indicator.hide_waiting()
        self.view.white_clock.toggle_timer()
        self.view.black_clock.toggle_timer()

    def on_wait_button_finished(self):
        """Handler when the ESP button press is detected. Processes the move from the camera and updates the game state accordingly.

        Args:
            None
        Return:
            None
        """
        if self._is_shutting_down:
            return

        self.view.turn_indicator.hide_waiting()
        self.board_widget.clear_trajectory()

        cam_result = self.cam.process_image()
        self.take_picture_signal.emit()
        try:
            move = chess.Move.from_uci(cam_result['move']['uci'])
        except Exception as e:
            print(f"Caught error while parsing move from camera result: {str(e)}.")
            self._start_button_wait("Error detecting move!\nPlease press the button again to try a valid move.")
            return

        if self.chess_game.is_promotion_move(move):
            to_square = move.to_square
            row = 7 - chess.square_rank(to_square) if self.chess_game.get_player_color() == chess.WHITE else chess.square_rank(to_square)
            col = chess.square_file(to_square) if self.chess_game.get_player_color() == chess.WHITE else 7 - chess.square_file(to_square)
            square_widget = self.board_widget.board_layout.itemAtPosition(row, col).widget()
            chosen_piece = self.launch_promotion_dialog(square_widget) 
            if chosen_piece is not None:
                move.promotion = chosen_piece

        if self.chess_game.validate_move(move):
            moved_piece = self.chess_game.get_board().piece_at(move.from_square)
            piece = moved_piece.symbol().upper() if moved_piece is not None else "?"
            to_square = move.to_square
            to_square_name = chess.square_name(to_square)

            self.update_list(move=f"{piece}{to_square_name}", turn=self.chess_game.get_turn())
            path = self.make_move(move)

            if self.view.white_clock.initial_time > 0 and self.view.black_clock.initial_time > 0:
                self.view.white_clock.toggle_timer()
                self.view.black_clock.toggle_timer()
            self.update_chess_board()  # Update the board display after making the move
            self.selected_piece = None  # Reset the selected piece after making a move

            game_outcome = self.handle_game_outcome()
            if not game_outcome :
                self.computer_move()
        else:
            invalid_dialog = InvalidMoveDialog()
            invalid_dialog.exec()
            print(f"Camera processing result: Invalid move detected: {move.uci()}. Waiting for valid move.")
            temp_board = chess.Board(self.chess_game.get_board_state())
            temp_board.push(move)
            self.control.update_board_state(temp_board.fen())
            temp = move.from_square
            move.from_square = move.to_square
            move.to_square = temp
            path = self.control.get_path(move, self.chess_game.get_board())

            self.control.print_path(path)
            # Send the reversal path but mark it as NOT a valid move (so timers won't be toggled)
            self.send_path_async(path, is_valid_move=False)

    def on_wait_button_error(self, error_msg):
        """Handler when waiting for button press fails or times out. 
        Args:
            error_msg (str): Description of the error that occurred while waiting for button press.
        Return:
            None
        """
        if self._is_shutting_down:
            return
        self.view.turn_indicator.hide_waiting()
        self.cam.process_image()
        print(f"Error: {error_msg}. Continuing without button confirmation.")

    def handle_square_click(self, row, col):
        """Handle click events on the squares. Handles move selection and execution logic.

        Args:
            row (int): Row index of the clicked square.
            col (int): Column index of the clicked square.
        Return:
            None    
        """
        self.board_widget.clear_trajectory()

        if self.selected_piece is None:
            self.check_piece_selected(row,col)

        else :
            from_square = self.coordinate_to_square(*self.selected_piece)
            to_square = self.coordinate_to_square(row, col)

            # Try the move and catch any errors from invalid move formats (e.g., clicking the same square as the selected piece), just ignore those and wait for a valid move
            try:    
                move = chess.Move.from_uci(from_square + to_square)

                if self.chess_game.is_promotion_move(move):

                    # Anchor the promotion dialog to the destination square the user clicked.
                    square_widget = self.board_widget.board_layout.itemAtPosition(row, col).widget()
                    chosen_piece = self.launch_promotion_dialog(square_widget)

                    if chosen_piece is not None:
                        move.promotion = chosen_piece
                    else :
                        self.check_piece_selected(row, col)  # Update highlights for the new position after the move
                        return # If no piece chosen, cancel the move and wait for a valid move

                if self.chess_game.validate_move(move):

                    piece = self.board_widget.board[self.selected_piece[0]][self.selected_piece[1]].upper()
                    print(to_square)
                    self.update_list(move=f"{piece}{to_square}", turn=self.chess_game.get_turn())
                    print(f"Camera processing result: Actual move: {move.uci()}")
                    path = self.make_move(move)
                    if self.view.white_clock.initial_time > 0 and self.view.black_clock.initial_time > 0:
                        self.view.white_clock.toggle_timer()
                        self.view.black_clock.toggle_timer()
                    self.update_chess_board()  # Update the board display after making the move
                    self.selected_piece = None  # Reset the selected piece after making a move

                    game_outcome = self.handle_game_outcome()
                    if not game_outcome :
                        self.computer_move()
                else:
                    # If the move is not valid, reset the selection and highlights
                    self.check_piece_selected(row, col)  # Update highlights for the new position after the move
            except ValueError:
                pass # Invalid move format, happens when you click on the same square as the selected piece, just ignore it and wait for a valid move       

    def launch_promotion_dialog(self, square_widget):
        """Launch the promotion dialog anchored to the given square widget.

        Args:
            square_widget (QWidget): The widget representing the chess square where promotion is happening.

        Return:
            str: The piece type chosen for promotion ('q', 'r', 'b', or 'n').
        """
        promotion_dialog = PromotionWidget(self.chess_game.get_player_color())

        # Calculate screen coordinates to position the promotion dialog anchored to the square widget
        screen = QApplication.primaryScreen()
        target_x, target_y = self.get_screen_coordinates_from_square(square_widget, screen, promotion_dialog)
        promotion_dialog.move(target_x, target_y)

        result = promotion_dialog.exec()
        if result:
            return promotion_dialog.chosen_piece
        else:
            return None  # No piece chosen, treat as cancellation

    def get_screen_coordinates_from_square(self, square_widget, screen, promotion_dialog):
        """Calculate screen coordinates to position the promotion dialog anchored to the given square widget.

        Args:
            square_widget (QWidget): The widget representing the chess square.
            screen (QScreen): The primary screen for geometry calculations.
            promotion_dialog (QDialog): The promotion dialog to be positioned.  

        Return:
            (int, int): The (x, y) screen coordinates to position the promotion dialog.
        """


        square_top_left = square_widget.mapToGlobal(QPoint(0, 0))
        square_center_x = square_top_left.x() + (square_widget.width() // 2)

        dialog_w = promotion_dialog.width()
        dialog_h = promotion_dialog.height()

        target_x = square_center_x - (dialog_w // 2)
        y_above = square_top_left.y() - dialog_h
        y_below = square_top_left.y() + square_widget.height()

        screen = QApplication.primaryScreen()
        if screen is not None:
            geo = screen.availableGeometry()
            target_x = max(geo.left(), min(target_x, geo.right() - dialog_w + 1))

            if y_above >= geo.top():
                target_y = y_above
            elif (y_below + dialog_h) <= (geo.bottom() + 1):
                target_y = y_below
            else:
                target_y = max(geo.top(), min(y_above, geo.bottom() - dialog_h + 1))
        else:
            target_y = y_above

        return target_x, target_y


    def check_piece_selected(self, row, col): 

        """Select a piece (if valid) and highlight its legal destination squares.

        If the clicked square contains one of the current player's pieces, the piece is
        selected and the view highlights all legal moves from that square.

        Args:
            row (int): Board row coordinate (0-7).
            col (int): Board column coordinate (0-7).

        Return:
            None
        """

        player_color = self.chess_game.get_player_color()
        piece = self.board_widget.board[row][col]
        if piece != '_' and (( player_color == chess.WHITE and piece.isupper()) or 
                                                (player_color == chess.BLACK and piece.islower())):

            self.selected_piece = (row, col)
            legal_moves = self.chess_game.get_legal_moves_from_square(self.coordinate_to_square(row, col))

            if player_color : 
                highlighted_squares = [(7 - chess.square_rank(move.to_square), chess.square_file(move.to_square)) for move in legal_moves]
            else : 
                highlighted_squares = [(chess.square_rank(move.to_square), 7 - chess.square_file(move.to_square)) for move in legal_moves] 

            highlighted_squares.append((row, col))  # Also highlight the selected piece's square
            self.view.update_highlighted_squares(highlighted_squares)  # Highlight the selected piece and its legal moves

        else :
            self.selected_piece = None
            self.view.update_highlighted_squares([(row, col)])  # Clear highlights if no piece or opponent's piece is selected                

    def computer_move(self):
        """Execute computer's best move on the board and update UI.

        Args:
            None

        Return:
            None
        """
        best_move = self.chess_game.get_next_best_move()
        if best_move and best_move != chess.Move.null():

            uci_move = best_move.uci()
            match = re.search(r'\d+', uci_move)
            split_index = match.end()

            to_square = uci_move[split_index:]
            piece = self.board_widget.board[(7 - chess.square_rank(best_move.from_square))][chess.square_file(best_move.from_square)].upper()
            self.update_list(move=f"{piece}{to_square}",  turn=self.chess_game.get_turn())

            path = self.make_move(best_move)
            self.send_gantry_position.emit(path[-1].position.x * SQUARE_SIZE_MM, path[-1].position.y * SQUARE_SIZE_MM, True)  # Emit the final position of the path for gantry movement

            self.update_chess_board()  # Update the board display after computer move
            self.board_widget.set_trajectory(path)

            # Send path asynchronously to avoid blocking the UI
            self.send_path_async(path)
            self.handle_game_outcome()        

    def handle_game_outcome(self):
        """Check game outcome and show appropriate end-game dialog.

        Args:
            None

        Return:
            str: Game outcome ("white", "black", "draw", or None).
        """
        game_outcome = self.chess_game.check_game_outcome()

        if game_outcome :
            self.stop_clocks()
            if not game_outcome == "draw":
                # Get both king positions
                white_king_pos = self.chess_game.get_board().king(chess.WHITE)
                black_king_pos = self.chess_game.get_board().king(chess.BLACK)

                checkmate_dialog = WinnerDialog(winner_color=game_outcome)
                chess_game_outcome = chess.WHITE if game_outcome == "white" else chess.BLACK
                if chess_game_outcome != self.chess_game.get_player_color(): 
                    if self.chess_game.get_player_color() == chess.WHITE:
                        path = self.make_move(chess.Move.from_uci(f"{chess.square_name(black_king_pos)}{chess.square_name(white_king_pos)}"))
                    else :
                        path = self.make_move(chess.Move.from_uci(f"{chess.square_name(white_king_pos)}{chess.square_name(black_king_pos)}"))
                    self.wait_for_threads()
                    self.send_path_async(path)

                # Hide the waiting indicator before showing the checkmate dialog
                self.view.turn_indicator.hide_waiting()
                result = checkmate_dialog.exec()

            else : 
                draw_dialog = DrawDialog()
                result = draw_dialog.exec()

            #If want to play again switch to home page
            if result : 
                self.return_home_signal.emit()
                self.reset_board()
            else : 
                self.shutdown()
                app = QApplication.instance()
                if app is not None:
                    app.quit()

        return game_outcome       

    def outOfTime(self, losing_color):
        """Handle timeout condition and show outcome dialog.

        Args:
            losing_color (str): Color of player that ran out of time.

        Return:
            None
        """
        winner_color = "black" if losing_color == "white" else "white"

        self.stop_clocks()
        timeout_dialog = WinnerDialog(winner_color=winner_color, reason="timeout")
        result = timeout_dialog.exec()

        if result : 
            self.return_home_signal.emit()
        else : 
            self.shutdown()
            app = QApplication.instance()
            if app is not None:
                app.quit()

    def update_chess_board(self):
        """Update the board widget and store the new board state in history.

        This refreshes the displayed board after a move and appends the current FEN
        position to the controller's history list.

        Args:
            None

        Return:
            None
        """

        self.board_widget.paint_board() # Clear any existing highlights before updating the boar
        board_state = self.chess_game.get_board_state()
        self.board_positions.append(board_state)  # Store the new board state after the move
        self.board_positions_index = len(self.board_positions) - 1  # Update index to the latest position after making a move
        self.board_widget.update_board(board_state)

    def coordinate_to_square(self, row, col):
        """Convert board coordinates to chess square notation (e.g., (0,0) -> 'a8').

        Args:
            row (int): Board row coordinate (0-7).
            col (int): Board column coordinate (0-7).
        Return:
            str: Chess square in algebraic notation corresponding to the given coordinates.    
        """

        if self.chess_game.get_player_color(): 
            file = chr(ord('a') + col)
            rank = 8 - row
        else : 
            file = chr(ord('h') - col)
            rank = row + 1

        return f"{file}{rank}"

    def update_list(self, move, turn):
        """Append a move to the UI move list.

        Args:
            move (str): Move string to display (e.g., "Pe4", "Nf3", "Qxd5").
            turn (str): Player side for this move ("white" or "black").

        Return:
            None
        """

        if turn == "white":
            nb_move = self.view.move_list.count()+1
            self.view.move_list.addItem(QListWidgetItem(f"{nb_move}. {move}"))

        else : 
            nb_move = self.view.move_list.count()
            last_move = self.view.move_list.item(nb_move - 1)
            current_text = last_move.text()
            last_move.setText(current_text + f"\t {move}")

    def move_back_position(self):
        """Step backward in the stored board position history.

        Args:
            None
        Return:
            None
        """
        if self.board_positions_index > 0 :
            self.board_positions_index-=1
            previous_fen = self.board_positions[self.board_positions_index]
            self.board_widget.update_board(previous_fen)
            self.board_widget.paint_board()     

    def move_forward_position(self):
        """Step forward in the stored board position history.

        Args:
            None

        Return:
            None
        """
        if self.board_positions_index < len(self.board_positions) - 1 :
            self.board_positions_index+=1
            previous_fen = self.board_positions[self.board_positions_index]
            self.board_widget.update_board(previous_fen)
            self.board_widget.paint_board()            

    def update_score(self):
        """Recompute and display the material score difference.
        Shows a positive score next to the side that is ahead in material.

        Args:
            None

        Return:
            None
        """

        white_score = self.chess_game.get_material_evaluation(chess.WHITE)
        black_score = self.chess_game.get_material_evaluation(chess.BLACK)

        score = white_score - black_score

        if score > 0 :
            self.view.white_score.setText(f"+{score}")
            self.view.black_score.setText("")

        elif score < 0 :
            self.view.black_score.setText(f"+{-score}")  
            self.view.white_score.setText("")
        else :
            self.reset_score()

    def reset_score(self):
        """Clear the material score display.

        Args:
            None

        Return:
            None
        """
        self.view.white_score.setText("")
        self.view.black_score.setText("")        

    def clear_list(self):
        """Clear all entries from the move list widget.

        Args:
            None

        Return:
            None
        """
        self.view.move_list.clear() 

    def make_move(self, move: chess.Move):
        """Apply a chess move and generate the robot path for executing it.

        This updates the control/path planner with the current board state, generates
        a movement path for the gantry, applies the move to the chess model, updates
        material score, and updates the UI turn indicator.

        Args:
            move: Move to apply (typically a chess.Move instance).

        Return:
            list[Command]: Path as a list of Command objects produced by the control layer.
        """
        self.control.update_board_state(self.chess_game.get_board_state())
        path = self.control.get_path(move, self.chess_game.get_board())

        self.control.print_path(path)
        self.chess_game.make_move(move)
        self.update_score()

        turn = "white" if self.chess_game.get_turn() else "black"
        self.view.turn_indicator.update_turn(turn)

        return path

    def reset_board(self):
        """Reset board to starting position and clear all UI elements.

        Args:
            None

        Return:
            None
        """
        self.chess_game.reset_game()
        state = self.chess_game.get_board_state()
        self.reset_score()
        self.clear_list()
        self.board_widget.clear_trajectory()
        self.board_positions = []
        self.board_positions.append(state)  # Store the initial board state
        self.board_positions_index = 0
        self.board_widget.update_board(state)
        self.board_widget.paint_board()
        self.selected_square = None  # Reset selected square when resetting the board
        self.view.white_clock.reset_clock()
        self.view.black_clock.reset_clock()

    def stop_clocks(self):
        """Stop both white and black chess clocks.

        Args:
            None

        Return:
            None
        """
        self.view.white_clock.stop()
        self.view.black_clock.stop()

__init__(chess_game, view=None, control=None, communication=None, cam=None)

Initialize game page controller with chess game and hardware instances.

Parameters:

Name Type Description Default
chess_game

Chess game model instance.

required
view GameView

Game view widget.

None
control

Control instance for pathfinding.

None
communication

Communication instance for device control.

None
cam

Camera instance for board detection.

None
Return

None

Source code in python/ui/game_page.py
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
def __init__(self, chess_game, view=None, control=None, communication=None, cam=None):
    """Initialize game page controller with chess game and hardware instances.

    Args:
        chess_game: Chess game model instance.
        view (GameView): Game view widget.
        control: Control instance for pathfinding.
        communication: Communication instance for device control.
        cam: Camera instance for board detection.

    Return:
        None
    """
    super().__init__()
    self.chess_game = chess_game
    self.view = view
    self.cam = cam
    self.communication = communication

     # Initialize worker threads
    self.send_path_worker = None
    self.send_path_thread = None
    self.wait_button_worker = None
    self.wait_button_thread = None
    self._is_shutting_down = False

    self.board_widget = self.view.board
    self.board = []
    self.board_positions = []
    board_state = self.chess_game.get_board_state()
    self.board_positions.append(board_state)  # Store the initial board state
    self.board_positions_index = 0
    self.control = control
    self.control.update_board_state(board_state)

    self.selected_piece = None  # Track the currently selected piece for move selection
    self.last_path_was_move = False  # Track if last send_path was a valid move or move reversal
    self.board_widget.squared_clicked_signal.connect(self.handle_square_click)
    self.start_game_black_signal.connect(self.computer_move)
    self.view.white_clock.outOfTime_signal.connect(self.outOfTime)
    self.view.black_clock.outOfTime_signal.connect(self.outOfTime)

check_piece_selected(row, col)

Select a piece (if valid) and highlight its legal destination squares.

If the clicked square contains one of the current player's pieces, the piece is selected and the view highlights all legal moves from that square.

Parameters:

Name Type Description Default
row int

Board row coordinate (0-7).

required
col int

Board column coordinate (0-7).

required
Return

None

Source code in python/ui/game_page.py
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
def check_piece_selected(self, row, col): 

    """Select a piece (if valid) and highlight its legal destination squares.

    If the clicked square contains one of the current player's pieces, the piece is
    selected and the view highlights all legal moves from that square.

    Args:
        row (int): Board row coordinate (0-7).
        col (int): Board column coordinate (0-7).

    Return:
        None
    """

    player_color = self.chess_game.get_player_color()
    piece = self.board_widget.board[row][col]
    if piece != '_' and (( player_color == chess.WHITE and piece.isupper()) or 
                                            (player_color == chess.BLACK and piece.islower())):

        self.selected_piece = (row, col)
        legal_moves = self.chess_game.get_legal_moves_from_square(self.coordinate_to_square(row, col))

        if player_color : 
            highlighted_squares = [(7 - chess.square_rank(move.to_square), chess.square_file(move.to_square)) for move in legal_moves]
        else : 
            highlighted_squares = [(chess.square_rank(move.to_square), 7 - chess.square_file(move.to_square)) for move in legal_moves] 

        highlighted_squares.append((row, col))  # Also highlight the selected piece's square
        self.view.update_highlighted_squares(highlighted_squares)  # Highlight the selected piece and its legal moves

    else :
        self.selected_piece = None
        self.view.update_highlighted_squares([(row, col)])  # Clear highlights if no piece or opponent's piece is selected                

clear_list()

Clear all entries from the move list widget.

Return

None

Source code in python/ui/game_page.py
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
def clear_list(self):
    """Clear all entries from the move list widget.

    Args:
        None

    Return:
        None
    """
    self.view.move_list.clear() 

computer_move()

Execute computer's best move on the board and update UI.

Return

None

Source code in python/ui/game_page.py
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
def computer_move(self):
    """Execute computer's best move on the board and update UI.

    Args:
        None

    Return:
        None
    """
    best_move = self.chess_game.get_next_best_move()
    if best_move and best_move != chess.Move.null():

        uci_move = best_move.uci()
        match = re.search(r'\d+', uci_move)
        split_index = match.end()

        to_square = uci_move[split_index:]
        piece = self.board_widget.board[(7 - chess.square_rank(best_move.from_square))][chess.square_file(best_move.from_square)].upper()
        self.update_list(move=f"{piece}{to_square}",  turn=self.chess_game.get_turn())

        path = self.make_move(best_move)
        self.send_gantry_position.emit(path[-1].position.x * SQUARE_SIZE_MM, path[-1].position.y * SQUARE_SIZE_MM, True)  # Emit the final position of the path for gantry movement

        self.update_chess_board()  # Update the board display after computer move
        self.board_widget.set_trajectory(path)

        # Send path asynchronously to avoid blocking the UI
        self.send_path_async(path)
        self.handle_game_outcome()        

coordinate_to_square(row, col)

Convert board coordinates to chess square notation (e.g., (0,0) -> 'a8').

Parameters:

Name Type Description Default
row int

Board row coordinate (0-7).

required
col int

Board column coordinate (0-7).

required

Return: str: Chess square in algebraic notation corresponding to the given coordinates.

Source code in python/ui/game_page.py
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
def coordinate_to_square(self, row, col):
    """Convert board coordinates to chess square notation (e.g., (0,0) -> 'a8').

    Args:
        row (int): Board row coordinate (0-7).
        col (int): Board column coordinate (0-7).
    Return:
        str: Chess square in algebraic notation corresponding to the given coordinates.    
    """

    if self.chess_game.get_player_color(): 
        file = chr(ord('a') + col)
        rank = 8 - row
    else : 
        file = chr(ord('h') - col)
        rank = row + 1

    return f"{file}{rank}"

get_screen_coordinates_from_square(square_widget, screen, promotion_dialog)

Calculate screen coordinates to position the promotion dialog anchored to the given square widget.

Parameters:

Name Type Description Default
square_widget QWidget

The widget representing the chess square.

required
screen QScreen

The primary screen for geometry calculations.

required
promotion_dialog QDialog

The promotion dialog to be positioned.

required
Return

(int, int): The (x, y) screen coordinates to position the promotion dialog.

Source code in python/ui/game_page.py
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
def get_screen_coordinates_from_square(self, square_widget, screen, promotion_dialog):
    """Calculate screen coordinates to position the promotion dialog anchored to the given square widget.

    Args:
        square_widget (QWidget): The widget representing the chess square.
        screen (QScreen): The primary screen for geometry calculations.
        promotion_dialog (QDialog): The promotion dialog to be positioned.  

    Return:
        (int, int): The (x, y) screen coordinates to position the promotion dialog.
    """


    square_top_left = square_widget.mapToGlobal(QPoint(0, 0))
    square_center_x = square_top_left.x() + (square_widget.width() // 2)

    dialog_w = promotion_dialog.width()
    dialog_h = promotion_dialog.height()

    target_x = square_center_x - (dialog_w // 2)
    y_above = square_top_left.y() - dialog_h
    y_below = square_top_left.y() + square_widget.height()

    screen = QApplication.primaryScreen()
    if screen is not None:
        geo = screen.availableGeometry()
        target_x = max(geo.left(), min(target_x, geo.right() - dialog_w + 1))

        if y_above >= geo.top():
            target_y = y_above
        elif (y_below + dialog_h) <= (geo.bottom() + 1):
            target_y = y_below
        else:
            target_y = max(geo.top(), min(y_above, geo.bottom() - dialog_h + 1))
    else:
        target_y = y_above

    return target_x, target_y

handle_game_outcome()

Check game outcome and show appropriate end-game dialog.

Return

str: Game outcome ("white", "black", "draw", or None).

Source code in python/ui/game_page.py
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
def handle_game_outcome(self):
    """Check game outcome and show appropriate end-game dialog.

    Args:
        None

    Return:
        str: Game outcome ("white", "black", "draw", or None).
    """
    game_outcome = self.chess_game.check_game_outcome()

    if game_outcome :
        self.stop_clocks()
        if not game_outcome == "draw":
            # Get both king positions
            white_king_pos = self.chess_game.get_board().king(chess.WHITE)
            black_king_pos = self.chess_game.get_board().king(chess.BLACK)

            checkmate_dialog = WinnerDialog(winner_color=game_outcome)
            chess_game_outcome = chess.WHITE if game_outcome == "white" else chess.BLACK
            if chess_game_outcome != self.chess_game.get_player_color(): 
                if self.chess_game.get_player_color() == chess.WHITE:
                    path = self.make_move(chess.Move.from_uci(f"{chess.square_name(black_king_pos)}{chess.square_name(white_king_pos)}"))
                else :
                    path = self.make_move(chess.Move.from_uci(f"{chess.square_name(white_king_pos)}{chess.square_name(black_king_pos)}"))
                self.wait_for_threads()
                self.send_path_async(path)

            # Hide the waiting indicator before showing the checkmate dialog
            self.view.turn_indicator.hide_waiting()
            result = checkmate_dialog.exec()

        else : 
            draw_dialog = DrawDialog()
            result = draw_dialog.exec()

        #If want to play again switch to home page
        if result : 
            self.return_home_signal.emit()
            self.reset_board()
        else : 
            self.shutdown()
            app = QApplication.instance()
            if app is not None:
                app.quit()

    return game_outcome       

handle_square_click(row, col)

Handle click events on the squares. Handles move selection and execution logic.

Parameters:

Name Type Description Default
row int

Row index of the clicked square.

required
col int

Column index of the clicked square.

required

Return: None

Source code in python/ui/game_page.py
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
def handle_square_click(self, row, col):
    """Handle click events on the squares. Handles move selection and execution logic.

    Args:
        row (int): Row index of the clicked square.
        col (int): Column index of the clicked square.
    Return:
        None    
    """
    self.board_widget.clear_trajectory()

    if self.selected_piece is None:
        self.check_piece_selected(row,col)

    else :
        from_square = self.coordinate_to_square(*self.selected_piece)
        to_square = self.coordinate_to_square(row, col)

        # Try the move and catch any errors from invalid move formats (e.g., clicking the same square as the selected piece), just ignore those and wait for a valid move
        try:    
            move = chess.Move.from_uci(from_square + to_square)

            if self.chess_game.is_promotion_move(move):

                # Anchor the promotion dialog to the destination square the user clicked.
                square_widget = self.board_widget.board_layout.itemAtPosition(row, col).widget()
                chosen_piece = self.launch_promotion_dialog(square_widget)

                if chosen_piece is not None:
                    move.promotion = chosen_piece
                else :
                    self.check_piece_selected(row, col)  # Update highlights for the new position after the move
                    return # If no piece chosen, cancel the move and wait for a valid move

            if self.chess_game.validate_move(move):

                piece = self.board_widget.board[self.selected_piece[0]][self.selected_piece[1]].upper()
                print(to_square)
                self.update_list(move=f"{piece}{to_square}", turn=self.chess_game.get_turn())
                print(f"Camera processing result: Actual move: {move.uci()}")
                path = self.make_move(move)
                if self.view.white_clock.initial_time > 0 and self.view.black_clock.initial_time > 0:
                    self.view.white_clock.toggle_timer()
                    self.view.black_clock.toggle_timer()
                self.update_chess_board()  # Update the board display after making the move
                self.selected_piece = None  # Reset the selected piece after making a move

                game_outcome = self.handle_game_outcome()
                if not game_outcome :
                    self.computer_move()
            else:
                # If the move is not valid, reset the selection and highlights
                self.check_piece_selected(row, col)  # Update highlights for the new position after the move
        except ValueError:
            pass # Invalid move format, happens when you click on the same square as the selected piece, just ignore it and wait for a valid move       

launch_promotion_dialog(square_widget)

Launch the promotion dialog anchored to the given square widget.

Parameters:

Name Type Description Default
square_widget QWidget

The widget representing the chess square where promotion is happening.

required
Return

str: The piece type chosen for promotion ('q', 'r', 'b', or 'n').

Source code in python/ui/game_page.py
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
def launch_promotion_dialog(self, square_widget):
    """Launch the promotion dialog anchored to the given square widget.

    Args:
        square_widget (QWidget): The widget representing the chess square where promotion is happening.

    Return:
        str: The piece type chosen for promotion ('q', 'r', 'b', or 'n').
    """
    promotion_dialog = PromotionWidget(self.chess_game.get_player_color())

    # Calculate screen coordinates to position the promotion dialog anchored to the square widget
    screen = QApplication.primaryScreen()
    target_x, target_y = self.get_screen_coordinates_from_square(square_widget, screen, promotion_dialog)
    promotion_dialog.move(target_x, target_y)

    result = promotion_dialog.exec()
    if result:
        return promotion_dialog.chosen_piece
    else:
        return None  # No piece chosen, treat as cancellation

make_move(move)

Apply a chess move and generate the robot path for executing it.

This updates the control/path planner with the current board state, generates a movement path for the gantry, applies the move to the chess model, updates material score, and updates the UI turn indicator.

Parameters:

Name Type Description Default
move Move

Move to apply (typically a chess.Move instance).

required
Return

list[Command]: Path as a list of Command objects produced by the control layer.

Source code in python/ui/game_page.py
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
def make_move(self, move: chess.Move):
    """Apply a chess move and generate the robot path for executing it.

    This updates the control/path planner with the current board state, generates
    a movement path for the gantry, applies the move to the chess model, updates
    material score, and updates the UI turn indicator.

    Args:
        move: Move to apply (typically a chess.Move instance).

    Return:
        list[Command]: Path as a list of Command objects produced by the control layer.
    """
    self.control.update_board_state(self.chess_game.get_board_state())
    path = self.control.get_path(move, self.chess_game.get_board())

    self.control.print_path(path)
    self.chess_game.make_move(move)
    self.update_score()

    turn = "white" if self.chess_game.get_turn() else "black"
    self.view.turn_indicator.update_turn(turn)

    return path

move_back_position()

Step backward in the stored board position history.

Return: None

Source code in python/ui/game_page.py
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
def move_back_position(self):
    """Step backward in the stored board position history.

    Args:
        None
    Return:
        None
    """
    if self.board_positions_index > 0 :
        self.board_positions_index-=1
        previous_fen = self.board_positions[self.board_positions_index]
        self.board_widget.update_board(previous_fen)
        self.board_widget.paint_board()     

move_forward_position()

Step forward in the stored board position history.

Return

None

Source code in python/ui/game_page.py
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
def move_forward_position(self):
    """Step forward in the stored board position history.

    Args:
        None

    Return:
        None
    """
    if self.board_positions_index < len(self.board_positions) - 1 :
        self.board_positions_index+=1
        previous_fen = self.board_positions[self.board_positions_index]
        self.board_widget.update_board(previous_fen)
        self.board_widget.paint_board()            

on_send_path_error(error_msg)

Handler when send_path encounters an error.

Return: None

Source code in python/ui/game_page.py
634
635
636
637
638
639
640
641
642
643
644
645
646
def on_send_path_error(self, error_msg):
    """Handler when send_path encounters an error.

    Args:
        None
    Return:
        None
    """
    if self._is_shutting_down:
        return
    self.view.turn_indicator.hide_waiting()
    self.view.white_clock.toggle_timer()
    self.view.black_clock.toggle_timer()

on_send_path_finished()

Handler when send_path completes successfully.

Return

None

Source code in python/ui/game_page.py
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
def on_send_path_finished(self):
    """Handler when send_path completes successfully.

    Args:
        None

    Return:
        None
    """
    if self._is_shutting_down:
        return
    # Only toggle timers if this was a valid move path, not a move reversal
    if self.last_path_was_move:
        self.view.white_clock.toggle_timer()
        self.view.black_clock.toggle_timer()
        self.wait_for_button_press_async()
    else:
        # This was a move reversal for an invalid move - just wait for next button press
        self._start_button_wait("Invalid move reversed.\nPlease press button to try again.")

on_wait_button_error(error_msg)

Handler when waiting for button press fails or times out. Args: error_msg (str): Description of the error that occurred while waiting for button press. Return: None

Source code in python/ui/game_page.py
714
715
716
717
718
719
720
721
722
723
724
725
def on_wait_button_error(self, error_msg):
    """Handler when waiting for button press fails or times out. 
    Args:
        error_msg (str): Description of the error that occurred while waiting for button press.
    Return:
        None
    """
    if self._is_shutting_down:
        return
    self.view.turn_indicator.hide_waiting()
    self.cam.process_image()
    print(f"Error: {error_msg}. Continuing without button confirmation.")

on_wait_button_finished()

Handler when the ESP button press is detected. Processes the move from the camera and updates the game state accordingly.

Return: None

Source code in python/ui/game_page.py
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
def on_wait_button_finished(self):
    """Handler when the ESP button press is detected. Processes the move from the camera and updates the game state accordingly.

    Args:
        None
    Return:
        None
    """
    if self._is_shutting_down:
        return

    self.view.turn_indicator.hide_waiting()
    self.board_widget.clear_trajectory()

    cam_result = self.cam.process_image()
    self.take_picture_signal.emit()
    try:
        move = chess.Move.from_uci(cam_result['move']['uci'])
    except Exception as e:
        print(f"Caught error while parsing move from camera result: {str(e)}.")
        self._start_button_wait("Error detecting move!\nPlease press the button again to try a valid move.")
        return

    if self.chess_game.is_promotion_move(move):
        to_square = move.to_square
        row = 7 - chess.square_rank(to_square) if self.chess_game.get_player_color() == chess.WHITE else chess.square_rank(to_square)
        col = chess.square_file(to_square) if self.chess_game.get_player_color() == chess.WHITE else 7 - chess.square_file(to_square)
        square_widget = self.board_widget.board_layout.itemAtPosition(row, col).widget()
        chosen_piece = self.launch_promotion_dialog(square_widget) 
        if chosen_piece is not None:
            move.promotion = chosen_piece

    if self.chess_game.validate_move(move):
        moved_piece = self.chess_game.get_board().piece_at(move.from_square)
        piece = moved_piece.symbol().upper() if moved_piece is not None else "?"
        to_square = move.to_square
        to_square_name = chess.square_name(to_square)

        self.update_list(move=f"{piece}{to_square_name}", turn=self.chess_game.get_turn())
        path = self.make_move(move)

        if self.view.white_clock.initial_time > 0 and self.view.black_clock.initial_time > 0:
            self.view.white_clock.toggle_timer()
            self.view.black_clock.toggle_timer()
        self.update_chess_board()  # Update the board display after making the move
        self.selected_piece = None  # Reset the selected piece after making a move

        game_outcome = self.handle_game_outcome()
        if not game_outcome :
            self.computer_move()
    else:
        invalid_dialog = InvalidMoveDialog()
        invalid_dialog.exec()
        print(f"Camera processing result: Invalid move detected: {move.uci()}. Waiting for valid move.")
        temp_board = chess.Board(self.chess_game.get_board_state())
        temp_board.push(move)
        self.control.update_board_state(temp_board.fen())
        temp = move.from_square
        move.from_square = move.to_square
        move.to_square = temp
        path = self.control.get_path(move, self.chess_game.get_board())

        self.control.print_path(path)
        # Send the reversal path but mark it as NOT a valid move (so timers won't be toggled)
        self.send_path_async(path, is_valid_move=False)

outOfTime(losing_color)

Handle timeout condition and show outcome dialog.

Parameters:

Name Type Description Default
losing_color str

Color of player that ran out of time.

required
Return

None

Source code in python/ui/game_page.py
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
def outOfTime(self, losing_color):
    """Handle timeout condition and show outcome dialog.

    Args:
        losing_color (str): Color of player that ran out of time.

    Return:
        None
    """
    winner_color = "black" if losing_color == "white" else "white"

    self.stop_clocks()
    timeout_dialog = WinnerDialog(winner_color=winner_color, reason="timeout")
    result = timeout_dialog.exec()

    if result : 
        self.return_home_signal.emit()
    else : 
        self.shutdown()
        app = QApplication.instance()
        if app is not None:
            app.quit()

prepare_for_new_game()

Re-arm async operations when entering a fresh game. Args: None

Return

None

Source code in python/ui/game_page.py
532
533
534
535
536
537
538
539
540
541
def prepare_for_new_game(self):
    """Re-arm async operations when entering a fresh game.
    Args:
        None

    Return:
        None
    """
    self._is_shutting_down = False
    self.view.turn_indicator.hide_waiting()

quit_game()

Stop workers and return to home page.

Return

None

Source code in python/ui/game_page.py
450
451
452
453
454
455
456
457
458
459
460
461
def quit_game(self):
    """Stop workers and return to home page.

    Args:
        None

    Return:
        None
    """
    self.stop_active_workers()
    self._is_shutting_down = False
    self.return_home_signal.emit()

reset_board()

Reset board to starting position and clear all UI elements.

Return

None

Source code in python/ui/game_page.py
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
def reset_board(self):
    """Reset board to starting position and clear all UI elements.

    Args:
        None

    Return:
        None
    """
    self.chess_game.reset_game()
    state = self.chess_game.get_board_state()
    self.reset_score()
    self.clear_list()
    self.board_widget.clear_trajectory()
    self.board_positions = []
    self.board_positions.append(state)  # Store the initial board state
    self.board_positions_index = 0
    self.board_widget.update_board(state)
    self.board_widget.paint_board()
    self.selected_square = None  # Reset selected square when resetting the board
    self.view.white_clock.reset_clock()
    self.view.black_clock.reset_clock()

reset_score()

Clear the material score display.

Return

None

Source code in python/ui/game_page.py
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
def reset_score(self):
    """Clear the material score display.

    Args:
        None

    Return:
        None
    """
    self.view.white_score.setText("")
    self.view.black_score.setText("")        

send_path_async(path, is_valid_move=True)

Send path to device asynchronously without blocking the UI.

Parameters:

Name Type Description Default
path

The path to send to the device

required
is_valid_move

True if this is a valid move path, False if it's a move reversal

True

Return: None

Source code in python/ui/game_page.py
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
def send_path_async(self, path, is_valid_move=True):
    """Send path to device asynchronously without blocking the UI.

    Args:
        path: The path to send to the device
        is_valid_move: True if this is a valid move path, False if it's a move reversal
    Return:
        None
    """
    if self._is_shutting_down:
        return

    self.last_path_was_move = is_valid_move

    # Wait for any previous thread to finish before starting a new one
    self.wait_for_thread()

    # Create worker and thread (parent=self keeps thread alive)
    self.send_path_worker = SendPathWorker(self.communication, path)
    self.send_path_thread = QThread(parent=self)
    self.send_path_worker.moveToThread(self.send_path_thread)

    # Connect signals
    self.send_path_thread.started.connect(self.send_path_worker.run)
    self.send_path_worker.finished.connect(self.on_send_path_finished)
    self.send_path_worker.finished.connect(self.send_path_thread.quit)
    self.send_path_worker.error.connect(self.on_send_path_error)
    self.send_path_worker.error.connect(self.send_path_thread.quit)

    # Show waiting state and start thread
    self.view.turn_indicator.show_waiting("Sending move to device...\nPlease wait.")
    self.send_path_thread.start()

settings_button_clicked()

Emit settings signal to navigate to settings page.

Return

None

Source code in python/ui/game_page.py
439
440
441
442
443
444
445
446
447
448
def settings_button_clicked(self):
    """Emit settings signal to navigate to settings page.

    Args:
        None

    Return:
        None
    """
    self.show_settings_signal.emit()

shutdown()

Stop async workers and prevent new operations during app shutdown. Args: None

Return

None

Source code in python/ui/game_page.py
509
510
511
512
513
514
515
516
517
518
def shutdown(self):
    """Stop async workers and prevent new operations during app shutdown. 
    Args:
        None

    Return:
        None
    """
    self._is_shutting_down = True
    self.stop_active_workers()

stop_active_workers()

Stop current game async operations without locking the controller permanently. Args: None

Return

None

Source code in python/ui/game_page.py
520
521
522
523
524
525
526
527
528
529
530
def stop_active_workers(self):
    """Stop current game async operations without locking the controller permanently.
    Args:
        None

    Return:
        None
    """
    self.view.turn_indicator.hide_waiting()
    self.stop_clocks()
    self.wait_for_threads()

stop_clocks()

Stop both white and black chess clocks.

Return

None

Source code in python/ui/game_page.py
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
def stop_clocks(self):
    """Stop both white and black chess clocks.

    Args:
        None

    Return:
        None
    """
    self.view.white_clock.stop()
    self.view.black_clock.stop()

update_chess_board()

Update the board widget and store the new board state in history.

This refreshes the displayed board after a move and appends the current FEN position to the controller's history list.

Return

None

Source code in python/ui/game_page.py
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
def update_chess_board(self):
    """Update the board widget and store the new board state in history.

    This refreshes the displayed board after a move and appends the current FEN
    position to the controller's history list.

    Args:
        None

    Return:
        None
    """

    self.board_widget.paint_board() # Clear any existing highlights before updating the boar
    board_state = self.chess_game.get_board_state()
    self.board_positions.append(board_state)  # Store the new board state after the move
    self.board_positions_index = len(self.board_positions) - 1  # Update index to the latest position after making a move
    self.board_widget.update_board(board_state)

update_list(move, turn)

Append a move to the UI move list.

Parameters:

Name Type Description Default
move str

Move string to display (e.g., "Pe4", "Nf3", "Qxd5").

required
turn str

Player side for this move ("white" or "black").

required
Return

None

Source code in python/ui/game_page.py
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
def update_list(self, move, turn):
    """Append a move to the UI move list.

    Args:
        move (str): Move string to display (e.g., "Pe4", "Nf3", "Qxd5").
        turn (str): Player side for this move ("white" or "black").

    Return:
        None
    """

    if turn == "white":
        nb_move = self.view.move_list.count()+1
        self.view.move_list.addItem(QListWidgetItem(f"{nb_move}. {move}"))

    else : 
        nb_move = self.view.move_list.count()
        last_move = self.view.move_list.item(nb_move - 1)
        current_text = last_move.text()
        last_move.setText(current_text + f"\t {move}")

update_score()

Recompute and display the material score difference. Shows a positive score next to the side that is ahead in material.

Return

None

Source code in python/ui/game_page.py
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
def update_score(self):
    """Recompute and display the material score difference.
    Shows a positive score next to the side that is ahead in material.

    Args:
        None

    Return:
        None
    """

    white_score = self.chess_game.get_material_evaluation(chess.WHITE)
    black_score = self.chess_game.get_material_evaluation(chess.BLACK)

    score = white_score - black_score

    if score > 0 :
        self.view.white_score.setText(f"+{score}")
        self.view.black_score.setText("")

    elif score < 0 :
        self.view.black_score.setText(f"+{-score}")  
        self.view.white_score.setText("")
    else :
        self.reset_score()

wait_for_button_press_async()

Wait for physical button press asynchronously without blocking the UI. Args: None

Return

None

Source code in python/ui/game_page.py
576
577
578
579
580
581
582
583
584
585
586
def wait_for_button_press_async(self):
    """Wait for physical button press asynchronously without blocking the UI.
    Args:
        None

    Return:
        None
    """
    if self._is_shutting_down:
        return
    self._start_button_wait("Waiting for button press...\nPlease play your move.")

wait_for_button_thread()

Wait for any running button-wait thread to fully finish.

Return

None

Source code in python/ui/game_page.py
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
def wait_for_button_thread(self):
    """Wait for any running button-wait thread to fully finish.

    Args:
        None

    Return:
        None
    """
    if self.wait_button_thread is not None:
        if self.wait_button_worker is not None:
            self.wait_button_worker.cancel()
        if self.wait_button_thread.isRunning():
            self.wait_button_thread.quit()
            self.wait_button_thread.wait(2000)
        self.wait_button_thread = None
        self.wait_button_worker = None

wait_for_thread()

Wait for any running send_path thread to fully finish.

Return

None

Source code in python/ui/game_page.py
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
def wait_for_thread(self):
    """Wait for any running send_path thread to fully finish.

    Args:
        None

    Return:
        None
    """
    if self.send_path_thread is not None:
        if self.send_path_worker is not None:
            self.send_path_worker.cancel()
        if self.send_path_thread.isRunning():
            self.send_path_thread.quit()
            self.send_path_thread.wait(2000)
        self.send_path_thread = None
        self.send_path_worker = None

wait_for_threads()

Wait for all communication worker threads to finish. Args: None

Return

None

Source code in python/ui/game_page.py
499
500
501
502
503
504
505
506
507
def wait_for_threads(self):
    """Wait for all communication worker threads to finish.
    Args:
        None

    Return:
        None"""
    self.wait_for_thread()
    self.wait_for_button_thread()

GameView

Bases: QWidget

Game page view containing chess board, clocks, and move history.

Source code in python/ui/game_page.py
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
class GameView(QWidget):
    """Game page view containing chess board, clocks, and move history."""

    def __init__(self, chess_game, control, communication, cam):
        """Initialize game view with chess game and hardware instances.

        Args:
            chess_game: Chess game model instance.
            control: Control instance for pathfinding.
            communication: Communication instance for device control.
            cam: Camera instance for board detection.

        Return:
            None
        """
        super().__init__()

        self.chess_game = chess_game
        self.control = control
        self.cam = cam

        # Load the UI from the .ui file
        ui_path = os.path.join(os.path.dirname(__file__), 'gamePage.ui')

        if not os.path.exists(ui_path):
            raise FileNotFoundError(f"UI file not found at path: {ui_path}")

        uic.loadUi(ui_path, self)

        settings_button = self.findChild(QPushButton, "settingsButton")
        quit_button = self.findChild(QPushButton, "quitButton")  
        right_layout = self.findChild(QVBoxLayout, "rightLayout")
        resign_button = self.findChild(QPushButton, "resignButton")
        start_button = self.findChild(QPushButton, "startButton")
        move_back_button = self.findChild(QPushButton, "moveBackButton")
        move_forward_button = self.findChild(QPushButton, "moveForwardButton")
        self.move_list = self.findChild(QListWidget, "moveList")
        self.white_timer_display = self.findChild(QLabel, 'whiteTimer')
        self.black_timer_display = self.findChild(QLabel, 'blackTimer')
        self.black_score = self.findChild(QLabel, 'blackScore')
        self.white_score = self.findChild(QLabel, 'whiteScore')

        # Replace the simple turn_indicator label with TurnIndicatorWidget
        old_turn_indicator = self.findChild(QLabel, 'labelTurn')
        # Find the parent layout (layout_Timers)
        layout_timers = self.findChild(QHBoxLayout, 'layout_Timers')
        # Get the index of the old turn indicator
        index = layout_timers.indexOf(old_turn_indicator)
        # Remove the old widget
        layout_timers.removeWidget(old_turn_indicator)
        old_turn_indicator.deleteLater()
        # Create and insert the new TurnIndicatorWidget
        self.turn_indicator = TurnIndicatorWidget()
        layout_timers.insertWidget(index, self.turn_indicator)

        #Replace gridLayout in .ui by board widget with resizing capabilities    
        right_layout.removeItem(right_layout.itemAt(1))  
        resize_board = AspectRatioWidget(ChessBoardWidget())
        right_layout.insertWidget(1,resize_board)
        self.board = resize_board.board_widget

        self.white_clock = ChessClock(initial_time=600, clock_label=self.white_timer_display, color="white")
        self.black_clock = ChessClock(initial_time=600, clock_label=self.black_timer_display, color="black")

        self.game_page_controller = GamePageController(chess_game,self, self.control, communication, self.cam)

        # Connect buttons to controller methods
        settings_button.clicked.connect(self.game_page_controller.settings_button_clicked)     
        quit_button.clicked.connect(self.game_page_controller.quit_game)
        resign_button.clicked.connect(self.game_page_controller.reset_board)
        start_button.clicked.connect(self.start_time)
        move_back_button.clicked.connect(self.game_page_controller.move_back_position)
        move_forward_button.clicked.connect(self.game_page_controller.move_forward_position)

    def cleanup_threads(self):
        """Clean up all worker threads in the game page.
        Args:
            None
        Return:
            None    
        """
        self.game_page_controller.shutdown()

    def setup_board(self):
        """Set up board for new game by preparing controller and resetting state. Sends home command to gantry at start of game.

        Args:
            None

        Return:
            None
        """

        self.game_page_controller.communication.go_home()  # Move gantry to home position at start of game
        self.game_page_controller.prepare_for_new_game()
        color = self.chess_game.get_player_color()
        self.board.set_player_color(color)
        self.chess_game.reset_game()
        self.white_clock.set_initial_time(self.chess_game.get_time_control()*60)
        self.black_clock.set_initial_time(self.chess_game.get_time_control()*60)
        self.board.paint_board() # Clear any existing highlights before updating the boar
        self.board.update_board(self.chess_game.get_board_state())

    def start_time(self):
        """Start the chess clocks and initiate game based on player color.

        Args:
            None

        Return:
            None
        """
        color = self.chess_game.get_player_color()

        self.white_clock.reset_clock()
        self.black_clock.reset_clock()

        #If player is black launch first move of computer as white
        if not color :
            self.turn_indicator.update_turn("black")
            self.game_page_controller.start_game_black_signal.emit()

        else :        
            self.turn_indicator.update_turn("white")
            # Human starts as white: wait asynchronously for the board button press.
            self.game_page_controller.wait_for_button_press_async()

        if self.white_clock.initial_time > 0:    
            self.white_clock.toggle_timer()

    def update_highlighted_squares(self, squares):
        """Highlight the given squares on the board.

        Args:
            squares (list): List of (row, col) tuples to highlight.

        Return:
            None
        """
        self.board.paint_board()  # Clear existing highlights before applying new ones

        for row, col in squares:
            self.board.update_square_highlight(row, col)    

__init__(chess_game, control, communication, cam)

Initialize game view with chess game and hardware instances.

Parameters:

Name Type Description Default
chess_game

Chess game model instance.

required
control

Control instance for pathfinding.

required
communication

Communication instance for device control.

required
cam

Camera instance for board detection.

required
Return

None

Source code in python/ui/game_page.py
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
def __init__(self, chess_game, control, communication, cam):
    """Initialize game view with chess game and hardware instances.

    Args:
        chess_game: Chess game model instance.
        control: Control instance for pathfinding.
        communication: Communication instance for device control.
        cam: Camera instance for board detection.

    Return:
        None
    """
    super().__init__()

    self.chess_game = chess_game
    self.control = control
    self.cam = cam

    # Load the UI from the .ui file
    ui_path = os.path.join(os.path.dirname(__file__), 'gamePage.ui')

    if not os.path.exists(ui_path):
        raise FileNotFoundError(f"UI file not found at path: {ui_path}")

    uic.loadUi(ui_path, self)

    settings_button = self.findChild(QPushButton, "settingsButton")
    quit_button = self.findChild(QPushButton, "quitButton")  
    right_layout = self.findChild(QVBoxLayout, "rightLayout")
    resign_button = self.findChild(QPushButton, "resignButton")
    start_button = self.findChild(QPushButton, "startButton")
    move_back_button = self.findChild(QPushButton, "moveBackButton")
    move_forward_button = self.findChild(QPushButton, "moveForwardButton")
    self.move_list = self.findChild(QListWidget, "moveList")
    self.white_timer_display = self.findChild(QLabel, 'whiteTimer')
    self.black_timer_display = self.findChild(QLabel, 'blackTimer')
    self.black_score = self.findChild(QLabel, 'blackScore')
    self.white_score = self.findChild(QLabel, 'whiteScore')

    # Replace the simple turn_indicator label with TurnIndicatorWidget
    old_turn_indicator = self.findChild(QLabel, 'labelTurn')
    # Find the parent layout (layout_Timers)
    layout_timers = self.findChild(QHBoxLayout, 'layout_Timers')
    # Get the index of the old turn indicator
    index = layout_timers.indexOf(old_turn_indicator)
    # Remove the old widget
    layout_timers.removeWidget(old_turn_indicator)
    old_turn_indicator.deleteLater()
    # Create and insert the new TurnIndicatorWidget
    self.turn_indicator = TurnIndicatorWidget()
    layout_timers.insertWidget(index, self.turn_indicator)

    #Replace gridLayout in .ui by board widget with resizing capabilities    
    right_layout.removeItem(right_layout.itemAt(1))  
    resize_board = AspectRatioWidget(ChessBoardWidget())
    right_layout.insertWidget(1,resize_board)
    self.board = resize_board.board_widget

    self.white_clock = ChessClock(initial_time=600, clock_label=self.white_timer_display, color="white")
    self.black_clock = ChessClock(initial_time=600, clock_label=self.black_timer_display, color="black")

    self.game_page_controller = GamePageController(chess_game,self, self.control, communication, self.cam)

    # Connect buttons to controller methods
    settings_button.clicked.connect(self.game_page_controller.settings_button_clicked)     
    quit_button.clicked.connect(self.game_page_controller.quit_game)
    resign_button.clicked.connect(self.game_page_controller.reset_board)
    start_button.clicked.connect(self.start_time)
    move_back_button.clicked.connect(self.game_page_controller.move_back_position)
    move_forward_button.clicked.connect(self.game_page_controller.move_forward_position)

cleanup_threads()

Clean up all worker threads in the game page. Args: None Return: None

Source code in python/ui/game_page.py
318
319
320
321
322
323
324
325
def cleanup_threads(self):
    """Clean up all worker threads in the game page.
    Args:
        None
    Return:
        None    
    """
    self.game_page_controller.shutdown()

setup_board()

Set up board for new game by preparing controller and resetting state. Sends home command to gantry at start of game.

Return

None

Source code in python/ui/game_page.py
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
def setup_board(self):
    """Set up board for new game by preparing controller and resetting state. Sends home command to gantry at start of game.

    Args:
        None

    Return:
        None
    """

    self.game_page_controller.communication.go_home()  # Move gantry to home position at start of game
    self.game_page_controller.prepare_for_new_game()
    color = self.chess_game.get_player_color()
    self.board.set_player_color(color)
    self.chess_game.reset_game()
    self.white_clock.set_initial_time(self.chess_game.get_time_control()*60)
    self.black_clock.set_initial_time(self.chess_game.get_time_control()*60)
    self.board.paint_board() # Clear any existing highlights before updating the boar
    self.board.update_board(self.chess_game.get_board_state())

start_time()

Start the chess clocks and initiate game based on player color.

Return

None

Source code in python/ui/game_page.py
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
def start_time(self):
    """Start the chess clocks and initiate game based on player color.

    Args:
        None

    Return:
        None
    """
    color = self.chess_game.get_player_color()

    self.white_clock.reset_clock()
    self.black_clock.reset_clock()

    #If player is black launch first move of computer as white
    if not color :
        self.turn_indicator.update_turn("black")
        self.game_page_controller.start_game_black_signal.emit()

    else :        
        self.turn_indicator.update_turn("white")
        # Human starts as white: wait asynchronously for the board button press.
        self.game_page_controller.wait_for_button_press_async()

    if self.white_clock.initial_time > 0:    
        self.white_clock.toggle_timer()

update_highlighted_squares(squares)

Highlight the given squares on the board.

Parameters:

Name Type Description Default
squares list

List of (row, col) tuples to highlight.

required
Return

None

Source code in python/ui/game_page.py
374
375
376
377
378
379
380
381
382
383
384
385
386
def update_highlighted_squares(self, squares):
    """Highlight the given squares on the board.

    Args:
        squares (list): List of (row, col) tuples to highlight.

    Return:
        None
    """
    self.board.paint_board()  # Clear existing highlights before applying new ones

    for row, col in squares:
        self.board.update_square_highlight(row, col)    

GridButton

Bases: QPushButton

Source code in python/ui/game_page.py
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
class GridButton(QPushButton):
    def __init__(self):
        """Create a grid button that stays square within layouts.

        Args:
            None

        Return:
            None
        """
        super().__init__()

        sizePolicy = self.sizePolicy()
        sizePolicy.setHeightForWidth(True)
        self.setSizePolicy(sizePolicy)
        self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)

    def heightForWidth(self, width):
        """Return the preferred height for a given width.
        This enforces a square shape.
        Args:
            width (int): Current width.
        Return:
            int: Height equal to width.
        """
        return width  

__init__()

Create a grid button that stays square within layouts.

Return

None

Source code in python/ui/game_page.py
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
def __init__(self):
    """Create a grid button that stays square within layouts.

    Args:
        None

    Return:
        None
    """
    super().__init__()

    sizePolicy = self.sizePolicy()
    sizePolicy.setHeightForWidth(True)
    self.setSizePolicy(sizePolicy)
    self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)

heightForWidth(width)

Return the preferred height for a given width. This enforces a square shape. Args: width (int): Current width. Return: int: Height equal to width.

Source code in python/ui/game_page.py
1591
1592
1593
1594
1595
1596
1597
1598
1599
def heightForWidth(self, width):
    """Return the preferred height for a given width.
    This enforces a square shape.
    Args:
        width (int): Current width.
    Return:
        int: Height equal to width.
    """
    return width  

SendPathWorker

Bases: QObject

Worker thread to send path commands without blocking the UI.

Source code in python/ui/game_page.py
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
class SendPathWorker(QObject):
    """Worker thread to send path commands without blocking the UI."""
    finished = pyqtSignal()
    error = pyqtSignal(str)

    def __init__(self, communication, path):
        """Initialize the send-path worker.

        Args:
            communication: Communication instance used to send commands to the ESP/device.
            path: List of Command objects (or equivalent) to send to the device.

        Return:
            None
        """
        super().__init__()
        self.communication = communication
        self.path = path
        self._stop_event = threading.Event()

    def cancel(self):
        """Request cancellation of the worker operation.

        Args:
            None

        Return:
            None
        """
        self._stop_event.set()

    def run(self):
        """Execute send_path in the worker thread.

        Args:
            None
        Return:
            None    
        """
        try:
            if self._stop_event.is_set():
                return
            result = self.communication.send_path(self.path, stop_event=self._stop_event)
            if self._stop_event.is_set():
                return
            if not result:
                self.error.emit("Failed to send path to device")
            else:
                self.finished.emit()
        except Exception as e:
            self.error.emit(f"Error sending path: {str(e)}")

__init__(communication, path)

Initialize the send-path worker.

Parameters:

Name Type Description Default
communication

Communication instance used to send commands to the ESP/device.

required
path

List of Command objects (or equivalent) to send to the device.

required
Return

None

Source code in python/ui/game_page.py
32
33
34
35
36
37
38
39
40
41
42
43
44
45
def __init__(self, communication, path):
    """Initialize the send-path worker.

    Args:
        communication: Communication instance used to send commands to the ESP/device.
        path: List of Command objects (or equivalent) to send to the device.

    Return:
        None
    """
    super().__init__()
    self.communication = communication
    self.path = path
    self._stop_event = threading.Event()

cancel()

Request cancellation of the worker operation.

Return

None

Source code in python/ui/game_page.py
47
48
49
50
51
52
53
54
55
56
def cancel(self):
    """Request cancellation of the worker operation.

    Args:
        None

    Return:
        None
    """
    self._stop_event.set()

run()

Execute send_path in the worker thread.

Return: None

Source code in python/ui/game_page.py
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
def run(self):
    """Execute send_path in the worker thread.

    Args:
        None
    Return:
        None    
    """
    try:
        if self._stop_event.is_set():
            return
        result = self.communication.send_path(self.path, stop_event=self._stop_event)
        if self._stop_event.is_set():
            return
        if not result:
            self.error.emit("Failed to send path to device")
        else:
            self.finished.emit()
    except Exception as e:
        self.error.emit(f"Error sending path: {str(e)}")

TrajectoryOverlay

Bases: QWidget

Transparent overlay that draws the move trajectory on top of the board.

Source code in python/ui/game_page.py
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
class TrajectoryOverlay(QWidget):
    """Transparent overlay that draws the move trajectory on top of the board."""

    TRAJECTORY_COLOR = QColor(220, 50, 50, 200)
    EAT_COLOR = QColor(50, 220, 50, 200)
    POINT_COLOR = QColor(50, 50, 220, 200)
    LINE_WIDTH = 3
    DOT_RADIUS = 4
    ARROW_SIZE = 12

    def __init__(self, parent=None):
        """Initialize the trajectory overlay widget.

        Args:
            parent (QWidget | None): Parent widget (typically the board widget).

        Return:
            None
        """
        super().__init__(parent)
        self.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents)
        self.setAttribute(Qt.WidgetAttribute.WA_NoSystemBackground)
        self.trajectory = []  # list of (x, y) in 1-based board coords
        self.player_color = chess.WHITE

    def set_trajectory(self, path, player_color):
        """Set trajectory from a list of Command objects.

        Args:
            path (list[Command]): List of Command objects representing the move trajectory.
            player_color (bool): Player color to determine coordinate orientation (True for white, False for black).
        Return:
            None
        """
        self.trajectory = [(cmd.position.x, cmd.position.y) for cmd in path]
        self.magnet_states = [cmd.magnet_state for cmd in path]
        self.player_color = player_color
        self.update()

    def clear_trajectory(self):
        """Clear the currently displayed trajectory.

        Args:
            None

        Return:
            None
        """
        self.trajectory = []
        self.update()

    def _to_pixel(self, x, y):
        """Convert 1-based board coordinates to pixel position on the widget.

        Args:
            x (float): X coordinate in board space (1-8).
            y (float): Y coordinate in board space (1-8).
        Return:
            QPointF: Pixel coordinates corresponding to the given board coordinates, adjusted for player color orientation.    
        """
        sw = self.width() / 8.0
        sh = self.height() / 8.0
        if self.player_color == chess.WHITE:
            px = sw * (x - 0.5)
            py = sh * (8.5 - y)
        else:
            px = sw * (8.5 - x)
            py = sh * (y - 0.5)
        return QPointF(px, py)

    def paintEvent(self, event):
        """Paint the trajectory overlay on top of the board.

        Args:
            event: Qt paint event.

        Return:
            None
        """
        if len(self.trajectory) < 2:
            return

        painter = QPainter(self)
        painter.setRenderHint(QPainter.RenderHint.Antialiasing)

        pen = QPen(self.TRAJECTORY_COLOR, self.LINE_WIDTH)
        painter.setPen(pen)

        points = [self._to_pixel(x, y) for x, y in self.trajectory]

        # Draw path lines
        for i in range(len(points) - 1):
            if self.magnet_states[i] == False:
                painter.setPen(QPen(self.EAT_COLOR, self.LINE_WIDTH, Qt.PenStyle.DashLine))
                continue
            painter.drawLine(points[i], points[i + 1])

        # Draw dots at waypoints
        painter.setBrush(self.POINT_COLOR)
        painter.setPen(Qt.PenStyle.NoPen)
        for pt in points:
            painter.drawEllipse(pt, self.DOT_RADIUS, self.DOT_RADIUS)

        # Draw arrowhead at the final point
        if len(points) >= 2:
            p1 = points[-2]
            p2 = points[-1]
            angle = math.atan2(p2.y() - p1.y(), p2.x() - p1.x())
            arrow_p1 = QPointF(
                p2.x() - self.ARROW_SIZE * math.cos(angle - math.pi / 6),
                p2.y() - self.ARROW_SIZE * math.sin(angle - math.pi / 6),
            )
            arrow_p2 = QPointF(
                p2.x() - self.ARROW_SIZE * math.cos(angle + math.pi / 6),
                p2.y() - self.ARROW_SIZE * math.sin(angle + math.pi / 6),
            )
            painter.setBrush(self.TRAJECTORY_COLOR)
            painter.drawPolygon(QPolygonF([p2, arrow_p1, arrow_p2]))

        painter.end()

__init__(parent=None)

Initialize the trajectory overlay widget.

Parameters:

Name Type Description Default
parent QWidget | None

Parent widget (typically the board widget).

None
Return

None

Source code in python/ui/game_page.py
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
def __init__(self, parent=None):
    """Initialize the trajectory overlay widget.

    Args:
        parent (QWidget | None): Parent widget (typically the board widget).

    Return:
        None
    """
    super().__init__(parent)
    self.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents)
    self.setAttribute(Qt.WidgetAttribute.WA_NoSystemBackground)
    self.trajectory = []  # list of (x, y) in 1-based board coords
    self.player_color = chess.WHITE

clear_trajectory()

Clear the currently displayed trajectory.

Return

None

Source code in python/ui/game_page.py
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
def clear_trajectory(self):
    """Clear the currently displayed trajectory.

    Args:
        None

    Return:
        None
    """
    self.trajectory = []
    self.update()

paintEvent(event)

Paint the trajectory overlay on top of the board.

Parameters:

Name Type Description Default
event

Qt paint event.

required
Return

None

Source code in python/ui/game_page.py
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
def paintEvent(self, event):
    """Paint the trajectory overlay on top of the board.

    Args:
        event: Qt paint event.

    Return:
        None
    """
    if len(self.trajectory) < 2:
        return

    painter = QPainter(self)
    painter.setRenderHint(QPainter.RenderHint.Antialiasing)

    pen = QPen(self.TRAJECTORY_COLOR, self.LINE_WIDTH)
    painter.setPen(pen)

    points = [self._to_pixel(x, y) for x, y in self.trajectory]

    # Draw path lines
    for i in range(len(points) - 1):
        if self.magnet_states[i] == False:
            painter.setPen(QPen(self.EAT_COLOR, self.LINE_WIDTH, Qt.PenStyle.DashLine))
            continue
        painter.drawLine(points[i], points[i + 1])

    # Draw dots at waypoints
    painter.setBrush(self.POINT_COLOR)
    painter.setPen(Qt.PenStyle.NoPen)
    for pt in points:
        painter.drawEllipse(pt, self.DOT_RADIUS, self.DOT_RADIUS)

    # Draw arrowhead at the final point
    if len(points) >= 2:
        p1 = points[-2]
        p2 = points[-1]
        angle = math.atan2(p2.y() - p1.y(), p2.x() - p1.x())
        arrow_p1 = QPointF(
            p2.x() - self.ARROW_SIZE * math.cos(angle - math.pi / 6),
            p2.y() - self.ARROW_SIZE * math.sin(angle - math.pi / 6),
        )
        arrow_p2 = QPointF(
            p2.x() - self.ARROW_SIZE * math.cos(angle + math.pi / 6),
            p2.y() - self.ARROW_SIZE * math.sin(angle + math.pi / 6),
        )
        painter.setBrush(self.TRAJECTORY_COLOR)
        painter.drawPolygon(QPolygonF([p2, arrow_p1, arrow_p2]))

    painter.end()

set_trajectory(path, player_color)

Set trajectory from a list of Command objects.

Parameters:

Name Type Description Default
path list[Command]

List of Command objects representing the move trajectory.

required
player_color bool

Player color to determine coordinate orientation (True for white, False for black).

required

Return: None

Source code in python/ui/game_page.py
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
def set_trajectory(self, path, player_color):
    """Set trajectory from a list of Command objects.

    Args:
        path (list[Command]): List of Command objects representing the move trajectory.
        player_color (bool): Player color to determine coordinate orientation (True for white, False for black).
    Return:
        None
    """
    self.trajectory = [(cmd.position.x, cmd.position.y) for cmd in path]
    self.magnet_states = [cmd.magnet_state for cmd in path]
    self.player_color = player_color
    self.update()

WaitForButtonWorker

Bases: QObject

Worker thread to wait for ESP button press without blocking the UI.

Source code in python/ui/game_page.py
 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
class WaitForButtonWorker(QObject):
    """Worker thread to wait for ESP button press without blocking the UI."""
    finished = pyqtSignal()
    error = pyqtSignal(str)

    def __init__(self, communication):
        """Initialize the button-wait worker.

        Args:
            communication: Communication instance used to wait for the ESP button press.

        Return:
            None
        """
        super().__init__()
        self.communication = communication
        self._stop_event = threading.Event()

    def cancel(self):
        """Request cancellation of the worker operation.

        Args:
            None
        Return:
            None
        """
        self._stop_event.set()

    def run(self):
        """Execute wait_for_button_press in the worker thread.

        Args: 
            None
        Return:
            None    
        """
        try:
            if self._stop_event.is_set():
                return
            result = self.communication.wait_for_button_press(stop_event=self._stop_event)
            if self._stop_event.is_set():
                return
            if result:
                self.finished.emit()
            else:
                self.error.emit("No button press detected")
        except Exception as e:
            self.error.emit(f"Error while waiting for button press: {str(e)}")

__init__(communication)

Initialize the button-wait worker.

Parameters:

Name Type Description Default
communication

Communication instance used to wait for the ESP button press.

required
Return

None

Source code in python/ui/game_page.py
85
86
87
88
89
90
91
92
93
94
95
96
def __init__(self, communication):
    """Initialize the button-wait worker.

    Args:
        communication: Communication instance used to wait for the ESP button press.

    Return:
        None
    """
    super().__init__()
    self.communication = communication
    self._stop_event = threading.Event()

cancel()

Request cancellation of the worker operation.

Return: None

Source code in python/ui/game_page.py
 98
 99
100
101
102
103
104
105
106
def cancel(self):
    """Request cancellation of the worker operation.

    Args:
        None
    Return:
        None
    """
    self._stop_event.set()

run()

Execute wait_for_button_press in the worker thread.

Return: None

Source code in python/ui/game_page.py
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
def run(self):
    """Execute wait_for_button_press in the worker thread.

    Args: 
        None
    Return:
        None    
    """
    try:
        if self._stop_event.is_set():
            return
        result = self.communication.wait_for_button_press(stop_event=self._stop_event)
        if self._stop_event.is_set():
            return
        if result:
            self.finished.emit()
        else:
            self.error.emit("No button press detected")
    except Exception as e:
        self.error.emit(f"Error while waiting for button press: {str(e)}")

Home Page

The home/welcome screen and game mode selection.

File for the home page of the application, which is the first page that the user sees when they open the app. It contains buttons to choose difficulty, start a new game, and view settings

HomePageController

Bases: QObject

Controller for home page user interactions and difficulty/color selection.

Source code in python/ui/home_page.py
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
class HomePageController(QObject):
    """Controller for home page user interactions and difficulty/color selection."""
    # Define signals that will be emitted when user wants to navigate
    start_game_signal = pyqtSignal()
    settings_signal = pyqtSignal()

    def __init__(self, chess_model):
        """Initialize home page controller with chess model.

        Args:
            chess_model: Chess game model instance.

        Return:
            None
        """
        super().__init__()
        self.chess_model = chess_model

    def easy_button_clicked(self):
        """Handle easy difficulty selection.

        Args:
            None

        Return:
            None
        """
        self.chess_model.set_difficulty("easy")

    def medium_button_clicked(self):
        """Handle medium difficulty selection.

        Args:
            None

        Return:
            None
        """
        self.chess_model.set_difficulty("medium")

    def hard_button_clicked(self):
        """Handle hard difficulty selection.

        Args:
            None

        Return:
            None
        """
        self.chess_model.set_difficulty("hard")    

    def time_3_button_clicked(self):
        """Handle 3 minute time control selection.

        Args:
            None

        Return:
            None
        """
        self.chess_model.set_time_control(3)

    def time_5_button_clicked(self):
        """Handle 5 minute time control selection.

        Args:
            None

        Return:
            None
        """
        self.chess_model.set_time_control(5)

    def time_10_button_clicked(self):
        """Handle 10 minute time control selection.

        Args:
            None

        Return:
            None
        """
        self.chess_model.set_time_control(10)

    def time_none_button_clicked(self):
        """Handle no time limit selection.

        Args:
            None

        Return:
            None
        """
        self.chess_model.set_time_control(0)

    def white_button_clicked(self):
        """Handle white color selection for player.

        Args:
            None

        Return:
            None
        """
        self.chess_model.set_player_color(chess.WHITE)

    def black_button_clicked(self):
        """Handle black color selection for player.

        Args:
            None

        Return:
            None
        """
        self.chess_model.set_player_color(chess.BLACK)

    def start_game(self):
        """Emit start game signal to navigate to game page.

        Args:
            None

        Return:
            None
        """
        # Emit the signal instead of directly calling a method
        self.start_game_signal.emit()    

    def settings_button_clicked(self):
        """Emit settings signal to navigate to settings page.

        Args:
            None

        Return:
            None
        """
        self.settings_signal.emit()

__init__(chess_model)

Initialize home page controller with chess model.

Parameters:

Name Type Description Default
chess_model

Chess game model instance.

required
Return

None

Source code in python/ui/home_page.py
449
450
451
452
453
454
455
456
457
458
459
def __init__(self, chess_model):
    """Initialize home page controller with chess model.

    Args:
        chess_model: Chess game model instance.

    Return:
        None
    """
    super().__init__()
    self.chess_model = chess_model

black_button_clicked()

Handle black color selection for player.

Return

None

Source code in python/ui/home_page.py
549
550
551
552
553
554
555
556
557
558
def black_button_clicked(self):
    """Handle black color selection for player.

    Args:
        None

    Return:
        None
    """
    self.chess_model.set_player_color(chess.BLACK)

easy_button_clicked()

Handle easy difficulty selection.

Return

None

Source code in python/ui/home_page.py
461
462
463
464
465
466
467
468
469
470
def easy_button_clicked(self):
    """Handle easy difficulty selection.

    Args:
        None

    Return:
        None
    """
    self.chess_model.set_difficulty("easy")

hard_button_clicked()

Handle hard difficulty selection.

Return

None

Source code in python/ui/home_page.py
483
484
485
486
487
488
489
490
491
492
def hard_button_clicked(self):
    """Handle hard difficulty selection.

    Args:
        None

    Return:
        None
    """
    self.chess_model.set_difficulty("hard")    

medium_button_clicked()

Handle medium difficulty selection.

Return

None

Source code in python/ui/home_page.py
472
473
474
475
476
477
478
479
480
481
def medium_button_clicked(self):
    """Handle medium difficulty selection.

    Args:
        None

    Return:
        None
    """
    self.chess_model.set_difficulty("medium")

settings_button_clicked()

Emit settings signal to navigate to settings page.

Return

None

Source code in python/ui/home_page.py
572
573
574
575
576
577
578
579
580
581
def settings_button_clicked(self):
    """Emit settings signal to navigate to settings page.

    Args:
        None

    Return:
        None
    """
    self.settings_signal.emit()

start_game()

Emit start game signal to navigate to game page.

Return

None

Source code in python/ui/home_page.py
560
561
562
563
564
565
566
567
568
569
570
def start_game(self):
    """Emit start game signal to navigate to game page.

    Args:
        None

    Return:
        None
    """
    # Emit the signal instead of directly calling a method
    self.start_game_signal.emit()    

time_10_button_clicked()

Handle 10 minute time control selection.

Return

None

Source code in python/ui/home_page.py
516
517
518
519
520
521
522
523
524
525
def time_10_button_clicked(self):
    """Handle 10 minute time control selection.

    Args:
        None

    Return:
        None
    """
    self.chess_model.set_time_control(10)

time_3_button_clicked()

Handle 3 minute time control selection.

Return

None

Source code in python/ui/home_page.py
494
495
496
497
498
499
500
501
502
503
def time_3_button_clicked(self):
    """Handle 3 minute time control selection.

    Args:
        None

    Return:
        None
    """
    self.chess_model.set_time_control(3)

time_5_button_clicked()

Handle 5 minute time control selection.

Return

None

Source code in python/ui/home_page.py
505
506
507
508
509
510
511
512
513
514
def time_5_button_clicked(self):
    """Handle 5 minute time control selection.

    Args:
        None

    Return:
        None
    """
    self.chess_model.set_time_control(5)

time_none_button_clicked()

Handle no time limit selection.

Return

None

Source code in python/ui/home_page.py
527
528
529
530
531
532
533
534
535
536
def time_none_button_clicked(self):
    """Handle no time limit selection.

    Args:
        None

    Return:
        None
    """
    self.chess_model.set_time_control(0)

white_button_clicked()

Handle white color selection for player.

Return

None

Source code in python/ui/home_page.py
538
539
540
541
542
543
544
545
546
547
def white_button_clicked(self):
    """Handle white color selection for player.

    Args:
        None

    Return:
        None
    """
    self.chess_model.set_player_color(chess.WHITE)

HomeView

Bases: QWidget

Home page view for difficulty selection and game initialization.

Source code in python/ui/home_page.py
 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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
class HomeView(QWidget):
    """Home page view for difficulty selection and game initialization."""

    def __init__(self, chess_model):
        """Initialize home page view with chess model instance.

        Args:
            chess_model: Chess game model instance.

        Return:
            None
        """
        super().__init__()
        self.chess_model = chess_model
        self.home_page_controller = HomePageController(chess_model)
        self._difficulty_buttons: list[QToolButton] = []
        self._difficulty_icon_paths: dict[str, str] = {}
        self._difficulty_trimmed_images: dict[str, QImage] = {}
        self._difficulty_icon_cache: dict[tuple[str, int, bool], QIcon] = {}
        self._difficulty_last_side: int | None = None
        self._difficulty_last_checked: dict[str, bool] = {}

        self._difficulty_update_pending = False
        self._difficulty_update_timer = QTimer(self)
        self._difficulty_update_timer.setSingleShot(True)
        self._difficulty_update_timer.timeout.connect(self._update_difficulty_buttons)
        self.init_ui()

    def init_ui(self):
        """Initialize home page UI layout with logo, difficulty, and color buttons.

        Args:
            None

        Return:
            None
        """
        logo_label = QLabel(self)
        logo_path = os.path.join(os.path.dirname(__file__), "assets/CNChess_logo.png")
        trimmed_logo = self._get_trimmed_image(logo_path)
        if trimmed_logo is not None:
            logo_pixmap = QPixmap.fromImage(trimmed_logo)
        else:
            logo_pixmap = QPixmap(logo_path)
        if not logo_pixmap.isNull():
            logo_pixmap = logo_pixmap.scaled(
                800,
                400,
                Qt.AspectRatioMode.KeepAspectRatio,
                Qt.TransformationMode.SmoothTransformation,
            )
            logo_label.setPixmap(logo_pixmap)
            logo_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
            # Prevent the logo label from expanding vertically when the window grows.
            logo_label.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Fixed)
            logo_label.setMinimumHeight(logo_pixmap.height())
            logo_label.setMaximumHeight(logo_pixmap.height())

        level_layout = self.build_level_buttons()
        time_layout = self.build_time_control_buttons()
        color_layout = self.build_color_buttons()
        menu_layout = self.build_menu_buttons()

        hbox_layout = QHBoxLayout()
        hbox_layout.addStretch(20)
        hbox_layout.addLayout(color_layout)
        hbox_layout.addSpacing(50)
        hbox_layout.addLayout(menu_layout)
        hbox_layout.addStretch(20)

        main_layout = QVBoxLayout()
        main_layout.addStretch(1)
        main_layout.addWidget(logo_label, alignment=Qt.AlignmentFlag.AlignHCenter)
        main_layout.addSpacing(75)
        main_layout.addLayout(level_layout)
        main_layout.addSpacing(50)
        main_layout.addLayout(time_layout)
        main_layout.addSpacing(75)
        main_layout.addLayout(hbox_layout)
        # Ensure extra vertical space goes to the bottom when the window is large.
        main_layout.addStretch(1)
        self.setLayout(main_layout)

        self._update_difficulty_buttons()

    def _get_trimmed_image(self, image_path: str) -> QImage | None:
        """Get image with transparent areas trimmed.

        Args:
            image_path (str): Path to image file.

        Return:
            QImage: Trimmed image or None if image not found.
        """
        cached = self._difficulty_trimmed_images.get(image_path)
        if cached is not None:
            return cached

        pixmap = QPixmap(image_path)
        if pixmap.isNull():
            return None

        image = pixmap.toImage().convertToFormat(QImage.Format.Format_ARGB32)
        rect = image.rect()
        left = rect.right()
        right = rect.left()
        top = rect.bottom()
        bottom = rect.top()
        found = False

        alpha_threshold = 10
        for y in range(rect.top(), rect.bottom() + 1):
            for x in range(rect.left(), rect.right() + 1):
                if image.pixelColor(x, y).alpha() > alpha_threshold:
                    found = True
                    if x < left:
                        left = x
                    if x > right:
                        right = x
                    if y < top:
                        top = y
                    if y > bottom:
                        bottom = y

        if found and right >= left and bottom >= top:
            image = image.copy(left, top, (right - left + 1), (bottom - top + 1))

        self._difficulty_trimmed_images[image_path] = image
        return image

    def _make_filled_square_icon(self, image_path: str, target_size: QSize, *, darken: bool = False) -> QIcon:
        """Create filled square icon from image file.

        Args:
            image_path (str): Path to image file.
            target_size (QSize): Target size for icon.
            darken (bool): Whether to darken icon (default False).

        Return:
            QIcon: Generated icon.
        """
        side = int(target_size.width())
        cache_key = (image_path, side, darken)
        cached_icon = self._difficulty_icon_cache.get(cache_key)
        if cached_icon is not None:
            return cached_icon

        trimmed = self._get_trimmed_image(image_path)
        if trimmed is None:
            return QIcon()

        pixmap = QPixmap.fromImage(trimmed)

        scaled = pixmap.scaled(
            target_size,
            Qt.AspectRatioMode.KeepAspectRatioByExpanding,
            Qt.TransformationMode.SmoothTransformation,
        )

        x = max(0, (scaled.width() - target_size.width()) // 2)
        y = max(0, (scaled.height() - target_size.height()) // 2)
        cropped = scaled.copy(x, y, target_size.width(), target_size.height())

        if darken:
            painter = QPainter(cropped)
            painter.setCompositionMode(QPainter.CompositionMode.CompositionMode_SourceAtop)
            painter.fillRect(cropped.rect(), QColor(0, 0, 0, 110))
            painter.end()

        icon = QIcon(cropped)
        self._difficulty_icon_cache[cache_key] = icon
        return icon

    def _update_difficulty_buttons(self) -> None:
        """Update difficulty button icons based on current window size and selection state.

        Args:
            None

        Return:
            None
        """
        self._difficulty_update_pending = False
        if not self._difficulty_buttons:
            return

        # Estimate a responsive square size based on current window width.
        # Keep it within a sensible range so it doesn't get huge.
        side = int((self.width() - 200) / 3)
        side = max(90, min(220, side))
        target = QSize(side, side)

        checked_now = {b.objectName(): b.isChecked() for b in self._difficulty_buttons}
        if self._difficulty_last_side == side and self._difficulty_last_checked == checked_now:
            return

        self._difficulty_last_side = side
        self._difficulty_last_checked = checked_now

        for button in self._difficulty_buttons:
            button.setFixedSize(target)
            button.setIconSize(target)
            path = self._difficulty_icon_paths.get(button.objectName())
            if path:
                button.setIcon(self._make_filled_square_icon(path, target, darken=button.isChecked()))


    def resizeEvent(self, event):
        """Handle window resize events and coalesce frequent updates.

        Args:
            event: Resize event.

        Return:
            None
        """
        super().resizeEvent(event)
        # Coalesce frequent resize events
        if not self._difficulty_update_pending:
            self._difficulty_update_pending = True
        self._difficulty_update_timer.start(40)

    def build_level_buttons(self):
        """Build difficulty level selection buttons (Easy, Medium, Hard).

        Args:
            None

        Return:
            QHBoxLayout: Layout containing difficulty buttons.
        """
        level_button_size = QSize(175, 175)

        easy_button = QToolButton(self)
        easy_button.setObjectName("difficultyEasy")
        easy_button.setCheckable(True)
        easy_button.setAutoRaise(True)
        easy_button.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonIconOnly)
        easy_path = os.path.join(os.path.dirname(__file__), "assets", "easy_icon.png")
        self._difficulty_icon_paths[easy_button.objectName()] = easy_path
        easy_icon = self._make_filled_square_icon(easy_path, level_button_size)
        easy_button.setIcon(easy_icon)
        easy_button.setIconSize(level_button_size)
        easy_button.setFixedSize(level_button_size)
        easy_button.setFocusPolicy(Qt.FocusPolicy.NoFocus)

        medium_button = QToolButton(self)
        medium_button.setObjectName("difficultyMedium")
        medium_button.setCheckable(True)
        medium_button.setAutoRaise(True)
        medium_button.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonIconOnly)
        medium_path = os.path.join(os.path.dirname(__file__), "assets", "intermediate_icon.png")
        self._difficulty_icon_paths[medium_button.objectName()] = medium_path
        medium_icon = self._make_filled_square_icon(medium_path, level_button_size)
        medium_button.setIcon(medium_icon)
        medium_button.setIconSize(level_button_size)
        medium_button.setFixedSize(level_button_size)
        medium_button.setFocusPolicy(Qt.FocusPolicy.NoFocus)

        hard_button = QToolButton(self)
        hard_button.setObjectName("difficultyHard")
        hard_button.setCheckable(True)
        hard_button.setAutoRaise(True)
        hard_button.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonIconOnly)
        hard_path = os.path.join(os.path.dirname(__file__), "assets", "hard_icon.png")
        self._difficulty_icon_paths[hard_button.objectName()] = hard_path
        hard_icon = self._make_filled_square_icon(hard_path, level_button_size)
        hard_button.setIcon(hard_icon)
        hard_button.setIconSize(level_button_size)
        hard_button.setFixedSize(level_button_size)
        hard_button.setFocusPolicy(Qt.FocusPolicy.NoFocus)

        self._difficulty_buttons = [easy_button, medium_button, hard_button]

        # Update icons whenever selection changes (checked state)
        easy_button.toggled.connect(lambda _checked: self._update_difficulty_buttons())
        medium_button.toggled.connect(lambda _checked: self._update_difficulty_buttons())
        hard_button.toggled.connect(lambda _checked: self._update_difficulty_buttons())

        easy_button.clicked.connect(self.home_page_controller.easy_button_clicked)
        medium_button.clicked.connect(self.home_page_controller.medium_button_clicked)
        hard_button.clicked.connect(self.home_page_controller.hard_button_clicked)

        level_group = QButtonGroup(self)
        level_group.addButton(easy_button)
        level_group.addButton(medium_button)
        level_group.addButton(hard_button)
        level_group.setExclusive(True)
        easy_button.setChecked(True)

        layout = QHBoxLayout()
        layout.addStretch(50)
        layout.addWidget(easy_button)
        layout.addWidget(medium_button)
        layout.addWidget(hard_button)
        layout.addStretch(50)

        return layout

    def build_time_control_buttons(self):
        """Build time control selection buttons (3 min, 5 min, 10 min, No limit).

        Args:
            None

        Return:
            QHBoxLayout: Layout containing time control buttons.
        """
        time_3_button = QPushButton("3 MIN", self)
        time_3_button.setCheckable(True)
        time_3_button.setObjectName("time_button")
        time_3_button.setMinimumSize(120, 50)
        time_3_button.clicked.connect(self.home_page_controller.time_3_button_clicked)

        time_5_button = QPushButton("5 MIN", self)
        time_5_button.setCheckable(True)
        time_5_button.setObjectName("time_button")
        time_5_button.setMinimumSize(120, 50)
        time_5_button.clicked.connect(self.home_page_controller.time_5_button_clicked)

        time_10_button = QPushButton("10 MIN", self)
        time_10_button.setCheckable(True)
        time_10_button.setObjectName("time_button")
        time_10_button.setMinimumSize(120, 50)
        time_10_button.clicked.connect(self.home_page_controller.time_10_button_clicked)

        time_none_button = QPushButton("NO LIMIT", self)
        time_none_button.setCheckable(True)
        time_none_button.setObjectName("time_button")
        time_none_button.setMinimumSize(120, 50)
        time_none_button.clicked.connect(self.home_page_controller.time_none_button_clicked)

        time_group = QButtonGroup(self)
        time_group.addButton(time_3_button)
        time_group.addButton(time_5_button)
        time_group.addButton(time_10_button)
        time_group.addButton(time_none_button)
        time_group.setExclusive(True)
        time_none_button.setChecked(True)

        layout = QHBoxLayout()
        layout.addStretch(50)
        layout.addWidget(time_3_button)
        layout.addWidget(time_5_button)
        layout.addWidget(time_10_button)
        layout.addWidget(time_none_button)
        layout.addStretch(50)

        return layout

    def build_color_buttons(self):
        """Build player color selection buttons (White, Black).

        Args:
            None

        Return:
            QHBoxLayout: Layout containing color selection buttons.
        """
        color_button_size = QSize(100, 100)
        color_icon_size = color_button_size + QSize(50, 50)

        white_button = QToolButton(self)
        white_button.setObjectName("colorWhite")
        white_button.setCheckable(True)
        white_button.setAutoRaise(True)
        white_button.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonIconOnly)
        white_path = os.path.join(os.path.dirname(__file__), "assets", "white_pawn_icon.png")
        white_trimmed = self._get_trimmed_image(white_path)
        if white_trimmed is not None:
            white_pixmap = QPixmap.fromImage(white_trimmed)
        else:
            white_pixmap = QPixmap(white_path)

        white_button.setIcon(QIcon(white_pixmap))
        white_button.setIconSize(color_icon_size)

        black_button = QToolButton(self)
        black_button.setObjectName("colorBlack")
        black_button.setCheckable(True)
        black_button.setAutoRaise(True)
        black_button.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonIconOnly)
        black_path = os.path.join(os.path.dirname(__file__), "assets", "black_pawn_icon.png")
        black_trimmed = self._get_trimmed_image(black_path)
        if black_trimmed is not None:
            black_pixmap = QPixmap.fromImage(black_trimmed)
        else:
            black_pixmap = QPixmap(black_path)
        black_button.setIcon(QIcon(black_pixmap))
        black_button.setIconSize(color_icon_size)

        white_button.clicked.connect(self.home_page_controller.white_button_clicked)
        black_button.clicked.connect(self.home_page_controller.black_button_clicked)

        color_group = QButtonGroup(self)
        color_group.addButton(white_button)
        color_group.addButton(black_button)
        color_group.setExclusive(True)
        white_button.setChecked(True)

        layout = QHBoxLayout()
        layout.addWidget(white_button)
        layout.addWidget(black_button)

        return layout

    def build_menu_buttons(self):
        """Build menu buttons (Start Game, Settings).

        Args:
            None

        Return:
            QVBoxLayout: Layout containing menu buttons.
        """
        start_button = QPushButton("START GAME", self)
        start_button.clicked.connect(self.home_page_controller.start_game)
        start_button.setObjectName("menu_button")
        start_button.setMinimumSize(200, 60)

        settings_button = QPushButton("SETTINGS", self)
        settings_button.clicked.connect(self.home_page_controller.settings_button_clicked)
        settings_button.setObjectName("menu_button")
        settings_button.setMinimumSize(200, 60)

        layout = QVBoxLayout()
        layout.addWidget(start_button, alignment=Qt.AlignmentFlag.AlignHCenter)
        layout.addWidget(settings_button, alignment=Qt.AlignmentFlag.AlignHCenter)

        return layout

__init__(chess_model)

Initialize home page view with chess model instance.

Parameters:

Name Type Description Default
chess_model

Chess game model instance.

required
Return

None

Source code in python/ui/home_page.py
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
def __init__(self, chess_model):
    """Initialize home page view with chess model instance.

    Args:
        chess_model: Chess game model instance.

    Return:
        None
    """
    super().__init__()
    self.chess_model = chess_model
    self.home_page_controller = HomePageController(chess_model)
    self._difficulty_buttons: list[QToolButton] = []
    self._difficulty_icon_paths: dict[str, str] = {}
    self._difficulty_trimmed_images: dict[str, QImage] = {}
    self._difficulty_icon_cache: dict[tuple[str, int, bool], QIcon] = {}
    self._difficulty_last_side: int | None = None
    self._difficulty_last_checked: dict[str, bool] = {}

    self._difficulty_update_pending = False
    self._difficulty_update_timer = QTimer(self)
    self._difficulty_update_timer.setSingleShot(True)
    self._difficulty_update_timer.timeout.connect(self._update_difficulty_buttons)
    self.init_ui()

build_color_buttons()

Build player color selection buttons (White, Black).

Return

QHBoxLayout: Layout containing color selection buttons.

Source code in python/ui/home_page.py
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
def build_color_buttons(self):
    """Build player color selection buttons (White, Black).

    Args:
        None

    Return:
        QHBoxLayout: Layout containing color selection buttons.
    """
    color_button_size = QSize(100, 100)
    color_icon_size = color_button_size + QSize(50, 50)

    white_button = QToolButton(self)
    white_button.setObjectName("colorWhite")
    white_button.setCheckable(True)
    white_button.setAutoRaise(True)
    white_button.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonIconOnly)
    white_path = os.path.join(os.path.dirname(__file__), "assets", "white_pawn_icon.png")
    white_trimmed = self._get_trimmed_image(white_path)
    if white_trimmed is not None:
        white_pixmap = QPixmap.fromImage(white_trimmed)
    else:
        white_pixmap = QPixmap(white_path)

    white_button.setIcon(QIcon(white_pixmap))
    white_button.setIconSize(color_icon_size)

    black_button = QToolButton(self)
    black_button.setObjectName("colorBlack")
    black_button.setCheckable(True)
    black_button.setAutoRaise(True)
    black_button.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonIconOnly)
    black_path = os.path.join(os.path.dirname(__file__), "assets", "black_pawn_icon.png")
    black_trimmed = self._get_trimmed_image(black_path)
    if black_trimmed is not None:
        black_pixmap = QPixmap.fromImage(black_trimmed)
    else:
        black_pixmap = QPixmap(black_path)
    black_button.setIcon(QIcon(black_pixmap))
    black_button.setIconSize(color_icon_size)

    white_button.clicked.connect(self.home_page_controller.white_button_clicked)
    black_button.clicked.connect(self.home_page_controller.black_button_clicked)

    color_group = QButtonGroup(self)
    color_group.addButton(white_button)
    color_group.addButton(black_button)
    color_group.setExclusive(True)
    white_button.setChecked(True)

    layout = QHBoxLayout()
    layout.addWidget(white_button)
    layout.addWidget(black_button)

    return layout

build_level_buttons()

Build difficulty level selection buttons (Easy, Medium, Hard).

Return

QHBoxLayout: Layout containing difficulty buttons.

Source code in python/ui/home_page.py
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
def build_level_buttons(self):
    """Build difficulty level selection buttons (Easy, Medium, Hard).

    Args:
        None

    Return:
        QHBoxLayout: Layout containing difficulty buttons.
    """
    level_button_size = QSize(175, 175)

    easy_button = QToolButton(self)
    easy_button.setObjectName("difficultyEasy")
    easy_button.setCheckable(True)
    easy_button.setAutoRaise(True)
    easy_button.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonIconOnly)
    easy_path = os.path.join(os.path.dirname(__file__), "assets", "easy_icon.png")
    self._difficulty_icon_paths[easy_button.objectName()] = easy_path
    easy_icon = self._make_filled_square_icon(easy_path, level_button_size)
    easy_button.setIcon(easy_icon)
    easy_button.setIconSize(level_button_size)
    easy_button.setFixedSize(level_button_size)
    easy_button.setFocusPolicy(Qt.FocusPolicy.NoFocus)

    medium_button = QToolButton(self)
    medium_button.setObjectName("difficultyMedium")
    medium_button.setCheckable(True)
    medium_button.setAutoRaise(True)
    medium_button.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonIconOnly)
    medium_path = os.path.join(os.path.dirname(__file__), "assets", "intermediate_icon.png")
    self._difficulty_icon_paths[medium_button.objectName()] = medium_path
    medium_icon = self._make_filled_square_icon(medium_path, level_button_size)
    medium_button.setIcon(medium_icon)
    medium_button.setIconSize(level_button_size)
    medium_button.setFixedSize(level_button_size)
    medium_button.setFocusPolicy(Qt.FocusPolicy.NoFocus)

    hard_button = QToolButton(self)
    hard_button.setObjectName("difficultyHard")
    hard_button.setCheckable(True)
    hard_button.setAutoRaise(True)
    hard_button.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonIconOnly)
    hard_path = os.path.join(os.path.dirname(__file__), "assets", "hard_icon.png")
    self._difficulty_icon_paths[hard_button.objectName()] = hard_path
    hard_icon = self._make_filled_square_icon(hard_path, level_button_size)
    hard_button.setIcon(hard_icon)
    hard_button.setIconSize(level_button_size)
    hard_button.setFixedSize(level_button_size)
    hard_button.setFocusPolicy(Qt.FocusPolicy.NoFocus)

    self._difficulty_buttons = [easy_button, medium_button, hard_button]

    # Update icons whenever selection changes (checked state)
    easy_button.toggled.connect(lambda _checked: self._update_difficulty_buttons())
    medium_button.toggled.connect(lambda _checked: self._update_difficulty_buttons())
    hard_button.toggled.connect(lambda _checked: self._update_difficulty_buttons())

    easy_button.clicked.connect(self.home_page_controller.easy_button_clicked)
    medium_button.clicked.connect(self.home_page_controller.medium_button_clicked)
    hard_button.clicked.connect(self.home_page_controller.hard_button_clicked)

    level_group = QButtonGroup(self)
    level_group.addButton(easy_button)
    level_group.addButton(medium_button)
    level_group.addButton(hard_button)
    level_group.setExclusive(True)
    easy_button.setChecked(True)

    layout = QHBoxLayout()
    layout.addStretch(50)
    layout.addWidget(easy_button)
    layout.addWidget(medium_button)
    layout.addWidget(hard_button)
    layout.addStretch(50)

    return layout

build_menu_buttons()

Build menu buttons (Start Game, Settings).

Return

QVBoxLayout: Layout containing menu buttons.

Source code in python/ui/home_page.py
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
def build_menu_buttons(self):
    """Build menu buttons (Start Game, Settings).

    Args:
        None

    Return:
        QVBoxLayout: Layout containing menu buttons.
    """
    start_button = QPushButton("START GAME", self)
    start_button.clicked.connect(self.home_page_controller.start_game)
    start_button.setObjectName("menu_button")
    start_button.setMinimumSize(200, 60)

    settings_button = QPushButton("SETTINGS", self)
    settings_button.clicked.connect(self.home_page_controller.settings_button_clicked)
    settings_button.setObjectName("menu_button")
    settings_button.setMinimumSize(200, 60)

    layout = QVBoxLayout()
    layout.addWidget(start_button, alignment=Qt.AlignmentFlag.AlignHCenter)
    layout.addWidget(settings_button, alignment=Qt.AlignmentFlag.AlignHCenter)

    return layout

build_time_control_buttons()

Build time control selection buttons (3 min, 5 min, 10 min, No limit).

Return

QHBoxLayout: Layout containing time control buttons.

Source code in python/ui/home_page.py
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
def build_time_control_buttons(self):
    """Build time control selection buttons (3 min, 5 min, 10 min, No limit).

    Args:
        None

    Return:
        QHBoxLayout: Layout containing time control buttons.
    """
    time_3_button = QPushButton("3 MIN", self)
    time_3_button.setCheckable(True)
    time_3_button.setObjectName("time_button")
    time_3_button.setMinimumSize(120, 50)
    time_3_button.clicked.connect(self.home_page_controller.time_3_button_clicked)

    time_5_button = QPushButton("5 MIN", self)
    time_5_button.setCheckable(True)
    time_5_button.setObjectName("time_button")
    time_5_button.setMinimumSize(120, 50)
    time_5_button.clicked.connect(self.home_page_controller.time_5_button_clicked)

    time_10_button = QPushButton("10 MIN", self)
    time_10_button.setCheckable(True)
    time_10_button.setObjectName("time_button")
    time_10_button.setMinimumSize(120, 50)
    time_10_button.clicked.connect(self.home_page_controller.time_10_button_clicked)

    time_none_button = QPushButton("NO LIMIT", self)
    time_none_button.setCheckable(True)
    time_none_button.setObjectName("time_button")
    time_none_button.setMinimumSize(120, 50)
    time_none_button.clicked.connect(self.home_page_controller.time_none_button_clicked)

    time_group = QButtonGroup(self)
    time_group.addButton(time_3_button)
    time_group.addButton(time_5_button)
    time_group.addButton(time_10_button)
    time_group.addButton(time_none_button)
    time_group.setExclusive(True)
    time_none_button.setChecked(True)

    layout = QHBoxLayout()
    layout.addStretch(50)
    layout.addWidget(time_3_button)
    layout.addWidget(time_5_button)
    layout.addWidget(time_10_button)
    layout.addWidget(time_none_button)
    layout.addStretch(50)

    return layout

init_ui()

Initialize home page UI layout with logo, difficulty, and color buttons.

Return

None

Source code in python/ui/home_page.py
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
def init_ui(self):
    """Initialize home page UI layout with logo, difficulty, and color buttons.

    Args:
        None

    Return:
        None
    """
    logo_label = QLabel(self)
    logo_path = os.path.join(os.path.dirname(__file__), "assets/CNChess_logo.png")
    trimmed_logo = self._get_trimmed_image(logo_path)
    if trimmed_logo is not None:
        logo_pixmap = QPixmap.fromImage(trimmed_logo)
    else:
        logo_pixmap = QPixmap(logo_path)
    if not logo_pixmap.isNull():
        logo_pixmap = logo_pixmap.scaled(
            800,
            400,
            Qt.AspectRatioMode.KeepAspectRatio,
            Qt.TransformationMode.SmoothTransformation,
        )
        logo_label.setPixmap(logo_pixmap)
        logo_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        # Prevent the logo label from expanding vertically when the window grows.
        logo_label.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Fixed)
        logo_label.setMinimumHeight(logo_pixmap.height())
        logo_label.setMaximumHeight(logo_pixmap.height())

    level_layout = self.build_level_buttons()
    time_layout = self.build_time_control_buttons()
    color_layout = self.build_color_buttons()
    menu_layout = self.build_menu_buttons()

    hbox_layout = QHBoxLayout()
    hbox_layout.addStretch(20)
    hbox_layout.addLayout(color_layout)
    hbox_layout.addSpacing(50)
    hbox_layout.addLayout(menu_layout)
    hbox_layout.addStretch(20)

    main_layout = QVBoxLayout()
    main_layout.addStretch(1)
    main_layout.addWidget(logo_label, alignment=Qt.AlignmentFlag.AlignHCenter)
    main_layout.addSpacing(75)
    main_layout.addLayout(level_layout)
    main_layout.addSpacing(50)
    main_layout.addLayout(time_layout)
    main_layout.addSpacing(75)
    main_layout.addLayout(hbox_layout)
    # Ensure extra vertical space goes to the bottom when the window is large.
    main_layout.addStretch(1)
    self.setLayout(main_layout)

    self._update_difficulty_buttons()

resizeEvent(event)

Handle window resize events and coalesce frequent updates.

Parameters:

Name Type Description Default
event

Resize event.

required
Return

None

Source code in python/ui/home_page.py
219
220
221
222
223
224
225
226
227
228
229
230
231
232
def resizeEvent(self, event):
    """Handle window resize events and coalesce frequent updates.

    Args:
        event: Resize event.

    Return:
        None
    """
    super().resizeEvent(event)
    # Coalesce frequent resize events
    if not self._difficulty_update_pending:
        self._difficulty_update_pending = True
    self._difficulty_update_timer.start(40)

Settings Page

Configuration interface for system settings and calibration.

GridView

Bases: QWidget

Grid visualization widget for gantry position display.

Source code in python/ui/settings_page.py
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
class GridView(QWidget):
    """Grid visualization widget for gantry position display."""
    x = 0
    y = grid_height_mm
    positionChanged = pyqtSignal(int, int)

    def __init__(self, parent=None):
        """Initialize grid view widget.

        Args:
            parent: Parent widget (optional).

        Return:
            None
        """
        super().__init__(parent)
        self.init()

    def init(self):
        """Initialize grid dimensions and styling.

        Args:
            None

        Return:
            None
        """
        self.setFixedSize(int(grid_width_mm), int(grid_height_mm))
        self.setStyleSheet("border: 2px solid white;")

    def paintEvent(self, event):
        """Paint grid with lines and position indicator dot.

        Args:
            event: Paint event.

        Return:
            None
        """
        painter = QPainter(self)
        # Paint background
        painter.fillRect(self.rect(), Qt.GlobalColor.black)

        # Paint border
        border_pen = QPen(Qt.GlobalColor.white, 2)
        painter.setPen(border_pen)
        painter.drawRect(0, 0, self.width() - 1, self.height() - 1)

        # Paint grid lines
        grid_pen = QPen(Qt.GlobalColor.white, 1)
        painter.setPen(grid_pen)
        for i in range(0, round(grid_width_mm), round(grid_width_mm/8.0)):
            start_point = QPoint(i, 0)
            end_point = QPoint(i, round(grid_height_mm))
            v_line = QLine(start_point, end_point)
            painter.drawLine(v_line)
        for j in range(0, round(grid_height_mm), round(grid_height_mm/8.0)):
            start_point = QPoint(0, j)
            end_point = QPoint(round(grid_width_mm), j)
            h_line = QLine(start_point, end_point)
            painter.drawLine(h_line)

        # Paint the red dot for current position
        dot_pen = QPen(Qt.GlobalColor.red, 6)
        painter.setPen(dot_pen)
        painter.drawPoint(int(getattr(self, 'x', 0)), int(getattr(self, 'y', 0)))

    def mousePressEvent(self, event):
        """Handle mouse clicks on grid to move gantry.

        Args:
            event: Mouse press event.

        Return:
            None
        """
        x = event.pos().x()
        y = event.pos().y()
        self.positionChanged.emit(x, y)
        self.update_dot(x, y)

    def update_dot(self, x, y):
        """Update position indicator dot.

        Args:
            x (int): X pixel coordinate.
            y (int): Y pixel coordinate.

        Return:
            None
        """
        self.x = x
        self.y = y
        self.update()

        self.painter.end()

    def mousePressEvent(self, event):
        self.x = int(event.position().x())
        self.y = int(event.position().y())
        self.positionChanged.emit(self.x, self.y)

    def update_dot(self, x, y):
        self.x = x
        self.y = y
        self.update()

__init__(parent=None)

Initialize grid view widget.

Parameters:

Name Type Description Default
parent

Parent widget (optional).

None
Return

None

Source code in python/ui/settings_page.py
673
674
675
676
677
678
679
680
681
682
683
def __init__(self, parent=None):
    """Initialize grid view widget.

    Args:
        parent: Parent widget (optional).

    Return:
        None
    """
    super().__init__(parent)
    self.init()

init()

Initialize grid dimensions and styling.

Return

None

Source code in python/ui/settings_page.py
685
686
687
688
689
690
691
692
693
694
695
def init(self):
    """Initialize grid dimensions and styling.

    Args:
        None

    Return:
        None
    """
    self.setFixedSize(int(grid_width_mm), int(grid_height_mm))
    self.setStyleSheet("border: 2px solid white;")

paintEvent(event)

Paint grid with lines and position indicator dot.

Parameters:

Name Type Description Default
event

Paint event.

required
Return

None

Source code in python/ui/settings_page.py
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
def paintEvent(self, event):
    """Paint grid with lines and position indicator dot.

    Args:
        event: Paint event.

    Return:
        None
    """
    painter = QPainter(self)
    # Paint background
    painter.fillRect(self.rect(), Qt.GlobalColor.black)

    # Paint border
    border_pen = QPen(Qt.GlobalColor.white, 2)
    painter.setPen(border_pen)
    painter.drawRect(0, 0, self.width() - 1, self.height() - 1)

    # Paint grid lines
    grid_pen = QPen(Qt.GlobalColor.white, 1)
    painter.setPen(grid_pen)
    for i in range(0, round(grid_width_mm), round(grid_width_mm/8.0)):
        start_point = QPoint(i, 0)
        end_point = QPoint(i, round(grid_height_mm))
        v_line = QLine(start_point, end_point)
        painter.drawLine(v_line)
    for j in range(0, round(grid_height_mm), round(grid_height_mm/8.0)):
        start_point = QPoint(0, j)
        end_point = QPoint(round(grid_width_mm), j)
        h_line = QLine(start_point, end_point)
        painter.drawLine(h_line)

    # Paint the red dot for current position
    dot_pen = QPen(Qt.GlobalColor.red, 6)
    painter.setPen(dot_pen)
    painter.drawPoint(int(getattr(self, 'x', 0)), int(getattr(self, 'y', 0)))

SendHomeWorker

Bases: QObject

Worker thread to send home command without blocking the UI.

Source code in python/ui/settings_page.py
 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
class SendHomeWorker(QObject):
    """Worker thread to send home command without blocking the UI."""
    finished = pyqtSignal()
    error = pyqtSignal(str)

    def __init__(self, communication):
        """Initialize worker with communication instance.

        Args:
            communication: Communication instance for sending commands.

        Return:
            None
        """
        super().__init__()
        self.communication = communication
        self._stop_event = threading.Event()

    def cancel(self):
        """Cancel current home operation.

        Args:
            None

        Return:
            None
        """
        self._stop_event.set()

    def run(self):
        """Execute go_home in the worker thread.

        Args:
            None

        Return:
            None
        """
        try:
            if self._stop_event.is_set():
                return
            self.communication.go_home(stop_event=self._stop_event)
            if self._stop_event.is_set():
                return
            self.finished.emit()
        except Exception as e:
            self.error.emit(str(e))

__init__(communication)

Initialize worker with communication instance.

Parameters:

Name Type Description Default
communication

Communication instance for sending commands.

required
Return

None

Source code in python/ui/settings_page.py
59
60
61
62
63
64
65
66
67
68
69
70
def __init__(self, communication):
    """Initialize worker with communication instance.

    Args:
        communication: Communication instance for sending commands.

    Return:
        None
    """
    super().__init__()
    self.communication = communication
    self._stop_event = threading.Event()

cancel()

Cancel current home operation.

Return

None

Source code in python/ui/settings_page.py
72
73
74
75
76
77
78
79
80
81
def cancel(self):
    """Cancel current home operation.

    Args:
        None

    Return:
        None
    """
    self._stop_event.set()

run()

Execute go_home in the worker thread.

Return

None

Source code in python/ui/settings_page.py
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
def run(self):
    """Execute go_home in the worker thread.

    Args:
        None

    Return:
        None
    """
    try:
        if self._stop_event.is_set():
            return
        self.communication.go_home(stop_event=self._stop_event)
        if self._stop_event.is_set():
            return
        self.finished.emit()
    except Exception as e:
        self.error.emit(str(e))

SendPositionWorker

Bases: QObject

Worker thread to send position commands without blocking the UI.

Source code in python/ui/settings_page.py
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
class SendPositionWorker(QObject):
    """Worker thread to send position commands without blocking the UI."""
    finished = pyqtSignal()
    error = pyqtSignal(str)

    def __init__(self, communication, position):
        """Initialize worker with communication and target position.

        Args:
            communication: Communication instance for sending commands.
            position (Position): Target position to send.

        Return:
            None
        """
        super().__init__()
        self.communication = communication
        self.position = position
        self._stop_event = threading.Event()

    def cancel(self):
        self._stop_event.set()

    def run(self):
        """Execute send_position in the worker thread."""
        try:
            if self._stop_event.is_set():
                return
            self.communication.send_position(self.position, relative=False, stop_event=self._stop_event)
            if self._stop_event.is_set():
                return
            self.finished.emit()
        except Exception as e:
            self.error.emit(str(e))

__init__(communication, position)

Initialize worker with communication and target position.

Parameters:

Name Type Description Default
communication

Communication instance for sending commands.

required
position Position

Target position to send.

required
Return

None

Source code in python/ui/settings_page.py
24
25
26
27
28
29
30
31
32
33
34
35
36
37
def __init__(self, communication, position):
    """Initialize worker with communication and target position.

    Args:
        communication: Communication instance for sending commands.
        position (Position): Target position to send.

    Return:
        None
    """
    super().__init__()
    self.communication = communication
    self.position = position
    self._stop_event = threading.Event()

run()

Execute send_position in the worker thread.

Source code in python/ui/settings_page.py
42
43
44
45
46
47
48
49
50
51
52
def run(self):
    """Execute send_position in the worker thread."""
    try:
        if self._stop_event.is_set():
            return
        self.communication.send_position(self.position, relative=False, stop_event=self._stop_event)
        if self._stop_event.is_set():
            return
        self.finished.emit()
    except Exception as e:
        self.error.emit(str(e))

SettingsController

Bases: QObject

Source code in python/ui/settings_page.py
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
class SettingsController(QObject):

    back_button_signal = pyqtSignal()

    def __init__(self, view, com, cam):
        """Initialize settings controller with view and hardware instances.

        Args:
            view (SettingsView): Settings view widget.
            com: Communication instance for device control.
            cam: Camera instance for image capture.

        Return:
            None
        """
        super().__init__()
        self.view = view
        self.com = com
        self.cam = cam

        # Initialize worker thread and waiting dialog
        self.send_position_worker = None
        self.send_position_thread = None
        self.send_home_worker = None
        self.send_home_thread = None
        self.waiting_dialog = WaitingDialog(self.view)
        self.active_operations = 0  # Counter to track concurrent operations
        self._is_shutting_down = False

    def cleanup_threads(self):
        """Clean up all worker threads in the controller."""
        self._is_shutting_down = True
        self.waiting_dialog.hide()

        if self.send_position_thread is not None:
            if self.send_position_worker is not None:
                self.send_position_worker.cancel()
            if self.send_position_thread.isRunning():
                print("[INFO] Stopping send_position thread...")
                self.send_position_thread.quit()
                self.send_position_thread.wait(2000)
            self.send_position_thread = None
            self.send_position_worker = None

        if self.send_home_thread is not None:
            if self.send_home_worker is not None:
                self.send_home_worker.cancel()
            if self.send_home_thread.isRunning():
                print("[INFO] Stopping send_home thread...")
                self.send_home_thread.quit()
                self.send_home_thread.wait(2000)
            self.send_home_thread = None
            self.send_home_worker = None

    def quit(self):
        """Cleanup and emit back button signal to return to previous page.

        Args:
            None

        Return:
            None
        """
        self.cleanup_threads()
        self.back_button_signal.emit()

    def send_position_async(self, position):
        """Send position to device asynchronously without blocking the UI."""
        if self._is_shutting_down:
            return

        # Wait for any previous thread to finish before starting a new one
        if self.send_position_thread is not None and self.send_position_thread.isRunning():
            if self.send_position_worker is not None:
                self.send_position_worker.cancel()
            self.send_position_thread.quit()
            self.send_position_thread.wait(2000)

        # Create worker and thread
        self.send_position_worker = SendPositionWorker(self.com, position)
        self.send_position_thread = QThread(parent=self)
        self.send_position_worker.moveToThread(self.send_position_thread)

        # Connect signals
        self.send_position_thread.started.connect(self.send_position_worker.run)
        self.send_position_worker.finished.connect(self.on_send_position_finished)
        self.send_position_worker.finished.connect(self.send_position_thread.quit)
        self.send_position_worker.error.connect(self.on_send_position_error)
        self.send_position_worker.error.connect(self.send_position_thread.quit)

        # Show waiting dialog and start thread
        self.active_operations += 1
        self.waiting_dialog.set_message("Sending position to device...\nPlease wait.")
        self.waiting_dialog.show()
        self.send_position_thread.start()

    def on_send_position_finished(self):
        """Handler when send_position completes successfully."""
        if self._is_shutting_down:
            return
        self.active_operations -= 1
        if self.active_operations <= 0:
            self.active_operations = 0
            self.waiting_dialog.hide()

    def on_send_position_error(self, error_msg):
        """Handler when send_position encounters an error."""
        if self._is_shutting_down:
            return
        self.active_operations -= 1
        if self.active_operations <= 0:
            self.active_operations = 0
            self.waiting_dialog.hide()
        print(f"Error sending position: {error_msg}")

    def go(self):
        pos = Position(float(self.view.x_spinner.value() + 0.5*SQUARE_SIZE_MM), float(self.view.y_spinner.value()+0.5*SQUARE_SIZE_MM))
        self.send_position_async(pos)

    def send_home_async(self):
        """Send home command to device asynchronously without blocking the UI."""
        if self._is_shutting_down:
            return

        # Wait for any previous thread to finish before starting a new one
        if self.send_home_thread is not None and self.send_home_thread.isRunning():
            if self.send_home_worker is not None:
                self.send_home_worker.cancel()
            self.send_home_thread.quit()
            self.send_home_thread.wait(2000)

        # Create worker and thread
        self.send_home_worker = SendHomeWorker(self.com)
        self.send_home_thread = QThread(parent=self)
        self.send_home_worker.moveToThread(self.send_home_thread)

        # Connect signals
        self.send_home_thread.started.connect(self.send_home_worker.run)
        self.send_home_worker.finished.connect(self.on_send_home_finished)
        self.send_home_worker.finished.connect(self.send_home_thread.quit)
        self.send_home_worker.error.connect(self.on_send_home_error)
        self.send_home_worker.error.connect(self.send_home_thread.quit)

        # Show waiting dialog and start thread
        self.active_operations += 1
        self.waiting_dialog.set_message("Sending home command...\nPlease wait.")
        self.waiting_dialog.show()
        self.send_home_thread.start()

    def on_send_home_finished(self):
        """Handler when send_home completes successfully."""
        if self._is_shutting_down:
            return
        self.active_operations -= 1
        if self.active_operations <= 0:
            self.active_operations = 0
            self.waiting_dialog.hide()

    def on_send_home_error(self, error_msg):
        """Handler when send_home encounters an error."""
        if self._is_shutting_down:
            return
        self.active_operations -= 1
        if self.active_operations <= 0:
            self.active_operations = 0
            self.waiting_dialog.hide()
        print(f"Error sending home command: {error_msg}")

    def home(self):
        """Home the gantry to origin position.

        Args:
            None

        Return:
            None
        """
        self.view.x_spinner.setValue(0.0)
        self.view.y_spinner.setValue(0.0)
        self.send_home_async()

    def stop(self):
        """Stop the gantry motor immediately.

        Args:
            None

        Return:
            None
        """
        self.com.stop()

    def z_move_up(self):
        """Move servo magnet up.

        Args:
            None

        Return:
            None
        """
        self.com.move_servo(True)

    def z_move_down(self):
        """Move servo magnet down.

        Args:
            None

        Return:
            None
        """
        self.com.move_servo(False)

    # def update_speed(self, value):
    #     self.speed_label.setText(f"Speed : {value}%")
    #     print(f"Speed set to {value}%")

    def take_picture(self):
        """Capture image from camera and display it.

        Args:
            None

        Return:
            None
        """
        image = self.cam.process_image()["warped_image"]
        display_image_with_grid = self.cam.squares.draw_grid(image, color=(0, 255, 0), thickness=2)

        img_path = os.path.join(os.path.dirname(__file__), 'assets', 'captured_image.jpg')
        cv2.imwrite(img_path, cv2.cvtColor(display_image_with_grid, cv2.COLOR_RGB2BGR))

        self.update_picture(img_path)

    def update_picture(self, img_path):
        """Update camera image display with new image.

        Args:
            image: New image to display.

        Return:
            None
        """
        pixmap = QPixmap(img_path)
        pixmap = pixmap.scaled(640, 480, Qt.AspectRatioMode.KeepAspectRatio)

        self.view.last_pic.setPixmap(pixmap)

    def calibrate_camera(self):
        """Launch camera calibration from UI.

        Args:
            None

        Return:
            None
        """
        self.cam.recalibrate_from_UI()

__init__(view, com, cam)

Initialize settings controller with view and hardware instances.

Parameters:

Name Type Description Default
view SettingsView

Settings view widget.

required
com

Communication instance for device control.

required
cam

Camera instance for image capture.

required
Return

None

Source code in python/ui/settings_page.py
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
def __init__(self, view, com, cam):
    """Initialize settings controller with view and hardware instances.

    Args:
        view (SettingsView): Settings view widget.
        com: Communication instance for device control.
        cam: Camera instance for image capture.

    Return:
        None
    """
    super().__init__()
    self.view = view
    self.com = com
    self.cam = cam

    # Initialize worker thread and waiting dialog
    self.send_position_worker = None
    self.send_position_thread = None
    self.send_home_worker = None
    self.send_home_thread = None
    self.waiting_dialog = WaitingDialog(self.view)
    self.active_operations = 0  # Counter to track concurrent operations
    self._is_shutting_down = False

calibrate_camera()

Launch camera calibration from UI.

Return

None

Source code in python/ui/settings_page.py
656
657
658
659
660
661
662
663
664
665
def calibrate_camera(self):
    """Launch camera calibration from UI.

    Args:
        None

    Return:
        None
    """
    self.cam.recalibrate_from_UI()

cleanup_threads()

Clean up all worker threads in the controller.

Source code in python/ui/settings_page.py
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
def cleanup_threads(self):
    """Clean up all worker threads in the controller."""
    self._is_shutting_down = True
    self.waiting_dialog.hide()

    if self.send_position_thread is not None:
        if self.send_position_worker is not None:
            self.send_position_worker.cancel()
        if self.send_position_thread.isRunning():
            print("[INFO] Stopping send_position thread...")
            self.send_position_thread.quit()
            self.send_position_thread.wait(2000)
        self.send_position_thread = None
        self.send_position_worker = None

    if self.send_home_thread is not None:
        if self.send_home_worker is not None:
            self.send_home_worker.cancel()
        if self.send_home_thread.isRunning():
            print("[INFO] Stopping send_home thread...")
            self.send_home_thread.quit()
            self.send_home_thread.wait(2000)
        self.send_home_thread = None
        self.send_home_worker = None

home()

Home the gantry to origin position.

Return

None

Source code in python/ui/settings_page.py
575
576
577
578
579
580
581
582
583
584
585
586
def home(self):
    """Home the gantry to origin position.

    Args:
        None

    Return:
        None
    """
    self.view.x_spinner.setValue(0.0)
    self.view.y_spinner.setValue(0.0)
    self.send_home_async()

on_send_home_error(error_msg)

Handler when send_home encounters an error.

Source code in python/ui/settings_page.py
565
566
567
568
569
570
571
572
573
def on_send_home_error(self, error_msg):
    """Handler when send_home encounters an error."""
    if self._is_shutting_down:
        return
    self.active_operations -= 1
    if self.active_operations <= 0:
        self.active_operations = 0
        self.waiting_dialog.hide()
    print(f"Error sending home command: {error_msg}")

on_send_home_finished()

Handler when send_home completes successfully.

Source code in python/ui/settings_page.py
556
557
558
559
560
561
562
563
def on_send_home_finished(self):
    """Handler when send_home completes successfully."""
    if self._is_shutting_down:
        return
    self.active_operations -= 1
    if self.active_operations <= 0:
        self.active_operations = 0
        self.waiting_dialog.hide()

on_send_position_error(error_msg)

Handler when send_position encounters an error.

Source code in python/ui/settings_page.py
512
513
514
515
516
517
518
519
520
def on_send_position_error(self, error_msg):
    """Handler when send_position encounters an error."""
    if self._is_shutting_down:
        return
    self.active_operations -= 1
    if self.active_operations <= 0:
        self.active_operations = 0
        self.waiting_dialog.hide()
    print(f"Error sending position: {error_msg}")

on_send_position_finished()

Handler when send_position completes successfully.

Source code in python/ui/settings_page.py
503
504
505
506
507
508
509
510
def on_send_position_finished(self):
    """Handler when send_position completes successfully."""
    if self._is_shutting_down:
        return
    self.active_operations -= 1
    if self.active_operations <= 0:
        self.active_operations = 0
        self.waiting_dialog.hide()

quit()

Cleanup and emit back button signal to return to previous page.

Return

None

Source code in python/ui/settings_page.py
461
462
463
464
465
466
467
468
469
470
471
def quit(self):
    """Cleanup and emit back button signal to return to previous page.

    Args:
        None

    Return:
        None
    """
    self.cleanup_threads()
    self.back_button_signal.emit()

send_home_async()

Send home command to device asynchronously without blocking the UI.

Source code in python/ui/settings_page.py
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
def send_home_async(self):
    """Send home command to device asynchronously without blocking the UI."""
    if self._is_shutting_down:
        return

    # Wait for any previous thread to finish before starting a new one
    if self.send_home_thread is not None and self.send_home_thread.isRunning():
        if self.send_home_worker is not None:
            self.send_home_worker.cancel()
        self.send_home_thread.quit()
        self.send_home_thread.wait(2000)

    # Create worker and thread
    self.send_home_worker = SendHomeWorker(self.com)
    self.send_home_thread = QThread(parent=self)
    self.send_home_worker.moveToThread(self.send_home_thread)

    # Connect signals
    self.send_home_thread.started.connect(self.send_home_worker.run)
    self.send_home_worker.finished.connect(self.on_send_home_finished)
    self.send_home_worker.finished.connect(self.send_home_thread.quit)
    self.send_home_worker.error.connect(self.on_send_home_error)
    self.send_home_worker.error.connect(self.send_home_thread.quit)

    # Show waiting dialog and start thread
    self.active_operations += 1
    self.waiting_dialog.set_message("Sending home command...\nPlease wait.")
    self.waiting_dialog.show()
    self.send_home_thread.start()

send_position_async(position)

Send position to device asynchronously without blocking the UI.

Source code in python/ui/settings_page.py
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
def send_position_async(self, position):
    """Send position to device asynchronously without blocking the UI."""
    if self._is_shutting_down:
        return

    # Wait for any previous thread to finish before starting a new one
    if self.send_position_thread is not None and self.send_position_thread.isRunning():
        if self.send_position_worker is not None:
            self.send_position_worker.cancel()
        self.send_position_thread.quit()
        self.send_position_thread.wait(2000)

    # Create worker and thread
    self.send_position_worker = SendPositionWorker(self.com, position)
    self.send_position_thread = QThread(parent=self)
    self.send_position_worker.moveToThread(self.send_position_thread)

    # Connect signals
    self.send_position_thread.started.connect(self.send_position_worker.run)
    self.send_position_worker.finished.connect(self.on_send_position_finished)
    self.send_position_worker.finished.connect(self.send_position_thread.quit)
    self.send_position_worker.error.connect(self.on_send_position_error)
    self.send_position_worker.error.connect(self.send_position_thread.quit)

    # Show waiting dialog and start thread
    self.active_operations += 1
    self.waiting_dialog.set_message("Sending position to device...\nPlease wait.")
    self.waiting_dialog.show()
    self.send_position_thread.start()

stop()

Stop the gantry motor immediately.

Return

None

Source code in python/ui/settings_page.py
588
589
590
591
592
593
594
595
596
597
def stop(self):
    """Stop the gantry motor immediately.

    Args:
        None

    Return:
        None
    """
    self.com.stop()

take_picture()

Capture image from camera and display it.

Return

None

Source code in python/ui/settings_page.py
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
def take_picture(self):
    """Capture image from camera and display it.

    Args:
        None

    Return:
        None
    """
    image = self.cam.process_image()["warped_image"]
    display_image_with_grid = self.cam.squares.draw_grid(image, color=(0, 255, 0), thickness=2)

    img_path = os.path.join(os.path.dirname(__file__), 'assets', 'captured_image.jpg')
    cv2.imwrite(img_path, cv2.cvtColor(display_image_with_grid, cv2.COLOR_RGB2BGR))

    self.update_picture(img_path)

update_picture(img_path)

Update camera image display with new image.

Parameters:

Name Type Description Default
image

New image to display.

required
Return

None

Source code in python/ui/settings_page.py
642
643
644
645
646
647
648
649
650
651
652
653
654
def update_picture(self, img_path):
    """Update camera image display with new image.

    Args:
        image: New image to display.

    Return:
        None
    """
    pixmap = QPixmap(img_path)
    pixmap = pixmap.scaled(640, 480, Qt.AspectRatioMode.KeepAspectRatio)

    self.view.last_pic.setPixmap(pixmap)

z_move_down()

Move servo magnet down.

Return

None

Source code in python/ui/settings_page.py
610
611
612
613
614
615
616
617
618
619
def z_move_down(self):
    """Move servo magnet down.

    Args:
        None

    Return:
        None
    """
    self.com.move_servo(False)

z_move_up()

Move servo magnet up.

Return

None

Source code in python/ui/settings_page.py
599
600
601
602
603
604
605
606
607
608
def z_move_up(self):
    """Move servo magnet up.

    Args:
        None

    Return:
        None
    """
    self.com.move_servo(True)

SettingsView

Bases: QWidget

Source code in python/ui/settings_page.py
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
class SettingsView(QWidget):

    def __init__(self, com=None, cam=None):
        """Initialize settings view with communication and camera instances.

        Args:
            com: Communication instance for device control.
            cam: Camera instance for image capture.

        Return:
            None
        """
        super().__init__()
        self._updating_spinners = False
        self.controller = SettingsController(self, com, cam)
        self.init_ui()

    def cleanup_threads(self):
        """Clean up all worker threads in the settings page."""
        self.controller.cleanup_threads()

    def init_ui(self):
        """Initialize settings page UI layout.

        Args:
            None

        Return:
            None
        """
        back_button = QPushButton("Back", self)
        back_button.clicked.connect(self.controller.quit)
        grid = self.build_grid()
        layout_coord = self.build_coord()
        layout_remoteXY = self.build_remoteXY()
        layout_controls = self.build_controls()
        camera_layout = self.build_camera()

        left_layout = QVBoxLayout()
        left_layout.addWidget(back_button, alignment=Qt.AlignmentFlag.AlignTop)
        middle_layout = QVBoxLayout()
        middle_layout.addWidget(grid, alignment=Qt.AlignmentFlag.AlignHCenter)
        middle_layout.addLayout(layout_coord)
        middle_layout.addLayout(layout_remoteXY)
        middle_layout.addLayout(layout_controls)

        main_layout = QHBoxLayout()
        main_layout.addLayout(left_layout)
        main_layout.addLayout(middle_layout)
        main_layout.addLayout(camera_layout)
        main_layout.setStretch(0, 0)
        main_layout.setStretch(1, 2)
        main_layout.setStretch(2, 2)

        self.setLayout(main_layout)

    def build_remoteXY(self):
        """Build XY axis manual movement control panel.

        Args:
            None

        Return:
            QHBoxLayout: Layout containing movement buttons and step control.
        """
        up_button = QPushButton("+Y", self)
        up_button.clicked.connect(self.move_up)

        down_button = QPushButton("-Y", self)
        down_button.clicked.connect(self.move_down)

        left_button = QPushButton("-X", self)
        left_button.clicked.connect(self.move_left)

        right_button = QPushButton("+X", self)
        right_button.clicked.connect(self.move_right)

        self.step_spinner = QDoubleSpinBox(self)
        self.step_spinner.setRange(0.0, 100.0)
        self.step_spinner.setSingleStep(1.0)
        self.step_spinner.setValue(5.0)

        z_up_button = QPushButton("+Z", self)
        z_up_button.clicked.connect(self.controller.z_move_up)
        z_down_button = QPushButton("-Z", self)
        z_down_button.clicked.connect(self.controller.z_move_down)

        grid_layout = QGridLayout()
        grid_layout.addWidget(up_button, 0, 1)
        grid_layout.addWidget(down_button, 2, 1)
        grid_layout.addWidget(left_button, 1, 0)
        grid_layout.addWidget(right_button, 1, 2)
        grid_layout.addWidget(self.step_spinner, 1, 1)

        vbox_layout = QVBoxLayout()
        vbox_layout.addWidget(z_up_button)
        vbox_layout.addWidget(z_down_button)

        layout = QHBoxLayout()
        layout.addLayout(grid_layout)
        layout.addLayout(vbox_layout)

        return layout

    def build_controls(self):
        """Build home and stop control buttons.

        Args:
            None

        Return:
            QVBoxLayout: Layout containing HOME and STOP buttons.
        """
        home_button = QPushButton("HOME", self)
        home_button.clicked.connect(self.controller.home)

        stop_button = QPushButton("STOP", self)
        stop_button.clicked.connect(self.controller.stop)

        layout = QVBoxLayout()
        layout.addWidget(home_button)
        layout.addWidget(stop_button)

        return layout

    def build_coord(self):
        """Build coordinate input spinners and GO button.

        Args:
            None

        Return:
            QHBoxLayout: Layout containing X/Y spinners and GO button.
        """
        self.x_spinner = QDoubleSpinBox(self)
        self.x_spinner.setRange(0.0, grid_width_mm)
        self.x_spinner.setSingleStep(1.0)
        self.x_spinner.setValue(0.0)
        self.x_spinner.setPrefix("X: ")
        self.x_spinner.valueChanged.connect(self.on_spinner_changed)

        self.y_spinner = QDoubleSpinBox(self)
        self.y_spinner.setRange(0.0, grid_height_mm)
        self.y_spinner.setSingleStep(1.0)
        self.y_spinner.setValue(0.0)
        self.y_spinner.setPrefix("Y: ")
        self.y_spinner.valueChanged.connect(self.on_spinner_changed)

        go_button = QPushButton("GO", self)
        go_button.clicked.connect(self.controller.go)

        layout = QHBoxLayout()
        layout.addWidget(self.x_spinner)
        layout.addWidget(self.y_spinner)
        layout.addWidget(go_button)

        return layout

    def build_grid(self):
        """Build grid display widget.

        Args:
            None

        Return:
            GridView: Grid visualization widget.
        """
        self.grid = GridView()
        self.grid.positionChanged.connect(self.update_coord)
        return self.grid

    def build_camera(self):
        """Build camera display and calibration section.

        Args:
            None

        Return:
            QVBoxLayout: Layout containing camera image and control buttons.
        """
        self.last_pic = QLabel(self)
        img_path = os.path.join(os.path.dirname(__file__), 'assets', 'captured_image.jpg')

        image = QPixmap(img_path)
        if not image.isNull():
            image = image.scaled(640, 480, Qt.AspectRatioMode.KeepAspectRatio)
        self.last_pic.setPixmap(image)

        pic_button = QPushButton("TAKE PICTURE", self)
        pic_button.clicked.connect(self.controller.take_picture)
        pic_button.setObjectName("camera_button")

        calib_button = QPushButton("CALIBRATE CAMERA", self)
        calib_button.clicked.connect(self.controller.calibrate_camera)
        calib_button.setObjectName("camera_button")

        layout = QVBoxLayout()
        layout.addStretch()
        layout.addWidget(self.last_pic, alignment=Qt.AlignmentFlag.AlignHCenter)
        layout.addSpacing(20)
        layout.addWidget(pic_button, alignment=Qt.AlignmentFlag.AlignHCenter)
        layout.addWidget(calib_button, alignment=Qt.AlignmentFlag.AlignHCenter)
        layout.addStretch()

        return layout

    def update_coord(self, x, y, computer_move=False):
        """Update coordinate spinners and grid position indicator.

        Args:
            x (float): X coordinate value.
            y (float): Y coordinate value.
            computer_move (bool): Whether this is a computer move (affects Y transformation).

        Return:
            None
        """
        self.view_updating_spinners = True
        self.x_spinner.setValue(float(x))
        if not computer_move:
            self.y_spinner.setValue(grid_height_mm - float(y))

        else :
            self.y_spinner.setValue(y)     
            y = grid_height_mm - float(y)
            x = x - SQUARE_SIZE_MM/2
            y = y - SQUARE_SIZE_MM/2 + SQUARE_SIZE_MM

        self._updating_spinners = False
        self.grid.update_dot(x,y)

    def on_spinner_changed(self):
        """Handle coordinate spinner value changes.

        Args:
            None

        Return:
            None
        """
        if self._updating_spinners:
            return
        x = self.x_spinner.value()
        y = abs(self.y_spinner.value() - grid_height_mm)
        self.grid.update_dot(x, y)

    def move_up(self):
        """Move gantry up (increase Y coordinate).

        Args:
            None

        Return:
            None
        """
        current_value = abs(self.y_spinner.value() - grid_height_mm)
        self.update_coord(self.x_spinner.value(), current_value - self.step_spinner.value())

    def move_down(self):
        """Move gantry down (decrease Y coordinate).

        Args:
            None

        Return:
            None
        """
        current_value = abs(self.y_spinner.value() - grid_height_mm)
        self.update_coord(self.x_spinner.value(), current_value + self.step_spinner.value())

    def move_left(self):
        """Move gantry left (decrease X coordinate).

        Args:
            None

        Return:
            None
        """
        current_value = self.x_spinner.value()
        self.update_coord(current_value - self.step_spinner.value(), abs(self.y_spinner.value() - grid_height_mm))

    def move_right(self):
        """Move gantry right (increase X coordinate).

        Args:
            None

        Return:
            None
        """
        current_value = self.x_spinner.value()
        self.update_coord(current_value + self.step_spinner.value(), abs(self.y_spinner.value() - grid_height_mm))

    def update_captured_image(self, img_path=os.path.join(os.path.dirname(__file__), 'assets', 'captured_image.jpg')):
        """Take picture and update image in view.

        Args:
            img_path (str): File path to new image.

        Return:
            None
        """
        self.controller.update_picture(img_path=img_path)

__init__(com=None, cam=None)

Initialize settings view with communication and camera instances.

Parameters:

Name Type Description Default
com

Communication instance for device control.

None
cam

Camera instance for image capture.

None
Return

None

Source code in python/ui/settings_page.py
104
105
106
107
108
109
110
111
112
113
114
115
116
117
def __init__(self, com=None, cam=None):
    """Initialize settings view with communication and camera instances.

    Args:
        com: Communication instance for device control.
        cam: Camera instance for image capture.

    Return:
        None
    """
    super().__init__()
    self._updating_spinners = False
    self.controller = SettingsController(self, com, cam)
    self.init_ui()

build_camera()

Build camera display and calibration section.

Return

QVBoxLayout: Layout containing camera image and control buttons.

Source code in python/ui/settings_page.py
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
def build_camera(self):
    """Build camera display and calibration section.

    Args:
        None

    Return:
        QVBoxLayout: Layout containing camera image and control buttons.
    """
    self.last_pic = QLabel(self)
    img_path = os.path.join(os.path.dirname(__file__), 'assets', 'captured_image.jpg')

    image = QPixmap(img_path)
    if not image.isNull():
        image = image.scaled(640, 480, Qt.AspectRatioMode.KeepAspectRatio)
    self.last_pic.setPixmap(image)

    pic_button = QPushButton("TAKE PICTURE", self)
    pic_button.clicked.connect(self.controller.take_picture)
    pic_button.setObjectName("camera_button")

    calib_button = QPushButton("CALIBRATE CAMERA", self)
    calib_button.clicked.connect(self.controller.calibrate_camera)
    calib_button.setObjectName("camera_button")

    layout = QVBoxLayout()
    layout.addStretch()
    layout.addWidget(self.last_pic, alignment=Qt.AlignmentFlag.AlignHCenter)
    layout.addSpacing(20)
    layout.addWidget(pic_button, alignment=Qt.AlignmentFlag.AlignHCenter)
    layout.addWidget(calib_button, alignment=Qt.AlignmentFlag.AlignHCenter)
    layout.addStretch()

    return layout

build_controls()

Build home and stop control buttons.

Return

QVBoxLayout: Layout containing HOME and STOP buttons.

Source code in python/ui/settings_page.py
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
def build_controls(self):
    """Build home and stop control buttons.

    Args:
        None

    Return:
        QVBoxLayout: Layout containing HOME and STOP buttons.
    """
    home_button = QPushButton("HOME", self)
    home_button.clicked.connect(self.controller.home)

    stop_button = QPushButton("STOP", self)
    stop_button.clicked.connect(self.controller.stop)

    layout = QVBoxLayout()
    layout.addWidget(home_button)
    layout.addWidget(stop_button)

    return layout

build_coord()

Build coordinate input spinners and GO button.

Return

QHBoxLayout: Layout containing X/Y spinners and GO button.

Source code in python/ui/settings_page.py
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
def build_coord(self):
    """Build coordinate input spinners and GO button.

    Args:
        None

    Return:
        QHBoxLayout: Layout containing X/Y spinners and GO button.
    """
    self.x_spinner = QDoubleSpinBox(self)
    self.x_spinner.setRange(0.0, grid_width_mm)
    self.x_spinner.setSingleStep(1.0)
    self.x_spinner.setValue(0.0)
    self.x_spinner.setPrefix("X: ")
    self.x_spinner.valueChanged.connect(self.on_spinner_changed)

    self.y_spinner = QDoubleSpinBox(self)
    self.y_spinner.setRange(0.0, grid_height_mm)
    self.y_spinner.setSingleStep(1.0)
    self.y_spinner.setValue(0.0)
    self.y_spinner.setPrefix("Y: ")
    self.y_spinner.valueChanged.connect(self.on_spinner_changed)

    go_button = QPushButton("GO", self)
    go_button.clicked.connect(self.controller.go)

    layout = QHBoxLayout()
    layout.addWidget(self.x_spinner)
    layout.addWidget(self.y_spinner)
    layout.addWidget(go_button)

    return layout

build_grid()

Build grid display widget.

Return

GridView: Grid visualization widget.

Source code in python/ui/settings_page.py
260
261
262
263
264
265
266
267
268
269
270
271
def build_grid(self):
    """Build grid display widget.

    Args:
        None

    Return:
        GridView: Grid visualization widget.
    """
    self.grid = GridView()
    self.grid.positionChanged.connect(self.update_coord)
    return self.grid

build_remoteXY()

Build XY axis manual movement control panel.

Return

QHBoxLayout: Layout containing movement buttons and step control.

Source code in python/ui/settings_page.py
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
def build_remoteXY(self):
    """Build XY axis manual movement control panel.

    Args:
        None

    Return:
        QHBoxLayout: Layout containing movement buttons and step control.
    """
    up_button = QPushButton("+Y", self)
    up_button.clicked.connect(self.move_up)

    down_button = QPushButton("-Y", self)
    down_button.clicked.connect(self.move_down)

    left_button = QPushButton("-X", self)
    left_button.clicked.connect(self.move_left)

    right_button = QPushButton("+X", self)
    right_button.clicked.connect(self.move_right)

    self.step_spinner = QDoubleSpinBox(self)
    self.step_spinner.setRange(0.0, 100.0)
    self.step_spinner.setSingleStep(1.0)
    self.step_spinner.setValue(5.0)

    z_up_button = QPushButton("+Z", self)
    z_up_button.clicked.connect(self.controller.z_move_up)
    z_down_button = QPushButton("-Z", self)
    z_down_button.clicked.connect(self.controller.z_move_down)

    grid_layout = QGridLayout()
    grid_layout.addWidget(up_button, 0, 1)
    grid_layout.addWidget(down_button, 2, 1)
    grid_layout.addWidget(left_button, 1, 0)
    grid_layout.addWidget(right_button, 1, 2)
    grid_layout.addWidget(self.step_spinner, 1, 1)

    vbox_layout = QVBoxLayout()
    vbox_layout.addWidget(z_up_button)
    vbox_layout.addWidget(z_down_button)

    layout = QHBoxLayout()
    layout.addLayout(grid_layout)
    layout.addLayout(vbox_layout)

    return layout

cleanup_threads()

Clean up all worker threads in the settings page.

Source code in python/ui/settings_page.py
119
120
121
def cleanup_threads(self):
    """Clean up all worker threads in the settings page."""
    self.controller.cleanup_threads()

init_ui()

Initialize settings page UI layout.

Return

None

Source code in python/ui/settings_page.py
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
def init_ui(self):
    """Initialize settings page UI layout.

    Args:
        None

    Return:
        None
    """
    back_button = QPushButton("Back", self)
    back_button.clicked.connect(self.controller.quit)
    grid = self.build_grid()
    layout_coord = self.build_coord()
    layout_remoteXY = self.build_remoteXY()
    layout_controls = self.build_controls()
    camera_layout = self.build_camera()

    left_layout = QVBoxLayout()
    left_layout.addWidget(back_button, alignment=Qt.AlignmentFlag.AlignTop)
    middle_layout = QVBoxLayout()
    middle_layout.addWidget(grid, alignment=Qt.AlignmentFlag.AlignHCenter)
    middle_layout.addLayout(layout_coord)
    middle_layout.addLayout(layout_remoteXY)
    middle_layout.addLayout(layout_controls)

    main_layout = QHBoxLayout()
    main_layout.addLayout(left_layout)
    main_layout.addLayout(middle_layout)
    main_layout.addLayout(camera_layout)
    main_layout.setStretch(0, 0)
    main_layout.setStretch(1, 2)
    main_layout.setStretch(2, 2)

    self.setLayout(main_layout)

move_down()

Move gantry down (decrease Y coordinate).

Return

None

Source code in python/ui/settings_page.py
360
361
362
363
364
365
366
367
368
369
370
def move_down(self):
    """Move gantry down (decrease Y coordinate).

    Args:
        None

    Return:
        None
    """
    current_value = abs(self.y_spinner.value() - grid_height_mm)
    self.update_coord(self.x_spinner.value(), current_value + self.step_spinner.value())

move_left()

Move gantry left (decrease X coordinate).

Return

None

Source code in python/ui/settings_page.py
372
373
374
375
376
377
378
379
380
381
382
def move_left(self):
    """Move gantry left (decrease X coordinate).

    Args:
        None

    Return:
        None
    """
    current_value = self.x_spinner.value()
    self.update_coord(current_value - self.step_spinner.value(), abs(self.y_spinner.value() - grid_height_mm))

move_right()

Move gantry right (increase X coordinate).

Return

None

Source code in python/ui/settings_page.py
384
385
386
387
388
389
390
391
392
393
394
def move_right(self):
    """Move gantry right (increase X coordinate).

    Args:
        None

    Return:
        None
    """
    current_value = self.x_spinner.value()
    self.update_coord(current_value + self.step_spinner.value(), abs(self.y_spinner.value() - grid_height_mm))

move_up()

Move gantry up (increase Y coordinate).

Return

None

Source code in python/ui/settings_page.py
348
349
350
351
352
353
354
355
356
357
358
def move_up(self):
    """Move gantry up (increase Y coordinate).

    Args:
        None

    Return:
        None
    """
    current_value = abs(self.y_spinner.value() - grid_height_mm)
    self.update_coord(self.x_spinner.value(), current_value - self.step_spinner.value())

on_spinner_changed()

Handle coordinate spinner value changes.

Return

None

Source code in python/ui/settings_page.py
333
334
335
336
337
338
339
340
341
342
343
344
345
346
def on_spinner_changed(self):
    """Handle coordinate spinner value changes.

    Args:
        None

    Return:
        None
    """
    if self._updating_spinners:
        return
    x = self.x_spinner.value()
    y = abs(self.y_spinner.value() - grid_height_mm)
    self.grid.update_dot(x, y)

update_captured_image(img_path=os.path.join(os.path.dirname(__file__), 'assets', 'captured_image.jpg'))

Take picture and update image in view.

Parameters:

Name Type Description Default
img_path str

File path to new image.

join(dirname(__file__), 'assets', 'captured_image.jpg')
Return

None

Source code in python/ui/settings_page.py
396
397
398
399
400
401
402
403
404
405
def update_captured_image(self, img_path=os.path.join(os.path.dirname(__file__), 'assets', 'captured_image.jpg')):
    """Take picture and update image in view.

    Args:
        img_path (str): File path to new image.

    Return:
        None
    """
    self.controller.update_picture(img_path=img_path)

update_coord(x, y, computer_move=False)

Update coordinate spinners and grid position indicator.

Parameters:

Name Type Description Default
x float

X coordinate value.

required
y float

Y coordinate value.

required
computer_move bool

Whether this is a computer move (affects Y transformation).

False
Return

None

Source code in python/ui/settings_page.py
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
def update_coord(self, x, y, computer_move=False):
    """Update coordinate spinners and grid position indicator.

    Args:
        x (float): X coordinate value.
        y (float): Y coordinate value.
        computer_move (bool): Whether this is a computer move (affects Y transformation).

    Return:
        None
    """
    self.view_updating_spinners = True
    self.x_spinner.setValue(float(x))
    if not computer_move:
        self.y_spinner.setValue(grid_height_mm - float(y))

    else :
        self.y_spinner.setValue(y)     
        y = grid_height_mm - float(y)
        x = x - SQUARE_SIZE_MM/2
        y = y - SQUARE_SIZE_MM/2 + SQUARE_SIZE_MM

    self._updating_spinners = False
    self.grid.update_dot(x,y)

Dialog Components

Popup dialogs for notifications and selections.

DrawDialog

Bases: QDialog

Dialog shown at end of game to announce a draw and offer play again or quit options.

Source code in python/ui/dialog_ui.py
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
class DrawDialog(QDialog):
    """Dialog shown at end of game to announce a draw and offer play again or quit options."""  

    def __init__(self, parent=None):
        """Initialize the draw dialog.
        Args:
            parent (QWidget | None): Optional parent widget.
        Return:
            None
        """
        super().__init__(parent)

        self.setWindowFlags(Qt.WindowType.FramelessWindowHint | Qt.WindowType.Dialog)
        self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
        self.setFixedSize(320, 225)
        self.setModal(True) 

        self.container = QFrame(self)
        self.container.setFixedSize(self.width(), self.height())

        # --- Updated Custom Styling (QSS) ---
        self.container.setStyleSheet("""
            QFrame {
                background-color: #2E4C3B; /* Sleek slate blue background */
                border: 2px solid #34495e; /* Slightly lighter blue border */
                border-radius: 15px;       
            }
            QLabel {
                color: #ffffff;
                border: none;
            }
            QPushButton {
                background-color: #4CAF50; /* Green play button */
                color: white;
                border-radius: 5px;
                padding: 10px 15px;
                font-weight: bold;
                font-size: 14px;
                border: none;
            }
            QPushButton:hover {
                background-color: #45a049;
            }
            QPushButton#quitBtn {          
                background-color: #f44336; /* Red quit button */
            }
            QPushButton#quitBtn:hover {
                background-color: #da190b;
            }
        """)

        main_layout = QVBoxLayout(self.container)
        button_layout = QHBoxLayout()
        image_layout = QHBoxLayout()

        message = f"DRAW"
        self.label = QLabel(message)
        self.label.setAlignment(Qt.AlignmentFlag.AlignCenter)

        font = self.label.font()
        font.setPointSize(18)
        font.setBold(True)
        self.label.setFont(font)

        self.white_image = QPixmap(f"ui/assets/chess_assets/pieces_png/white-king.png") 
        self.black_image = QPixmap(f"ui/assets/chess_assets/pieces_png/black-king.png")

        white_label = QLabel()
        white_label.setPixmap(self.white_image)
        black_label = QLabel()
        black_label.setPixmap(self.black_image)

        image_layout.addWidget(white_label)
        image_layout.addWidget(black_label)

        self.play_again_btn = QPushButton("Play Again")
        self.quit_btn = QPushButton("Quit")
        self.quit_btn.setObjectName("quitBtn") 

        self.play_again_btn.clicked.connect(self.accept) 
        self.quit_btn.clicked.connect(self.reject)       

        button_layout.addWidget(self.play_again_btn)
        button_layout.addWidget(self.quit_btn)

        main_layout.addWidget(self.label)
        main_layout.addLayout(image_layout)
        main_layout.addLayout(button_layout)

        dialog_layout = QVBoxLayout(self)
        dialog_layout.setContentsMargins(0, 0, 0, 0)
        dialog_layout.addWidget(self.container)

__init__(parent=None)

Initialize the draw dialog. Args: parent (QWidget | None): Optional parent widget. Return: None

Source code in python/ui/dialog_ui.py
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
def __init__(self, parent=None):
    """Initialize the draw dialog.
    Args:
        parent (QWidget | None): Optional parent widget.
    Return:
        None
    """
    super().__init__(parent)

    self.setWindowFlags(Qt.WindowType.FramelessWindowHint | Qt.WindowType.Dialog)
    self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
    self.setFixedSize(320, 225)
    self.setModal(True) 

    self.container = QFrame(self)
    self.container.setFixedSize(self.width(), self.height())

    # --- Updated Custom Styling (QSS) ---
    self.container.setStyleSheet("""
        QFrame {
            background-color: #2E4C3B; /* Sleek slate blue background */
            border: 2px solid #34495e; /* Slightly lighter blue border */
            border-radius: 15px;       
        }
        QLabel {
            color: #ffffff;
            border: none;
        }
        QPushButton {
            background-color: #4CAF50; /* Green play button */
            color: white;
            border-radius: 5px;
            padding: 10px 15px;
            font-weight: bold;
            font-size: 14px;
            border: none;
        }
        QPushButton:hover {
            background-color: #45a049;
        }
        QPushButton#quitBtn {          
            background-color: #f44336; /* Red quit button */
        }
        QPushButton#quitBtn:hover {
            background-color: #da190b;
        }
    """)

    main_layout = QVBoxLayout(self.container)
    button_layout = QHBoxLayout()
    image_layout = QHBoxLayout()

    message = f"DRAW"
    self.label = QLabel(message)
    self.label.setAlignment(Qt.AlignmentFlag.AlignCenter)

    font = self.label.font()
    font.setPointSize(18)
    font.setBold(True)
    self.label.setFont(font)

    self.white_image = QPixmap(f"ui/assets/chess_assets/pieces_png/white-king.png") 
    self.black_image = QPixmap(f"ui/assets/chess_assets/pieces_png/black-king.png")

    white_label = QLabel()
    white_label.setPixmap(self.white_image)
    black_label = QLabel()
    black_label.setPixmap(self.black_image)

    image_layout.addWidget(white_label)
    image_layout.addWidget(black_label)

    self.play_again_btn = QPushButton("Play Again")
    self.quit_btn = QPushButton("Quit")
    self.quit_btn.setObjectName("quitBtn") 

    self.play_again_btn.clicked.connect(self.accept) 
    self.quit_btn.clicked.connect(self.reject)       

    button_layout.addWidget(self.play_again_btn)
    button_layout.addWidget(self.quit_btn)

    main_layout.addWidget(self.label)
    main_layout.addLayout(image_layout)
    main_layout.addLayout(button_layout)

    dialog_layout = QVBoxLayout(self)
    dialog_layout.setContentsMargins(0, 0, 0, 0)
    dialog_layout.addWidget(self.container)

HoverIconToolButton

Bases: QToolButton

Source code in python/ui/dialog_ui.py
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
class HoverIconToolButton(QToolButton):
    def __init__(self, parent=None):
        """Create a tool button that swaps icons on hover.

        Args:
            parent (QWidget | None): Optional parent widget.

        Return:
            None
        """
        super().__init__(parent)
        self._normal_icon: QIcon | None = None
        self._hover_icon: QIcon | None = None
        self.setMouseTracking(True)
        self.setAttribute(Qt.WidgetAttribute.WA_Hover, True)

    @staticmethod
    def _darken_pixmap(pixmap: QPixmap, alpha: int = 90) -> QPixmap:
        """Return a darkened copy of a pixmap.

        Args:
            pixmap (QPixmap): Source pixmap.
            alpha (int): Darkness alpha (0-255). Higher means darker.

        Return:
            QPixmap: Darkened pixmap.
        """
        dark = QPixmap(pixmap.size())
        dark.fill(Qt.GlobalColor.transparent)

        painter = QPainter(dark)
        painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
        painter.drawPixmap(0, 0, pixmap)
        painter.setCompositionMode(QPainter.CompositionMode.CompositionMode_SourceAtop)
        painter.fillRect(dark.rect(), QColor(0, 0, 0, alpha))
        painter.end()
        return dark

    def setHoverIcons(self, normal_icon: QIcon, hover_icon: QIcon):
        """Set the icons used for normal and hover states.

        Args:
            normal_icon (QIcon): Icon displayed normally.
            hover_icon (QIcon): Icon displayed while hovering.

        Return:
            None
        """
        self._normal_icon = normal_icon
        self._hover_icon = hover_icon
        self.setIcon(normal_icon)

    def enterEvent(self, event):
        """Handle mouse enter by switching to the hover icon.
        Args:
            event: Qt enter event.
        Return:
            None
        """
        if self._hover_icon is not None:
            self.setIcon(self._hover_icon)
        return super().enterEvent(event)

    def leaveEvent(self, event):
        """Handle mouse leave by restoring the normal icon.
        Args:
            event: Qt leave event.
        Return:
            None
        """
        if self._normal_icon is not None:
            self.setIcon(self._normal_icon)
        return super().leaveEvent(event)

__init__(parent=None)

Create a tool button that swaps icons on hover.

Parameters:

Name Type Description Default
parent QWidget | None

Optional parent widget.

None
Return

None

Source code in python/ui/dialog_ui.py
105
106
107
108
109
110
111
112
113
114
115
116
117
118
def __init__(self, parent=None):
    """Create a tool button that swaps icons on hover.

    Args:
        parent (QWidget | None): Optional parent widget.

    Return:
        None
    """
    super().__init__(parent)
    self._normal_icon: QIcon | None = None
    self._hover_icon: QIcon | None = None
    self.setMouseTracking(True)
    self.setAttribute(Qt.WidgetAttribute.WA_Hover, True)

enterEvent(event)

Handle mouse enter by switching to the hover icon. Args: event: Qt enter event. Return: None

Source code in python/ui/dialog_ui.py
156
157
158
159
160
161
162
163
164
165
def enterEvent(self, event):
    """Handle mouse enter by switching to the hover icon.
    Args:
        event: Qt enter event.
    Return:
        None
    """
    if self._hover_icon is not None:
        self.setIcon(self._hover_icon)
    return super().enterEvent(event)

leaveEvent(event)

Handle mouse leave by restoring the normal icon. Args: event: Qt leave event. Return: None

Source code in python/ui/dialog_ui.py
167
168
169
170
171
172
173
174
175
176
def leaveEvent(self, event):
    """Handle mouse leave by restoring the normal icon.
    Args:
        event: Qt leave event.
    Return:
        None
    """
    if self._normal_icon is not None:
        self.setIcon(self._normal_icon)
    return super().leaveEvent(event)

setHoverIcons(normal_icon, hover_icon)

Set the icons used for normal and hover states.

Parameters:

Name Type Description Default
normal_icon QIcon

Icon displayed normally.

required
hover_icon QIcon

Icon displayed while hovering.

required
Return

None

Source code in python/ui/dialog_ui.py
142
143
144
145
146
147
148
149
150
151
152
153
154
def setHoverIcons(self, normal_icon: QIcon, hover_icon: QIcon):
    """Set the icons used for normal and hover states.

    Args:
        normal_icon (QIcon): Icon displayed normally.
        hover_icon (QIcon): Icon displayed while hovering.

    Return:
        None
    """
    self._normal_icon = normal_icon
    self._hover_icon = hover_icon
    self.setIcon(normal_icon)

InvalidMoveDialog

Bases: QDialog

Dialog showing invalid move message that automatically closes after 2 seconds.

Source code in python/ui/dialog_ui.py
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
class InvalidMoveDialog(QDialog):
    """Dialog showing invalid move message that automatically closes after 2 seconds."""

    def __init__(self, parent=None):
        """Initialize the invalid move dialog.
        Args:
            parent (QWidget | None): Optional parent widget.
        Return:
            None"""
        super().__init__(parent)

        self.setWindowFlags(Qt.WindowType.FramelessWindowHint | Qt.WindowType.Dialog)
        self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
        self.setFixedSize(300, 150)
        self.setModal(True)

        self.container = QFrame(self)
        self.container.setFixedSize(self.width(), self.height())

        # --- Custom Styling ---
        self.container.setStyleSheet("""
            QFrame {
                background-color: #8B0000; /* Dark red background */
                border: 2px solid #FF4444; /* Red border */
                border-radius: 15px;       
            }
            QLabel {
                color: #ffffff;
                border: none;
            }
        """)

        main_layout = QVBoxLayout(self.container)

        self.label = QLabel("INVALID MOVE")
        self.label.setAlignment(Qt.AlignmentFlag.AlignCenter)

        font = self.label.font()
        font.setPointSize(18)
        font.setBold(True)
        self.label.setFont(font)

        main_layout.addWidget(self.label)

        dialog_layout = QVBoxLayout(self)
        dialog_layout.setContentsMargins(0, 0, 0, 0)
        dialog_layout.addWidget(self.container)

        # Timer to auto-close after 2 seconds
        self.close_timer = QTimer(self)
        self.close_timer.timeout.connect(self.reject)
        self.close_timer.setSingleShot(True)
        self.close_timer.start(2000)  # 2000 milliseconds = 2 seconds

        # Center the dialog on parent
        if parent:
            parent_geometry = parent.geometry()
            self.move(
                parent_geometry.left() + (parent_geometry.width() - 300) // 2,
                parent_geometry.top() + (parent_geometry.height() - 150) // 2
            )

__init__(parent=None)

Initialize the invalid move dialog. Args: parent (QWidget | None): Optional parent widget. Return: None

Source code in python/ui/dialog_ui.py
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
def __init__(self, parent=None):
    """Initialize the invalid move dialog.
    Args:
        parent (QWidget | None): Optional parent widget.
    Return:
        None"""
    super().__init__(parent)

    self.setWindowFlags(Qt.WindowType.FramelessWindowHint | Qt.WindowType.Dialog)
    self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
    self.setFixedSize(300, 150)
    self.setModal(True)

    self.container = QFrame(self)
    self.container.setFixedSize(self.width(), self.height())

    # --- Custom Styling ---
    self.container.setStyleSheet("""
        QFrame {
            background-color: #8B0000; /* Dark red background */
            border: 2px solid #FF4444; /* Red border */
            border-radius: 15px;       
        }
        QLabel {
            color: #ffffff;
            border: none;
        }
    """)

    main_layout = QVBoxLayout(self.container)

    self.label = QLabel("INVALID MOVE")
    self.label.setAlignment(Qt.AlignmentFlag.AlignCenter)

    font = self.label.font()
    font.setPointSize(18)
    font.setBold(True)
    self.label.setFont(font)

    main_layout.addWidget(self.label)

    dialog_layout = QVBoxLayout(self)
    dialog_layout.setContentsMargins(0, 0, 0, 0)
    dialog_layout.addWidget(self.container)

    # Timer to auto-close after 2 seconds
    self.close_timer = QTimer(self)
    self.close_timer.timeout.connect(self.reject)
    self.close_timer.setSingleShot(True)
    self.close_timer.start(2000)  # 2000 milliseconds = 2 seconds

    # Center the dialog on parent
    if parent:
        parent_geometry = parent.geometry()
        self.move(
            parent_geometry.left() + (parent_geometry.width() - 300) // 2,
            parent_geometry.top() + (parent_geometry.height() - 150) // 2
        )

PromotionWidget

Bases: QDialog

Source code in python/ui/dialog_ui.py
 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
class PromotionWidget(QDialog): 

    promotion_signal = pyqtSignal(int)  # Signal to emit the chosen promotion piece as chess piece type (e.g., chess.QUEEN)

    def __init__(self, player_color):
        """Create the promotion choice dialog.
        Displays piece options (Q/R/B/N) and returns the selected promotion type.

        Args:
            player_color: Player color (chess.WHITE or chess.BLACK) used to choose correct piece icons.

        Return:
            None
        """
        super().__init__()

        self.setWindowTitle("")
        self.setWindowFlag(Qt.WindowType.FramelessWindowHint, True)
        self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground, True)
        self.setStyleSheet("QDialog { background: transparent; }")

        # Image-only promotion choices (no padding/background/border).
        button_size = QSize(56, 56)
        icon_size = QSize(56, 56)

        layout = QHBoxLayout()
        layout.setSpacing(0)
        layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(layout)

        self.piece_chosen_dict = {
            'Q': chess.QUEEN,
            'R': chess.ROOK,
            'B': chess.BISHOP,
            'N': chess.KNIGHT,}

        piece_name_map = {
            'Q': 'queen',
            'R': 'rook',
            'B': 'bishop',
            'N': 'knight',
        }

        color_prefix = 'white' if player_color == chess.WHITE else 'black'

        pieces = ['Q', 'R', 'B', 'N'] if player_color == chess.WHITE else ['q', 'r', 'b', 'n']
        for piece in pieces:
            piece_upper = piece.upper()
            filename = f"{color_prefix}-{piece_name_map[piece_upper]}.png"
            icon_path = os.path.join(os.path.dirname(__file__), "assets", "chess_assets", "pieces_png", filename)

            button = HoverIconToolButton(self)
            button.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonIconOnly)
            button.setAutoRaise(True)
            button.setFixedSize(button_size)
            button.setIconSize(icon_size)
            button.setFocusPolicy(Qt.FocusPolicy.NoFocus)
            button.setStyleSheet(
                "QToolButton { border: none; padding: 0px; margin: 0px; background: transparent; }"
                "QToolButton:hover { background: transparent; }"
                "QToolButton:pressed { background: transparent; }"
            )

            pixmap = QPixmap(icon_path)
            if not pixmap.isNull():
                normal_icon = QIcon(pixmap)
                hover_icon = QIcon(HoverIconToolButton._darken_pixmap(pixmap, alpha=90))
                button.setHoverIcons(normal_icon, hover_icon)
            else:
                # Fallback to text if asset missing
                button.setText(piece_upper)

            button.clicked.connect(lambda _checked=False, p=piece: self.promote(p))
            layout.addWidget(button)

        self.setFixedSize(
            (button_size.width() * len(pieces)) + (layout.spacing() * (len(pieces) - 1)) + layout.contentsMargins().left() + layout.contentsMargins().right(),
            button_size.height() + layout.contentsMargins().top() + layout.contentsMargins().bottom(),
        )

    def promote(self, piece):
        """Select a promotion piece and close the dialog.

        Args:
            piece (str): One of 'Q', 'R', 'B', 'N' (case-insensitive).

        Return:
            None
        """
        self.chosen_piece = self.piece_chosen_dict[piece.upper()]
        self.accept()  # Close the promotion dialog after selection    

__init__(player_color)

Create the promotion choice dialog. Displays piece options (Q/R/B/N) and returns the selected promotion type.

Parameters:

Name Type Description Default
player_color

Player color (chess.WHITE or chess.BLACK) used to choose correct piece icons.

required
Return

None

Source code in python/ui/dialog_ui.py
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
def __init__(self, player_color):
    """Create the promotion choice dialog.
    Displays piece options (Q/R/B/N) and returns the selected promotion type.

    Args:
        player_color: Player color (chess.WHITE or chess.BLACK) used to choose correct piece icons.

    Return:
        None
    """
    super().__init__()

    self.setWindowTitle("")
    self.setWindowFlag(Qt.WindowType.FramelessWindowHint, True)
    self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground, True)
    self.setStyleSheet("QDialog { background: transparent; }")

    # Image-only promotion choices (no padding/background/border).
    button_size = QSize(56, 56)
    icon_size = QSize(56, 56)

    layout = QHBoxLayout()
    layout.setSpacing(0)
    layout.setContentsMargins(0, 0, 0, 0)
    self.setLayout(layout)

    self.piece_chosen_dict = {
        'Q': chess.QUEEN,
        'R': chess.ROOK,
        'B': chess.BISHOP,
        'N': chess.KNIGHT,}

    piece_name_map = {
        'Q': 'queen',
        'R': 'rook',
        'B': 'bishop',
        'N': 'knight',
    }

    color_prefix = 'white' if player_color == chess.WHITE else 'black'

    pieces = ['Q', 'R', 'B', 'N'] if player_color == chess.WHITE else ['q', 'r', 'b', 'n']
    for piece in pieces:
        piece_upper = piece.upper()
        filename = f"{color_prefix}-{piece_name_map[piece_upper]}.png"
        icon_path = os.path.join(os.path.dirname(__file__), "assets", "chess_assets", "pieces_png", filename)

        button = HoverIconToolButton(self)
        button.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonIconOnly)
        button.setAutoRaise(True)
        button.setFixedSize(button_size)
        button.setIconSize(icon_size)
        button.setFocusPolicy(Qt.FocusPolicy.NoFocus)
        button.setStyleSheet(
            "QToolButton { border: none; padding: 0px; margin: 0px; background: transparent; }"
            "QToolButton:hover { background: transparent; }"
            "QToolButton:pressed { background: transparent; }"
        )

        pixmap = QPixmap(icon_path)
        if not pixmap.isNull():
            normal_icon = QIcon(pixmap)
            hover_icon = QIcon(HoverIconToolButton._darken_pixmap(pixmap, alpha=90))
            button.setHoverIcons(normal_icon, hover_icon)
        else:
            # Fallback to text if asset missing
            button.setText(piece_upper)

        button.clicked.connect(lambda _checked=False, p=piece: self.promote(p))
        layout.addWidget(button)

    self.setFixedSize(
        (button_size.width() * len(pieces)) + (layout.spacing() * (len(pieces) - 1)) + layout.contentsMargins().left() + layout.contentsMargins().right(),
        button_size.height() + layout.contentsMargins().top() + layout.contentsMargins().bottom(),
    )

promote(piece)

Select a promotion piece and close the dialog.

Parameters:

Name Type Description Default
piece str

One of 'Q', 'R', 'B', 'N' (case-insensitive).

required
Return

None

Source code in python/ui/dialog_ui.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
def promote(self, piece):
    """Select a promotion piece and close the dialog.

    Args:
        piece (str): One of 'Q', 'R', 'B', 'N' (case-insensitive).

    Return:
        None
    """
    self.chosen_piece = self.piece_chosen_dict[piece.upper()]
    self.accept()  # Close the promotion dialog after selection    

SpinningGear

Bases: QWidget

Spinning gear widget for animations and loading states.

Source code in python/ui/dialog_ui.py
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
class SpinningGear(QWidget):
    """Spinning gear widget for animations and loading states."""

    def __init__(self, size=50, image_path="ui/assets/gear_icon.png"):
        """Initialize the spinning gear widget.

        Args:
            size (int): Size of the gear in pixels (width and height).
            image_path (str): Path to the gear image file.

        Return:
            None
        """
        super().__init__()
        self.setFixedSize(size, size)
        self.angle = 0

        # Load and scale the gear image
        original_image = QPixmap(image_path)
        self.gear_image = original_image.scaled(
            size, size,
            Qt.AspectRatioMode.KeepAspectRatio,
            Qt.TransformationMode.SmoothTransformation
        )

        # Animation timer
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.rotate_gear)
        self.timer.start(16)

    def rotate_gear(self):
        """Rotate the gear by a small increment.

        Args:
            None

        Return:
            None
        """
        self.angle += 2
        if self.angle >= 360:
            self.angle = 0
        self.update()

    def paintEvent(self, event):
        """Paint the rotating gear on the widget.

        Args:
            event: Qt paint event.

        Return:
            None
        """
        painter = QPainter(self)
        painter.setRenderHint(QPainter.RenderHint.Antialiasing)
        painter.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform)

        # Move the origin to the center of the widget
        painter.translate(self.width() / 2, self.height() / 2)

        # Rotate the canvas
        painter.rotate(self.angle)

        # Draw the image centered at the origin
        offset_x = int(-self.gear_image.width() / 2)
        offset_y = int(-self.gear_image.height() / 2)
        painter.drawPixmap(offset_x, offset_y, self.gear_image)

    def set_image(self, image_path, size=None):
        """Update the gear image (optional method for dynamic image changes).

        Args:
            image_path (str): Path to the new gear image file.
            size (int | None): Optional new size. If None, keeps current size.

        Return:
            None
        """
        current_size = self.width() if size is None else size
        if size is not None:
            self.setFixedSize(size, size)

        original_image = QPixmap(image_path)
        self.gear_image = original_image.scaled(
            current_size, current_size,
            Qt.AspectRatioMode.KeepAspectRatio,
            Qt.TransformationMode.SmoothTransformation
        )
        self.update()

__init__(size=50, image_path='ui/assets/gear_icon.png')

Initialize the spinning gear widget.

Parameters:

Name Type Description Default
size int

Size of the gear in pixels (width and height).

50
image_path str

Path to the gear image file.

'ui/assets/gear_icon.png'
Return

None

Source code in python/ui/dialog_ui.py
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
def __init__(self, size=50, image_path="ui/assets/gear_icon.png"):
    """Initialize the spinning gear widget.

    Args:
        size (int): Size of the gear in pixels (width and height).
        image_path (str): Path to the gear image file.

    Return:
        None
    """
    super().__init__()
    self.setFixedSize(size, size)
    self.angle = 0

    # Load and scale the gear image
    original_image = QPixmap(image_path)
    self.gear_image = original_image.scaled(
        size, size,
        Qt.AspectRatioMode.KeepAspectRatio,
        Qt.TransformationMode.SmoothTransformation
    )

    # Animation timer
    self.timer = QTimer(self)
    self.timer.timeout.connect(self.rotate_gear)
    self.timer.start(16)

paintEvent(event)

Paint the rotating gear on the widget.

Parameters:

Name Type Description Default
event

Qt paint event.

required
Return

None

Source code in python/ui/dialog_ui.py
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
def paintEvent(self, event):
    """Paint the rotating gear on the widget.

    Args:
        event: Qt paint event.

    Return:
        None
    """
    painter = QPainter(self)
    painter.setRenderHint(QPainter.RenderHint.Antialiasing)
    painter.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform)

    # Move the origin to the center of the widget
    painter.translate(self.width() / 2, self.height() / 2)

    # Rotate the canvas
    painter.rotate(self.angle)

    # Draw the image centered at the origin
    offset_x = int(-self.gear_image.width() / 2)
    offset_y = int(-self.gear_image.height() / 2)
    painter.drawPixmap(offset_x, offset_y, self.gear_image)

rotate_gear()

Rotate the gear by a small increment.

Return

None

Source code in python/ui/dialog_ui.py
208
209
210
211
212
213
214
215
216
217
218
219
220
def rotate_gear(self):
    """Rotate the gear by a small increment.

    Args:
        None

    Return:
        None
    """
    self.angle += 2
    if self.angle >= 360:
        self.angle = 0
    self.update()

set_image(image_path, size=None)

Update the gear image (optional method for dynamic image changes).

Parameters:

Name Type Description Default
image_path str

Path to the new gear image file.

required
size int | None

Optional new size. If None, keeps current size.

None
Return

None

Source code in python/ui/dialog_ui.py
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
def set_image(self, image_path, size=None):
    """Update the gear image (optional method for dynamic image changes).

    Args:
        image_path (str): Path to the new gear image file.
        size (int | None): Optional new size. If None, keeps current size.

    Return:
        None
    """
    current_size = self.width() if size is None else size
    if size is not None:
        self.setFixedSize(size, size)

    original_image = QPixmap(image_path)
    self.gear_image = original_image.scaled(
        current_size, current_size,
        Qt.AspectRatioMode.KeepAspectRatio,
        Qt.TransformationMode.SmoothTransformation
    )
    self.update()

TurnIndicatorWidget

Bases: QWidget

Combined widget showing current turn with dynamic background and optional waiting spinner.

Source code in python/ui/dialog_ui.py
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
class TurnIndicatorWidget(QWidget):
    """Combined widget showing current turn with dynamic background and optional waiting spinner."""

    def __init__(self, parent=None):
        """Initialize the turn indicator widget.
        Args:
            parent (QWidget | None): Optional parent widget.
        Return:
            None"""
        super().__init__(parent)
        self.setFixedHeight(140)
        # Allow more horizontal space for text
        self.setMinimumWidth(400)
        self.setMaximumWidth(900)
        self.current_turn = "white"  # "white" or "black"
        self.is_waiting = False
        self.waiting_message = ""

        # Main layout
        self.main_layout = QHBoxLayout(self)
        self.main_layout.setContentsMargins(15, 15, 15, 15)
        self.main_layout.setSpacing(15)

        # Turn text label
        self.turn_label = QLabel("White's Turn")
        self.turn_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.turn_label.setStyleSheet("border: none; font-size: 32px;")
        font = self.turn_label.font()
        font.setBold(True)
        self.turn_label.setFont(font)

        # Container for waiting state (gear and message)
        self.waiting_container = QWidget()
        waiting_layout = QHBoxLayout(self.waiting_container)
        waiting_layout.setContentsMargins(0, 0, 0, 0)
        waiting_layout.setSpacing(15)

        # Spinning gear for waiting state
        self.spinning_gear = SpinningGear(70, "ui/assets/gear_icon.png")

        # Message label for waiting state
        self.message_label = QLabel("")
        self.message_label.setAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter)
        self.message_label.setWordWrap(True)
        self.message_label.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
        self.message_label.setStyleSheet("border: none; font-size: 22px")

        waiting_layout.addWidget(self.spinning_gear, 0, Qt.AlignmentFlag.AlignCenter)
        waiting_layout.addWidget(self.message_label, 1, Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter)
        self.waiting_container.setVisible(False)

        # Add widgets to main layout
        self.main_layout.addWidget(self.turn_label, 1, Qt.AlignmentFlag.AlignCenter)
        self.main_layout.addWidget(self.waiting_container, 1, Qt.AlignmentFlag.AlignCenter)

        # Set initial background color and text color
        self.update_turn("white")

    def update_turn(self, color):
        """Update the turn indicator with new color (white or black).
        Args:
             color (str): "white" or "black" indicating the current player's turn.
        Return:
             None"""

        self.current_turn = color
        if color.lower() == "white":
            bg_color = "white"
            self.turn_label.setText("White's Turn")
        else:
            bg_color = "black"
            self.turn_label.setText("Black's Turn")

        # Update background color only - labels will be styled by global QSS
        self.setStyleSheet(f"""
            TurnIndicatorWidget {{
                background-color: {bg_color};
                border: 2px solid #34495e;
                border-radius: 10px;
            }}
        """)

    def show_waiting(self, message="Processing..."):
        """Show waiting state with spinning gear and message.
        Args :
             message (str): Message to display next to the spinning gear.
        Return :   
             None"""
        self.is_waiting = True
        self.waiting_message = message
        self.turn_label.setVisible(False)
        self.message_label.setText(message)
        self.waiting_container.setVisible(True)

    def hide_waiting(self):
        """Hide waiting state and show turn indicator.
        Args : 
             None
        Return :
             None"""
        self.is_waiting = False
        self.waiting_message = ""
        self.turn_label.setVisible(True)
        self.waiting_container.setVisible(False)
        self.message_label.setText("")

__init__(parent=None)

Initialize the turn indicator widget. Args: parent (QWidget | None): Optional parent widget. Return: None

Source code in python/ui/dialog_ui.py
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
def __init__(self, parent=None):
    """Initialize the turn indicator widget.
    Args:
        parent (QWidget | None): Optional parent widget.
    Return:
        None"""
    super().__init__(parent)
    self.setFixedHeight(140)
    # Allow more horizontal space for text
    self.setMinimumWidth(400)
    self.setMaximumWidth(900)
    self.current_turn = "white"  # "white" or "black"
    self.is_waiting = False
    self.waiting_message = ""

    # Main layout
    self.main_layout = QHBoxLayout(self)
    self.main_layout.setContentsMargins(15, 15, 15, 15)
    self.main_layout.setSpacing(15)

    # Turn text label
    self.turn_label = QLabel("White's Turn")
    self.turn_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
    self.turn_label.setStyleSheet("border: none; font-size: 32px;")
    font = self.turn_label.font()
    font.setBold(True)
    self.turn_label.setFont(font)

    # Container for waiting state (gear and message)
    self.waiting_container = QWidget()
    waiting_layout = QHBoxLayout(self.waiting_container)
    waiting_layout.setContentsMargins(0, 0, 0, 0)
    waiting_layout.setSpacing(15)

    # Spinning gear for waiting state
    self.spinning_gear = SpinningGear(70, "ui/assets/gear_icon.png")

    # Message label for waiting state
    self.message_label = QLabel("")
    self.message_label.setAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter)
    self.message_label.setWordWrap(True)
    self.message_label.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
    self.message_label.setStyleSheet("border: none; font-size: 22px")

    waiting_layout.addWidget(self.spinning_gear, 0, Qt.AlignmentFlag.AlignCenter)
    waiting_layout.addWidget(self.message_label, 1, Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter)
    self.waiting_container.setVisible(False)

    # Add widgets to main layout
    self.main_layout.addWidget(self.turn_label, 1, Qt.AlignmentFlag.AlignCenter)
    self.main_layout.addWidget(self.waiting_container, 1, Qt.AlignmentFlag.AlignCenter)

    # Set initial background color and text color
    self.update_turn("white")

hide_waiting()

Hide waiting state and show turn indicator. Args : None Return : None

Source code in python/ui/dialog_ui.py
599
600
601
602
603
604
605
606
607
608
609
def hide_waiting(self):
    """Hide waiting state and show turn indicator.
    Args : 
         None
    Return :
         None"""
    self.is_waiting = False
    self.waiting_message = ""
    self.turn_label.setVisible(True)
    self.waiting_container.setVisible(False)
    self.message_label.setText("")

show_waiting(message='Processing...')

Show waiting state with spinning gear and message. Args : message (str): Message to display next to the spinning gear. Return :
None

Source code in python/ui/dialog_ui.py
587
588
589
590
591
592
593
594
595
596
597
def show_waiting(self, message="Processing..."):
    """Show waiting state with spinning gear and message.
    Args :
         message (str): Message to display next to the spinning gear.
    Return :   
         None"""
    self.is_waiting = True
    self.waiting_message = message
    self.turn_label.setVisible(False)
    self.message_label.setText(message)
    self.waiting_container.setVisible(True)

update_turn(color)

Update the turn indicator with new color (white or black). Args: color (str): "white" or "black" indicating the current player's turn. Return: None

Source code in python/ui/dialog_ui.py
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
def update_turn(self, color):
    """Update the turn indicator with new color (white or black).
    Args:
         color (str): "white" or "black" indicating the current player's turn.
    Return:
         None"""

    self.current_turn = color
    if color.lower() == "white":
        bg_color = "white"
        self.turn_label.setText("White's Turn")
    else:
        bg_color = "black"
        self.turn_label.setText("Black's Turn")

    # Update background color only - labels will be styled by global QSS
    self.setStyleSheet(f"""
        TurnIndicatorWidget {{
            background-color: {bg_color};
            border: 2px solid #34495e;
            border-radius: 10px;
        }}
    """)

WaitingDialog

Bases: QDialog

Simple waiting dialog to show while path is being sent.

Source code in python/ui/dialog_ui.py
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
class WaitingDialog(QDialog):
    """Simple waiting dialog to show while path is being sent."""

    def __init__(self, parent=None):
        """Initialize the waiting dialog.
        Args:
            parent (QWidget | None): Optional parent widget.
        Return:
            None"""
        super().__init__(parent)
        self.setWindowTitle("Processing Move")
        self.setModal(True)
        self.setFixedSize(300, 150)

        layout = QVBoxLayout()
        layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.label = QLabel("Sending move to device...\nPlease wait.")
        self.label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.spinning_gear = SpinningGear(65, "ui/assets/gear_icon.png")
        layout.addWidget(self.label, alignment=Qt.AlignmentFlag.AlignCenter)
        layout.addWidget(self.spinning_gear, alignment=Qt.AlignmentFlag.AlignCenter)
        self.setLayout(layout)

        # Center the dialog on parent
        if parent:
            parent_geometry = parent.geometry()
            self.move(
                parent_geometry.left() + (parent_geometry.width() - 300) // 2,
                parent_geometry.top() + (parent_geometry.height() - 100) // 2
            )

    def set_message(self, message):
        """Update the waiting message displayed in the dialog.
        Args:
            message (str): New message to display.
        Return:
            None"""
        self.label.setText(message)

__init__(parent=None)

Initialize the waiting dialog. Args: parent (QWidget | None): Optional parent widget. Return: None

Source code in python/ui/dialog_ui.py
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
def __init__(self, parent=None):
    """Initialize the waiting dialog.
    Args:
        parent (QWidget | None): Optional parent widget.
    Return:
        None"""
    super().__init__(parent)
    self.setWindowTitle("Processing Move")
    self.setModal(True)
    self.setFixedSize(300, 150)

    layout = QVBoxLayout()
    layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
    self.label = QLabel("Sending move to device...\nPlease wait.")
    self.label.setAlignment(Qt.AlignmentFlag.AlignCenter)
    self.spinning_gear = SpinningGear(65, "ui/assets/gear_icon.png")
    layout.addWidget(self.label, alignment=Qt.AlignmentFlag.AlignCenter)
    layout.addWidget(self.spinning_gear, alignment=Qt.AlignmentFlag.AlignCenter)
    self.setLayout(layout)

    # Center the dialog on parent
    if parent:
        parent_geometry = parent.geometry()
        self.move(
            parent_geometry.left() + (parent_geometry.width() - 300) // 2,
            parent_geometry.top() + (parent_geometry.height() - 100) // 2
        )

set_message(message)

Update the waiting message displayed in the dialog. Args: message (str): New message to display. Return: None

Source code in python/ui/dialog_ui.py
497
498
499
500
501
502
503
def set_message(self, message):
    """Update the waiting message displayed in the dialog.
    Args:
        message (str): New message to display.
    Return:
        None"""
    self.label.setText(message)

WinnerDialog

Bases: QDialog

Dialog shown at end of game to announce winner and offer play again or quit options. Quit exits the application, while play again just closes the dialog and returns to the main menu.

Source code in python/ui/dialog_ui.py
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
class WinnerDialog(QDialog):
    """Dialog shown at end of game to announce winner and offer play again or quit options. 
    Quit exits the application, while play again just closes the dialog and returns to the main menu."""

    def __init__(self, winner_color="white", parent=None, reason="checkmate"):
        """Initialize the winner dialog.
        Args:
            winner_color (str): "white" or "black" indicating the winner's color.
            parent (QWidget | None): Optional parent widget.
            reason (str): "checkmate" or "timeout" indicating how the game was won
        Return:
            None
        """

        super().__init__(parent)

        self.setWindowFlags(Qt.WindowType.FramelessWindowHint | Qt.WindowType.Dialog)
        self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
        self.setFixedSize(320, 225)
        self.setModal(True) 

        self.container = QFrame(self)
        self.container.setFixedSize(self.width(), self.height())

        # --- Updated Custom Styling (QSS) ---
        self.container.setStyleSheet("""
            QFrame {
                background-color: #2E4C3B; /* Sleek slate blue background */
                border: 2px solid #34495e; /* Slightly lighter blue border */
                border-radius: 15px;       
            }
            QLabel {
                color: #ffffff;
                border: none;
            }
            QPushButton {
                background-color: #4CAF50; /* Green play button */
                color: white;
                border-radius: 5px;
                padding: 10px 15px;
                font-weight: bold;
                font-size: 14px;
                border: none;
            }
            QPushButton:hover {
                background-color: #45a049;
            }
            QPushButton#quitBtn {          
                background-color: #f44336; /* Red quit button */
            }
            QPushButton#quitBtn:hover {
                background-color: #da190b;
            }
        """)

        main_layout = QVBoxLayout(self.container)
        button_layout = QHBoxLayout()
        image_layout = QHBoxLayout()

        if reason == "checkmate":
            message = f"CHECKMATE!"
        else :
            message = f"Out of time \n{winner_color.capitalize()} wins!"

        self.label = QLabel(message)
        self.label.setAlignment(Qt.AlignmentFlag.AlignCenter)

        font = self.label.font()
        font.setPointSize(16)
        font.setBold(True)
        self.label.setFont(font)

        self.winner_image = QPixmap(f"ui/assets/chess_assets/pieces_png/{winner_color}-king.png")
        loser_color = "black" if winner_color == "white" else "white"
        self.loser_image = QPixmap(f"ui/assets/chess_assets/pieces_png/{loser_color}-king.png")
        transform = QTransform().rotate(-90)
        self.loser_image = self.loser_image.transformed(transform, Qt.TransformationMode.SmoothTransformation)

        winner_label = QLabel()
        winner_label.setPixmap(self.winner_image)
        loser_label = QLabel()
        loser_label.setPixmap(self.loser_image)

        image_layout.addWidget(winner_label)
        image_layout.addWidget(loser_label)

        self.play_again_btn = QPushButton("Play Again")
        self.quit_btn = QPushButton("Quit")
        self.quit_btn.setObjectName("quitBtn") 

        self.play_again_btn.clicked.connect(self.accept) 
        self.quit_btn.clicked.connect(self.reject)       

        button_layout.addWidget(self.play_again_btn)
        button_layout.addWidget(self.quit_btn)

        main_layout.addWidget(self.label)
        main_layout.addLayout(image_layout)
        main_layout.addLayout(button_layout)

        dialog_layout = QVBoxLayout(self)
        dialog_layout.setContentsMargins(0, 0, 0, 0)
        dialog_layout.addWidget(self.container)

__init__(winner_color='white', parent=None, reason='checkmate')

Initialize the winner dialog. Args: winner_color (str): "white" or "black" indicating the winner's color. parent (QWidget | None): Optional parent widget. reason (str): "checkmate" or "timeout" indicating how the game was won Return: None

Source code in python/ui/dialog_ui.py
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
def __init__(self, winner_color="white", parent=None, reason="checkmate"):
    """Initialize the winner dialog.
    Args:
        winner_color (str): "white" or "black" indicating the winner's color.
        parent (QWidget | None): Optional parent widget.
        reason (str): "checkmate" or "timeout" indicating how the game was won
    Return:
        None
    """

    super().__init__(parent)

    self.setWindowFlags(Qt.WindowType.FramelessWindowHint | Qt.WindowType.Dialog)
    self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
    self.setFixedSize(320, 225)
    self.setModal(True) 

    self.container = QFrame(self)
    self.container.setFixedSize(self.width(), self.height())

    # --- Updated Custom Styling (QSS) ---
    self.container.setStyleSheet("""
        QFrame {
            background-color: #2E4C3B; /* Sleek slate blue background */
            border: 2px solid #34495e; /* Slightly lighter blue border */
            border-radius: 15px;       
        }
        QLabel {
            color: #ffffff;
            border: none;
        }
        QPushButton {
            background-color: #4CAF50; /* Green play button */
            color: white;
            border-radius: 5px;
            padding: 10px 15px;
            font-weight: bold;
            font-size: 14px;
            border: none;
        }
        QPushButton:hover {
            background-color: #45a049;
        }
        QPushButton#quitBtn {          
            background-color: #f44336; /* Red quit button */
        }
        QPushButton#quitBtn:hover {
            background-color: #da190b;
        }
    """)

    main_layout = QVBoxLayout(self.container)
    button_layout = QHBoxLayout()
    image_layout = QHBoxLayout()

    if reason == "checkmate":
        message = f"CHECKMATE!"
    else :
        message = f"Out of time \n{winner_color.capitalize()} wins!"

    self.label = QLabel(message)
    self.label.setAlignment(Qt.AlignmentFlag.AlignCenter)

    font = self.label.font()
    font.setPointSize(16)
    font.setBold(True)
    self.label.setFont(font)

    self.winner_image = QPixmap(f"ui/assets/chess_assets/pieces_png/{winner_color}-king.png")
    loser_color = "black" if winner_color == "white" else "white"
    self.loser_image = QPixmap(f"ui/assets/chess_assets/pieces_png/{loser_color}-king.png")
    transform = QTransform().rotate(-90)
    self.loser_image = self.loser_image.transformed(transform, Qt.TransformationMode.SmoothTransformation)

    winner_label = QLabel()
    winner_label.setPixmap(self.winner_image)
    loser_label = QLabel()
    loser_label.setPixmap(self.loser_image)

    image_layout.addWidget(winner_label)
    image_layout.addWidget(loser_label)

    self.play_again_btn = QPushButton("Play Again")
    self.quit_btn = QPushButton("Quit")
    self.quit_btn.setObjectName("quitBtn") 

    self.play_again_btn.clicked.connect(self.accept) 
    self.quit_btn.clicked.connect(self.reject)       

    button_layout.addWidget(self.play_again_btn)
    button_layout.addWidget(self.quit_btn)

    main_layout.addWidget(self.label)
    main_layout.addLayout(image_layout)
    main_layout.addLayout(button_layout)

    dialog_layout = QVBoxLayout(self)
    dialog_layout.setContentsMargins(0, 0, 0, 0)
    dialog_layout.addWidget(self.container)

User Interface Components

Game Board

  • Visual Representation - 8x8 chess board with pieces
  • Square Highlighting - Show selected piece and legal moves
  • Trajectory Display - Show robot movement path

Move History

  • Notation List - Display all moves in algebraic notation
  • Move Navigation - Step backward/forward through game
  • Capture Indicators - Mark captured pieces

Chess Clock

  • Time Display - Show remaining time for each player
  • Color Indicators - White/black background for current player
  • Out of Time Detection - Automatic game end on timeout

Status Indicators

  • Turn Indicator - Show which player's turn it is
  • Waiting Spinner - Show processing status with animated gear
  • Error Messages - Display issues or invalid moves

Settings Controls

  • Board Orientation - Rotate board perspective (possible to play as black or white)
  • Difficulty Selection - Choose chess engine opponent strength
  • Device Configuration - Select and test hardware (core XY or camera)