generated from mwc/project_game
I attempted to add a shooting feature where the player presses the M key to fire bullets upward. Originally, I tried making the space bar the key to shoot but this has shown to be difficult as it did not shoot bullets using M or the space bar. I created a new Bullet class and added code to spaceship.py that should create a bullet agent above the ship.However, the shooting did not work because Retro was not detecting the M key the way the code expected. Even though the feature is not working yet, it is an important mechanic because it would allow the player to clear asteroids and add a new layer of interaction and strategy to the game. I was annoyed with the idea that I was not able to get shooting to work but ultimately I decided to keep it within my code as a way to show that my previous did work and eventhough the shooting mechanic did not it is important for me to look back at it one day. Even if it doesn't work, it was an attempt at an idea.
59 lines
1.6 KiB
Python
59 lines
1.6 KiB
Python
# 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() |