2026-rff_mp/ProninVV/task-2-oop/Command.py

46 lines
1.2 KiB
Python

from abc import ABC, abstractmethod
class Player:
def __init__(self, start_cell):
self.current_cell = start_cell
class Command(ABC):
@abstractmethod
def execute(self) -> bool:
"""Выполняет действие. Возвращает True, если ход успешен."""
pass
@abstractmethod
def undo(self) -> None:
"""Откатывает действие назад."""
pass
class MoveCommand(Command):
def __init__(self, player: Player, maze, dx: int, dy: int):
self.player = player
self.maze = maze
self.dx = dx
self.dy = dy
self.previous_cell = None
def execute(self) -> bool:
new_x = self.player.current_cell.x + self.dx
new_y = self.player.current_cell.y + self.dy
next_cell = self.maze.getCell(new_x, new_y)
if next_cell and next_cell.isPassable():
self.previous_cell = self.player.current_cell
self.player.current_cell = next_cell
return True
print("Ошибка: Там стена или край лабиринта!")
return False
def undo(self) -> None:
if self.previous_cell:
self.player.current_cell = self.previous_cell