如何在条件下调节python中的函数?

时间:2018-05-05 15:28:34

标签: python-3.x function pygame

我在pygame中有一个函数,当用户按下空格时我必须运行它。但问题是,只要按下空格,该功能就会运行不止一次。我希望它运行一次,如果用户再次按空格,我希望该功能再次运行 - 一次。

下面的一些代码

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

现在God()在我希望每次用户按空格时一次绘制一个形状的同时绘制一堆形状。上帝()只被召唤一次。它从1到100中选取一个随机数,以便为每个形状创建概率。

1 个答案:

答案 0 :(得分:1)

对于您的问题,需要Minimal, Complete and Verifiable Example来获得更具体的帮助。

以下示例显示以下内容:

  1. 按住空格键以不断添加精灵(彩色矩形)。通过调用pygame.key.set_repeat()重复关键事件。
  2. 按住 Enter 键将不断添加精灵,但限制为每五秒钟一次
  3. 按下并释放 Tab 键将生成一个精灵。
  4. 如果您有任何问题,请与我们联系。

    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()