2026-rff_mp/SorokinAD/[2]lab_2/commands.py

92 lines
1.6 KiB
Python

from abc import ABC, abstractmethod
from cell import Cell
from maze import Maze
class Player:
def __init__(self, start_cell: Cell):
self.current_cell = start_cell
# =========================================================
# Command
# =========================================================
class Command(ABC):
@abstractmethod
def execute(self):
pass
@abstractmethod
def undo(self):
pass
# =========================================================
# MoveCommand
# =========================================================
class MoveCommand(Command):
DIRECTIONS = {
"W": (0, -1),
"S": (0, 1),
"A": (-1, 0),
"D": (1, 0),
}
def __init__(
self,
player: Player,
maze: Maze,
direction: str
):
self.player = player
self.maze = maze
self.direction = direction.upper()
self.previous_cell = None
def execute(self):
if self.direction not in self.DIRECTIONS:
return False
dx, dy = self.DIRECTIONS[self.direction]
current = self.player.current_cell
new_x = current.x + dx
new_y = current.y + dy
target = self.maze.get_cell(
new_x,
new_y
)
if target is None:
return False
if not target.is_passable():
return False
self.previous_cell = current
self.player.current_cell = target
return True
def undo(self):
if self.previous_cell is not None:
self.player.current_cell = (
self.previous_cell
)