Ich versuche, ein Space Invaders Spiel mit Pygame zu machen. Allerdings habe ich Probleme damit herauszufinden, wie man das Raumschiff dazu bringt, kontinuierlich mehrere Kugeln zu schießen und die Kugeln mitzunehmen. Die einzige Art, wie ich das Programm tatsächlich dazu gebracht habe, mehrere Kugeln zu schießen, ist durch eine for loop
, obwohl die Kugeln aufhören zu schießen, sobald die for loop
ihr Ende erreicht. Soll ich eine Liste erstellen, um alle Kugeln zu speichern? Jede Hilfe wird geschätzt: D.Python Pygame: Feuer mehrere Kugeln für Space Invader Spiel
Unten ist mein Python-Code bisher (Es hat nur das Raumschiff, das eine Kugel abfeuert).
from __future__ import print_function
import pygame
import os, sys
from pygame.locals import *
x_location = 357
y_location = 520
bullet_location_x = x_location + 35
bullet_location_y = y_location - 5
def load_image(path, colorkey): # loads an image given the file path
try:
image = pygame.image.load(path)
except pygame.error, message:
print("Cannot load image: {0}".format(path)) # print out error message
image = image.convert() # convert image so that it can be displayed properly
if colorkey is not None:
if colorkey is -1:
colorkey = image.get_at((0, 0))
image.set_colorkey(colorkey, RLEACCEL)
return image, image.get_rect() # Return the image and the image's rectangular area
def main():
global x_location, y_location, bullet_location_x, bullet_location_y
pygame.init()
background_color = (0, 0, 0) # green background
width, height = (800, 600) # width and height of screen
screen = pygame.display.set_mode((width, height)) # set width and height
pygame.display.set_caption('space invaders') # set title of game
clock = pygame.time.Clock() # create the clock
spaceship_img, spaceship_rect = load_image("spaceship.png", (0, 0, 0))
bullet_img, bullet_rect = load_image("bullet.png", (0, 0, 0))
while True:
screen.fill(background_color) # make the background green
##############################################################
# DISPLAY BULLET #
##############################################################
screen.blit(bullet_img, (bullet_location_x, bullet_location_y))
# Render the images
screen.blit(spaceship_img, (x_location, y_location))
keys = pygame.key.get_pressed() # get the keysnpressed
for event in pygame.event.get(): # check the events
if event.type == pygame.QUIT: # if the user presses quit
pygame.quit() # quit pygame
sys.exit() # terminate the process
if event.type == KEYDOWN:
if event.key == K_LEFT:
screen.fill(background_color)
x_location -= 5
screen.blit(spaceship_img, (x_location, y_location))
if event.key == K_RIGHT:
screen.fill(background_color)
x_location += 5
screen.blit(spaceship_img, (x_location, y_location))
if event.key == K_UP:
screen.blit(bullet_img, (bullet_location_x, bullet_location_y))
display_bullets = True
pygame.display.flip() # refresh the pygame window
clock.tick(60) # Makes the game run at around 60 FPS
bullet_location_y -= 5
pass
if __name__ == '__main__':
main()