我使用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()
答案 0 :(得分:1)
在主循环中,您只检查左右,而不是空格。你检查函数shootBullets
是否按了空格,但是为时已晚,shootBullets永远不会被执行(实际上如果for event in get()
循环以某种方式退出,它会被执行但是这不是你想要的)。
取而代之的是:
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:
move_left()
if event.key == pygame.K_RIGHT:
move_right()
if event.key == pygame.SPACE:
shootBullet()
[...]