0

im trying to shoot multiple bullets but i can only get it to shoot 1 then i have to restart the game how do i shoot multiple bullets ive tried doing for loops but i cant get them to work

import pygame
import sys

pygame.init()
bg=pygame.display.set_mode((1300,640))
FPS=pygame.time.Clock()
p=x,y,width,height=(0,0,100,100)
b=b_x,b_y,b_width,b_height=(x,y,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,0,255),(b_x+100,m,b_width,b_height))
    something()

def something():
    pygame.draw.rect(bg, (0, 0, 255), (b_x + 100, m, b_width, 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,0))
player1=pygame.draw.rect(bg,(255,0,0),(x,y,width,height))
if shoot:
    draw()

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

1 Answers1

1

To reload, just reset the shoot flag and bullet position.

Try this update:

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

For rapid fire, use a list to store the bullet positions. The space key adds to the bullet list. When the bullet goes off screen, remove it from the list.

import pygame
import sys

pygame.init()
bg=pygame.display.set_mode((1300,640))
FPS=pygame.time.Clock()
p=x,y,width,height=(0,0,100,100)
b=b_x,b_y,b_width,b_height=(x,y,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,0,255),(b_x+100,m,b_width,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,0))
    player1=pygame.draw.rect(bg,(255,0,0),(x,y,width,height))
    if len(bullets):  # if any active bullets
        draw()

    pygame.display.update()
    FPS.tick(30)
Mike67
  • 11,175
  • 2
  • 7
  • 15