Files
project_game/spaceship.py
angelotr 47a9e1abe3 I did not realize this had to be three submissions. My first progress was the add lives to the asteroid game.
For this feature, I added a health system so the player has three
lives instead of losing instantly. In nav_game.py, I added "health": 3
to the game state, and in spaceship.py I created a take_damage method
that subtracts one life when the ship is hit. If the player's health
reaches zero, the game ends. This change is important because it
makes the game less punishing, gives the player more chances to
recover from mistakes, and makes gameplay feel more balanced and fun.
2025-12-08 23:39:17 -05:00

59 lines
1.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 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 # dont 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 (probably an asteroid)
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()