Files
project_game/fruit_catcher/catcher.py
2026-03-19 12:43:05 -04:00

64 lines
1.9 KiB
Python

from random import randint
from .fruit import FruitPiece
class CatcherPiece:
character = "-"
color = "white_on_indigo"
z = 1
def __init__(self, position):
self.position = position
class Catcher:
width = 6
display = False
pieces = []
name = "catcher"
color = "white_on_indigo"
def __init__(self, position):
self.position = position
def play_turn(self, game):
if not self.pieces:
self.create_pieces(game)
def handle_keystroke(self, keystroke, game):
x, y = self.position
width, height = game.board_size
if keystroke.name == "KEY_LEFT":
new_x = max(0, x - 3)
self.position = (new_x, y)
self.update_piece_positions()
self.check_fruit_collisions(game)
if keystroke.name == "KEY_RIGHT":
new_x = min(width - self.width, x + 3)
self.position = (new_x, y)
self.update_piece_positions()
self.check_fruit_collisions(game)
def check_fruit_collisions(self, game):
agents_by_pos = game.get_agents_by_position()
seen = set()
for piece in self.pieces:
for agent in agents_by_pos.get(piece.position, []):
if isinstance(agent, FruitPiece) and agent.parent.alive and id(agent.parent) not in seen:
seen.add(id(agent.parent))
agent.parent.check_catcher_collision(game)
def create_pieces(self, game):
x, y = self.position
self.pieces = []
for i in range(self.width):
piece = CatcherPiece((x + i, y))
self.pieces.append(piece)
game.add_agent(piece)
def update_piece_positions(self):
x, y = self.position
for i, piece in enumerate(self.pieces):
piece.position = (x + i, y)
def can_move(self, position, game):
on_board = game.on_board(position)
empty = game.is_empty(position)