【问题标题】:Why is my ship not shooting bullets?为什么我的船不发射子弹?
【发布时间】: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 可以从以前的循环迭代中继承。

标签: python pygame


【解决方案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()
            [...]

【讨论】:

  • 您能否编辑您的代码以使其正确对齐
  • @PyNEwbie 对不起,你是对的。我想你也可以编辑其他答案来修复类似的错误。
  • 我打算编辑你的,但我不完全确定最后一个 if 语句的对齐方式。我以为你纠正了它,但是。 . .
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-30
  • 1970-01-01
  • 1970-01-01
  • 2017-12-09
  • 2011-02-15
  • 1970-01-01
相关资源
最近更新 更多