pygame射击多发子弹

问题描述

我试图射击多个子弹,但我只能射击1个子弹,然后我必须重新启动游戏。我如何射击多个子弹,我尝试做循环,但我无法使它们工作

import pygame
import sys

pygame.init()
bg=pygame.display.set_mode((1300,640))
FPS=pygame.time.Clock()
p=x,y,width,height=(0,100,100)
b=b_x,b_y,b_width,b_height=(x,25,25)
bullets=[99]
shoot=False
def draw():
    global bullet,b_x,shoot,m
    b_x+=50
    m=b_y+50
    bullet=pygame.draw.rect(bg,(0,255),(b_x+100,m,b_height))
    something()

def something():
    pygame.draw.rect(bg,(b_x + 100,b_height))


while True:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            pygame.quit()
            sys.exit()

        if event.type==pygame.KEYDOWN:
            if event.key==pygame.K_LEFT:
                x-=50

            if event.key==pygame.K_RIGHT:
                x+=50

            if event.key==pygame.K_SPACE:
                shoot=True

bg.fill((0,0))
player1=pygame.draw.rect(bg,(255,0),(x,height))
if shoot:
    draw()

pygame.display.update()
FPS.tick(30)

解决方法

要重新加载,只需重置射击标记和子弹位置即可。

尝试此更新:

if shoot:
    draw()
    if b_x > 1300:  # off screen
        b_x = 0
        shoot=False  # wait for space to re-shoot

要快速射击,请使用列表存储子弹位置。空格键将添加到项目符号列表中。当项目符号离开屏幕时,将其从列表中删除。

import pygame
import sys

pygame.init()
bg=pygame.display.set_mode((1300,640))
FPS=pygame.time.Clock()
p=x,y,width,height=(0,100,100)
b=b_x,b_y,b_width,b_height=(x,25,25)
bullets=[] # all active bullets
shoot=False
def draw():
    global bullets,bullet,b_x,shoot,m
    #b_x+=50
    m=b_y+50
    for i in range(len(bullets)):
       b_x = bullets[i] # x position of bullets
       bullet=pygame.draw.rect(bg,(0,255),(b_x+100,m,b_height))
       bullets[i] += 50  # move each bullet
    bullets = [b for b in bullets if b < 1300] # only keep bullets on screen   

while True:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            pygame.quit()
            sys.exit()

        if event.type==pygame.KEYDOWN:
            if event.key==pygame.K_LEFT:
                x-=50

            if event.key==pygame.K_RIGHT:
                x+=50

            if event.key==pygame.K_SPACE:
                bullets.append(0)  # add new bullets

    bg.fill((0,0))
    player1=pygame.draw.rect(bg,(255,0),(x,height))
    if len(bullets):  # if any active bullets
        draw()

    pygame.display.update()
    FPS.tick(30)