How to prevent spamming bullets in pygame

Viewed 134

In my game, there is a problem with bullet spamming, because the player can shoot a lot of bullets in a short time. How can I prevent the player to do that? Should I use a clock? And how can I use the clock? Here it is some code:

class Player (Obj):
    def command (self, shoot):
        keys = pg.key.get_pressed()
        self.shoot = shoot       
        if keys[shoot]:
            self.Shoot()
    def Shoot(self):   
        global prts
        prts.append (Ammo(player.x, player.y, prt_img ))
        print (prts)

while True:
    window.fill(WHITE)
    player.blit()
    player.command(pg.K_SPACE)
    for ammo in prts:
        ammo.blit()
        ammo.Move(0.5)
        ammo.BordCheck()
    pg.display.update()

Here it is an image of what happens

Sorry for any mistakes

1 Answers

Pygame by default will trigger the key pressed event as fast as your computer can handle it (meaning the better the computer, the faster you will shoot). This has been a common issue in old video games that were only tested on one computer.

Adding a 'clock' is a good way of fixing the problem. For example if you want the player to shoot no faster than a bullet every half a second, you can get the current time when he shoots and then on the next shoot you check the time, if less than 1/2 second has passed you don t shoot, else you shoot and update the time with the time of the new bullet.

For more optimization, you might even want to completely block the keyboard input from firing a 'shooting key pressed' event while the player cannot shoot but that is a minor optimization that shouldn t be necessary in a small game.

To manipulate time in python, you can use the time and datetime default modules. I often suggest using arrow if you have a lot of times and dates to manipulate as it is a bit simpler I think.

Here is an example comparing seconds using datetime :

#!/usr/bin/env python3

from datetime import datetime

t1 = datetime.strptime("Feb 12 08:02:34 2015", "%b %d %H:%M:%S %Y")
t2 = datetime.strptime("Feb 12 08:02:32 2015", "%b %d %H:%M:%S %Y")

difference = t1 - t2

print(difference.seconds) # 2, in this case

Does this solve your problem ?

Related