Files
project_game/player.py
ilmabura 2af3d6c2e7 Last milestone completed
Completed the project. I wanted to replace the player with a penguin, but it didn't fit the maze, so I kept it as an '>'.
It shows where you begin and where you need to go to finish, and each game is a different maze. I thought this was very difficult and i needed to learn how to make a maze, I was not prepared for that.
2025-12-07 16:17:56 -05:00

56 lines
1.8 KiB
Python

class Player:
"""
Player agent for Escape the Maze.
Moves one step at a time using the arrow keys.
Ends the game when it reaches the goal position.
"""
name = "player"
character = ">"
def __init__(self, board_size, goal_position):
# Start near the top-left corner
width, height = board_size
self.position = (1, 1)
self.goal_position = goal_position
def can_move_to(self, position, game):
"""
Returns True if there is no blocking agent (e.g., Wall) on this tile.
Non-blocking agents (like start/finish markers) are ignored.
"""
for agent in game.agents:
agent_pos = getattr(agent, "position", None)
if agent_pos == position:
if getattr(agent, "blocks_movement", False):
return False
return True
def handle_keystroke(self, keystroke, game):
"""
Called for each key pressed since the last turn.
Moves the player using the arrow keys and checks for win.
"""
x, y = self.position
new_position = None
if keystroke.name == "KEY_UP":
new_position = (x, y - 1)
elif keystroke.name == "KEY_DOWN":
new_position = (x, y + 1)
elif keystroke.name == "KEY_LEFT":
new_position = (x - 1, y)
elif keystroke.name == "KEY_RIGHT":
new_position = (x + 1, y)
if new_position is None:
return
if game.on_board(new_position) and self.can_move_to(new_position, game):
self.position = new_position
if self.position == self.goal_position:
game.state["win"] = True
game.state["message"] = "Congratulations! You've escaped the maze!"
game.end()