私はPygameを使用してSpace Invadersゲームを作ろうとしています。しかし、私は、宇宙船が複数の弾丸を連続的に撃つようにして弾丸をそれに沿って動かす方法を考え出すのに苦労しています。私が実際にプログラムに複数の弾を撃たせる唯一の方法はfor loop
ですが、弾丸はfor loop
の終わりに達すると射撃を止めます。私はすべての弾丸を格納するリストを作成する必要がありますか?どんな助けもありがたいです。Python Pygame:Space Invaderゲーム用の複数の弾丸を発射
以下は私のPythonコードです(これは1つの弾丸を発射する宇宙船しか持っていません)。
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()