【发布时间】:2016-06-24 13:34:49
【问题描述】:
我使用 Python 和 Pygame 制作了一个游戏。我的船四处移动,但我无法让它发射子弹。我定义了一个名为shootBullets() 的函数,但它不起作用。现在,如果我按下空格键,我的船就会移动。只有当我按向左或向右箭头键时它才会移动。当我按下空格键时,我希望我的飞船向屏幕底部发射子弹。这是我的代码:
import pygame,sys
from pygame.locals import *
pygame.init()
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)
bright_blue = (0, 135, 255)
yellow = (255,242,0)
ship_body = (33, 117, 243)
screen = pygame.display.set_mode((500,500))
pygame.display.set_caption("Battleship")
gameExit = False
background = pygame.image.load("Sky Background.png")
bulletImg = pygame.image.load("Bullet.png")
bulletY = 80
def shootBullets():
for event in pygame.event.get():
if event.type == KEYDOWN and event.key == K_SPACE:
bulletY += 5
screen.blit(bulletImg,(247,bulletY))
pygame.key.set_repeat(50,50)
ship_points = [ [100, 50], [180, 95], [320, 95], [400, 50], [250, 35] ]
x = 0
y = 0
while not gameExit:
for event in pygame.event.get():
if event.type == QUIT:
gameExit = True
if event.type == KEYDOWN:
if event.key == pygame.K_LEFT: x = -5
if event.key == pygame.K_RIGHT: x = 5
for point in ship_points:
point[0] += x
for point in ship_points:
if point[0] <= 0 or point[0] >= 500:
gameExit = True
shootBullets()
screen.fill(black)
screen.blit(background, (0,0))
ship = [
pygame.draw.polygon(screen, ship_body, ship_points),
pygame.draw.polygon(screen, black, ship_points, 1)]
pygame.display.update()
pygame.quit()
quit()
【问题讨论】:
-
您没有检查是否按下了空格。那么太空为什么要发射子弹呢?
-
您的
point[0] += x行在按any 键时运行。x可以从以前的循环迭代中继承。