diff --git a/README.md b/README.md index 30bf7df..c76d928 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,8 @@ Little Update: ![image](https://github.com/user-attachments/assets/4c684cd1-d46d-4c61-8e63-618654657924) Little Chess Game I created in half an hour using the ursina engine. + +Press **U** or click the **Undo** button to take back the last move. ![image](https://github.com/user-attachments/assets/1a8473b1-2445-497e-b5cf-9efe9afd0f87) ![image](https://github.com/user-attachments/assets/b01c78aa-bc15-4699-ac12-6a2f091d6251) ![image](https://github.com/user-attachments/assets/dbc30499-e322-4cb6-9f80-623c3cbe6e17) diff --git a/chess_game.py b/chess_game.py index a8d390d..833063c 100644 --- a/chess_game.py +++ b/chess_game.py @@ -41,6 +41,7 @@ def centered_text(msg: str, col, duration: float = 1.5): return btn move_display = None +undo_button = None def enable_board_input(state: bool): @@ -55,6 +56,15 @@ def update_board(): move_display.text = board.peek().uci() if board.move_stack else '' +def undo_move(): + if not board.move_stack: + return + board.pop() + update_board() + clear_highlights() + clicked.clear() + + def ask_promotion(base_move: str): enable_board_input(False) @@ -76,6 +86,8 @@ def choose(letter: str): centered_text('Check!', color.red) if board.is_checkmate(): centered_text('Checkmate!', color.gold) + if board.is_stalemate(): + centered_text('Stalemate!', color.gold) for i, (letter, glyph) in enumerate(pieces): b = Button( @@ -137,6 +149,8 @@ def handle_click(square_name: str): centered_text('Check!', color.red) if board.is_checkmate(): centered_text('Checkmate!', color.gold) + if board.is_stalemate(): + centered_text('Stalemate!', color.gold) except chess.IllegalMoveError: if needs_promotion(move): ask_promotion(move) @@ -178,7 +192,7 @@ def needs_promotion(base_move: str) -> bool: def layout_board(): - global tile_len, move_display + global tile_len, move_display, undo_button aspect = window.aspect_ratio tile_len = 1 / 8 if aspect < 1: @@ -203,12 +217,29 @@ def layout_board(): text='', ) + if undo_button is None: + undo_button = Button( + parent=move_display, + text='Undo', + color=color.azure, + text_color=color.black, + on_click=undo_move, + radius=0, + ) + else: + undo_button.parent = move_display + a8_pos = squares['a8'].position move_display.scale = (tile_len * .9, tile_len * .9) move_display.position = (a8_pos[0], a8_pos[1]) move_display.origin = (0, 0) move_display.z = -0.1 + undo_button.scale = move_display.scale + undo_button.position = (move_display.scale_x * 1.1, 0) + undo_button.origin = (0, 0) + undo_button.z = -0.1 + layout_board() @@ -224,4 +255,9 @@ def update(): _prev = window.size +def input(key): + if key == 'u': + undo_move() + + app.run()