Coder14
Coder14

Reputation: 81

How to regulate a function in python under condition?

I have a function in pygame, which I have to run when the user presses space. However, the problem is that as soon as space is pressed, the function runs much more than once. I want it to run once, and if the user presses space again, I want the function to run again - once.

Some code below

if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
  God()

Now God() draws a bunch of shapes at the same time when I want it to draw one shape at a time, everytime the user presses space. God() is only called once. It picks a random number from 1 to 100 in order to make probabilities for each shape.

Upvotes: 0

Views: 69

Answers (1)

import random
import random

Reputation: 3245

A Minimal, Complete and Verifiable Example is required for more specific assistance with your issue.

Below is an example that shows the following:

  1. Holding down the Spacebar to continually add sprites (coloured rectangles). The key down events are repeated by calling pygame.key.set_repeat().
  2. Holding down the Enter key will continually add sprites, but limited to once every five seconds
  3. Pressing and releasing the Tab key will generate a single sprite.

Let me know if you have any questions.

import random
import pygame
import time

screen_width, screen_height = 640, 480
def get_random_position():
    """return a random (x,y) position in the screen"""
    return (random.randint(0, screen_width - 1),  #randint includes both endpoints.
            random.randint(0, screen_height - 1)) 

def get_random_named_color(allow_grey=False):
    """return one of the builtin colors"""
    if allow_grey:
        return random.choice(all_colors)
    else:
        return random.choice(non_grey)

def non_grey(color):
    """Return true if the colour is not grey/gray"""
    return "grey" not in color[0] and "gray" not in color[0]

all_colors = list(pygame.colordict.THECOLORS.items())  
# convert color dictionary to a list for random selection once
non_grey = list(filter(non_grey, all_colors))

class PowerUp(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        width, height = 12, 10
        self.color, color = get_random_named_color()
        self.image = pygame.Surface([width, height])
        self.image.fill(color)
        # Fetch the rectangle object that has the dimensions of the image
        # Update the position of this object by setting the values of rect.x and rect.y
        self.rect = self.image.get_rect().move(*get_random_position())

    def update(self):
        #move to a random position
        self.rect.center = get_random_position()

if __name__ == "__main__":
    pygame.init()
    screen = pygame.display.set_mode((screen_width, screen_height))
    pygame.display.set_caption('Sprite Collision Demo')
    clock = pygame.time.Clock() #for limiting FPS
    FPS = 60
    exit_demo = False
    regulating = False
    reg_start = 0

    pygame.key.set_repeat(300, 200)

    #pygame.mouse.set_cursor(*pygame.cursors.ball)
    #create a sprite group to track the power ups.
    power_ups = pygame.sprite.Group()
    for _ in range(10):
        power_ups.add(PowerUp()) # create a new power up and add it to the group.

    # main loop
    while not exit_demo:
        for event in pygame.event.get():            
            if event.type == pygame.QUIT:
                exit_demo = True
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    exit_demo = True
                elif event.key == pygame.K_SPACE:
                    power_ups.add(PowerUp())
                    #power_ups.update()
                elif event.key == pygame.K_RETURN:
                    if not regulating:
                        reg_start = time.time()
                        power_ups.add(PowerUp())
                        regulating = True
                    else:
                        # limit to five seconds intervals
                        elapsed_ms = time.time() - reg_start
                        ##print("Regulating", elapsed_ms)
                        if elapsed_ms > 5:
                            regulating = False

            elif event.type == pygame.KEYUP:
                if event.key == pygame.K_TAB:
                    power_ups.add(PowerUp())                

            elif event.type == pygame.MOUSEBUTTONUP:
                for _ in range(10):
                    power_ups.add(PowerUp())
        # check for collision
        for p in power_ups:
            if p.rect.collidepoint(pygame.mouse.get_pos()):
                power_ups.remove(p)
                print(f"Removed {p.color} power up")

        # clear the screen with a black background
        screen.fill(pygame.Color("black"))
        # draw sprites
        power_ups.draw(screen)
        # update the surface
        pygame.display.update()
        # limit the frame rate
        clock.tick(FPS)
    pygame.quit()
    quit()

Upvotes: 1

Related Questions