Как регулировать функцию в Python при условии? - PullRequest
0 голосов
/ 05 мая 2018

У меня есть функция в pygame, которую я должен запускать, когда пользователь нажимает пробел. Однако проблема в том, что как только нажимается пробел, функция запускается гораздо чаще, чем один раз. Я хочу, чтобы он запускался один раз, и если пользователь снова нажимает пробел, я хочу, чтобы функция запускалась снова - один раз.

Код ниже

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

Теперь Бог () рисует множество фигур одновременно, когда я хочу, чтобы он рисовал одну фигуру за раз, каждый раз, когда пользователь нажимает пробел. Бог () вызывается только один раз. Он выбирает случайное число от 1 до 100, чтобы получить вероятности для каждой фигуры.

1 Ответ

0 голосов
/ 08 мая 2018

A Минимальный, полный и проверяемый пример требуется для более конкретной помощи по вашей проблеме.

Ниже приведен пример, который показывает следующее:

  1. Удерживая нажатой клавишу Пробел , можно непрерывно добавлять спрайты (цветные прямоугольники). События нажатия клавиш повторяются путем вызова pygame.key.set_repeat () .
  2. Удерживая нажатой клавишу Enter , вы будете постоянно добавлять спрайты, но не более одного раза в пять секунд
  3. Нажатие и отпускание клавиши Tab создаст один спрайт.

Дайте мне знать, если у вас есть какие-либо вопросы.

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()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...