# spaceship.py # ------------ # By MWC Contributors # This module defines a spaceship agent class. from bullet import Bullet class Spaceship: name = "ship" character = '^' def __init__(self, board_size): board_width, board_height = board_size self.position = (board_width // 2, board_height - 1) def handle_keystroke(self, keystroke, game): x, y = self.position new_position = None # Move LEFT if keystroke.name in ("KEY_LEFT", "a", "A"): new_position = (x - 1, y) # Move RIGHT elif keystroke.name in ("KEY_RIGHT", "d", "D"): new_position = (x + 1, y) # Move UP elif keystroke.name in ("KEY_UP", "w", "W"): new_position = (x, y - 1) # Move DOWN elif keystroke.name in ("KEY_DOWN", "s", "S"): new_position = (x, y + 1) # SHOOT (m or M) elif keystroke.name in ("m", "M"): bx, by = x, y - 1 if game.on_board((bx, by)): bullet = Bullet((bx, by)) game.add_agent(bullet) return # don’t move on shoot else: return # ignore other keys # If we are trying to move: if new_position is not None and game.on_board(new_position): if game.is_empty(new_position): self.position = new_position else: # We bumped into something self.take_damage(game) def take_damage(self, game): """Reduce health; end game if health reaches 0.""" game.state["health"] -= 1 if game.state["health"] <= 0: game.end()