Shooting Bullets
Now Try
- Create a ‘Bullet’ class that has the following properties: a 5x5 image, speed set to 15, and a corresponding rect.
Now Try
- Define a method called ‘set_pos’ that will be run in the constructor and will set the bullet object rect’s initial x and y positon. Hint: pass the ship object to ‘Bullet’s constructor.
Now Try
- Define a method called ‘update’ that will decrement the bullet by the ‘speed’ property. Be sure to have your program remove the bullet object when it goes off the screen. Hint: the method that removes objects is kill() and you would use it like this: self.kill()
Now Try
- Create a ‘bullet_group’.
- Have the ship create a bullet object when the SPACE key is pressed. Hint: pygame.K_SPACE
- Add the newly created bullet to ‘bullet_group’.
- Update the ‘bullet_group’.
- Print everything in the ‘bullet_group’ by applying the camera.
Let’s limit the amount of bullets to something more reasonable. We can do this by creating a global variable called TIMER. TIMER will be initialized to zero and will be incremented once in each iteration of the game loop. The way we are going to get the bullets to fire less frequently, is by firing on every 10th iteration of the game loop.
Now Try
- Create a global variable called TIMER and initialize it to zero.
- Increment TIMER on each iteration of the game loop.
- Write a conditional statement in ‘ship.update’ that will only create a bullet when the space key is pressed AND it’s the 10 iteration of the game loop. Hint: Use TIMER and the modulo operator. Also, be sure to declare ‘global TIMER’ at the top of every function or method that uses TIMER.
- Adjust your firing algorithm so that only 6 bullets can appear on the screen at a time.
Now Try
- In our version, the bullet is appearing dead center with respect to our ship. In the arcade version, the bullets start out as two streams that are separated by a space the width of a bullet. Make this adjustment so your game mirrors the “Raiden 2”.