Reputation: 11
Ok so I'm working on this project for school. I'm supposed to make a space invader type of game. I have finished making my ship to move and fire shots. Now here's the problem, when I try to multi-fire, it erases the previous bullet that was fired and fires a new one which isn't a nice site at all. How can I get it to actually fire multiple shots?
while (running == 1):
screen.fill(white)
for event in pygame.event.get():
if (event.type == pygame.QUIT):
running = 0
elif (event.type == pygame.KEYDOWN):
if (event.key == pygame.K_d):
dir = "R"
move = True
elif (event.key == pygame.K_a):
dir = "L"
move = True
elif (event.key == pygame.K_s):
dir = "D"
move = True
elif (event.key == pygame.K_w):
dir = "U"
move = True
elif (event.key == pygame.K_ESCAPE):
sys.exit(0)
elif (event.key == pygame.K_SPACE):
shot=True
xbul=xgun + 18
ybul=ygun
#if key[K_SPACE]:
#shot = True
if (event.type == pygame.KEYUP):
move = False
#OBJECT'S MOVEMENTS
if ((dir == "R" and xgun<460) and (move == True)):
xgun = xgun + 5
pygame.event.wait
elif ((dir == "L" and xgun>0) and (move == True)):
xgun = xgun - 5
pygame.event.wait
elif ((dir == "D" and ygun<660) and (move == True)):
ygun = ygun + 5
pygame.event.wait
elif ((dir == "U" and ygun>0) and (move == True)):
ygun = ygun - 5
screen.blit(gun, (xgun,ygun))
#PROJECTILE MOTION
#key = pygame.key.get_pressed()
if shot == True:
ybul = ybul - 10
screen.blit(bullet, (xbul, ybul))
if xbul>640:
shot=False
pygame.display.flip()
time.sleep(0.012)
Upvotes: 1
Views: 1044
Reputation: 19406
You can create a class for bullets which contain the x and y co-ordinates and other things related to the bullet.Then for each fire button press, create and append a new instance to a list. This way you can have as many bullets you want.
(Changed code for new move
function)
class Bullet:
def __init__(self,x,y,vx,vy):# you can add other arguments like colour,radius
self.x = x
self.y = y
self.vx = vx # velocity on x axis
self.vy = vy # velocity on y axis
def move(self):
self.x += self.vx
self.y += self.vy
Example Code to add to for use of list
and updating postion of the bullet(move()
is above):
if shot == True: # if there are bullets on screen (True if new bullet is fired).
if new_bullet== True: # if a new bullet is fired
bullet_list.append(Bullet(n_x,n_y,0,10)) # n_x and n_y are the co-ords
# for the new bullet.
for bullet in bullet_list:
bullet.move()
Upvotes: 1
Reputation: 11644
You only have variables for a single bullet--xbul and ybul. If you want multiple bullets, then you should make each of these a list. You can append to each list to add a new bullet, pop to remove an old bullet, and iterate over the lists when drawing.
Upvotes: 7