I'm working on simple game in Python and Pyglet. I want to give possibility to shoot so I create a bullet class. If I create one instance of that class for example
self.new_bullet = bullet()
I'm able to have only one instance at the moment. My question is how to create many instances at same time and be be able to refer to them and their variables? Example code (with pieces of pseudocode):
if key pressed:
self.new_bullet = bullet()
... somewhere in main loop ...
bullet_image.blit(new_bullet.x, new_bullet.y)
self.new_bullet.x += 5
class bullet:
def __init__(self):
self.pos_x = player.pos_x
self.pos_y = player.pos_y
So how should I create as many bullets as player wishes and still be able to give them speed and update their positions on screen?
I think that you want a list of bullet objects. Then, you can add to your list using append
, and during your main loop you can iterate through all of them using a for
loop.
self.bullets = []
self.bullets.append(bullet())
self.bullets.append(bullet())
In your main loop:
for bullet in self.bullets:
bullet_image.blit(bullet.x, bullet.y)
bullet.x += 5