CODE CREATIVE
ADDING ENEMIES
Defining a bullet class
Shooting Bullets
The next element we are going to add to our game is the ability for the ship to shoot bullets. In order to begin, we will need to create a ‘Bullet’ class which will define a 5x5 surface.

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
  1. Create a ‘bullet_group’.
  2. Have the ship create a bullet object when the SPACE key is pressed. Hint: pygame.K_SPACE
  3. Add the newly created bullet to ‘bullet_group’.
  4. Update the ‘bullet_group’.
  5. Print everything in the ‘bullet_group’ by applying the camera.
Your program should now fire bullets when you press the space bar. However, notice that the bullets are firing very rapidly. To be exact, they are firing as many times as the space bar is registering per second. Since we limited our game to 60 frames per second, the space bar is registering 60 times a second and 60 bullets are being created every second the space bar is being held down.

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
  1. Create a global variable called TIMER and initialize it to zero.
  2. Increment TIMER on each iteration of the game loop.
  3. 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.
  4. Adjust your firing algorithm so that only 6 bullets can appear on the screen at a time.
Great, now your bullets are now firing at a reasonable rate.

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”.