From fd2983fa355ab28a84b8febe7cc66b259de202be Mon Sep 17 00:00:00 2001 From: Eduard Prokhorikhin Date: Tue, 23 Apr 2024 16:50:19 +0200 Subject: [PATCH] feat: added demo mode for agent --- src/agents/agent.py | 13 ++++++------- src/game/tetris.py | 10 ++++++++-- 2 files changed, 14 insertions(+), 9 deletions(-) diff --git a/src/agents/agent.py b/src/agents/agent.py index 59878c4..c6bc0cf 100644 --- a/src/agents/agent.py +++ b/src/agents/agent.py @@ -77,18 +77,17 @@ def playGameDemoStepByStep(agent: Agent, board: Tetris) -> Tetris: # Get the result of the agent's action result = agent.result(board) + + if Action.HARD_DROP in result: + result.remove(Action.HARD_DROP) + result.append([Action.SOFT_DROP] * 20) # Perform the action(s) on the board if isinstance(result, list): for action in result: - board.doAction(action) - sleep(0.3) - # board.printBoard() + board.doAction(action, demo=True) else: - board.doAction(result) - sleep(0.1) - # board.printBoard() + board.doAction(action, demo=True) # Advance the game by one frame board.doAction(Action.SOFT_DROP) if board.blockHasLanded: board.updateBoard() - # board.printBoard() diff --git a/src/game/tetris.py b/src/game/tetris.py index 9b6bd67..08cd5a2 100644 --- a/src/game/tetris.py +++ b/src/game/tetris.py @@ -2,9 +2,12 @@ import copy from enum import Enum, auto +from time import sleep from src.game.block import Block +DEMO_SLEEP = 0.05 + class Action(Enum): """Enumeration for the possible actions that can be performed on the board""" @@ -91,12 +94,13 @@ def _initBoard(self) -> list[list[int]]: def getBoard(self) -> list[list[int]]: return copy.deepcopy(self.board) - def doAction(self, action: Action) -> None: + def doAction(self, action: Action, demo: bool = False) -> None: """ Performs the specified action on the current block and updates the game board accordingly. Args: action (Action): The action to perform, as defined in the Action enumeration. + demo (bool): If True, the action will be performed with a delay for demonstration purposes. """ # Move the new block according to the action @@ -125,6 +129,8 @@ def doAction(self, action: Action) -> None: if self.isValidBlockPosition(new_block): self.block = new_block self._placeBlock() + if demo: + sleep(DEMO_SLEEP) def updateBoard(self): @@ -327,7 +333,7 @@ def transition_model(current_state: Tetris, target_state: Tetris) -> list[Action if current_state == target_state: actions.append(Action.SOFT_DROP) - print("No transition needed") + # print("No transition needed") return actions # Find where the last block is in the target state