【问题标题】:How can I prevent Pygame from getting events between two while loops?如何防止 Pygame 在两个 while 循环之间获取事件?
【发布时间】:2017-03-18 00:31:44
【问题描述】:

我一直在尝试在 Raspberry Pi 上创建一个短跑游戏,但用户可以在倒计时期间通过按箭头键来作弊。我怎样才能阻止关键事件被收集到实际的短跑片段之外?我猜我需要在“while distance

import pygame
import time
from time import sleep
from sense_hat import SenseHat

sense = SenseHat()


pygame.init()
pygame.display.set_mode((140,180))

high_score = 50
name = "no-one"
foot = 1 #only lets you start with your left foot

red = (80, 0, 0)
blue = (0, 0, 80)
gameStart = False
while True:
    print ("READY!")
    sleep(1)
    print("SET!")
    sleep(2)
    print("GO!")
    events = 0     
    distance = int(0)
    start_time = time.time()


    #sets the distance of the race (64) pixels

    while distance < 64:

        #Getting the Key input
        events = pygame.event.get()
        for event in events:
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT and foot == 1:
                    print("left")
                    foot += 1
                    distance += 1
                elif event.key == pygame.K_RIGHT and foot == 2:
                    print("right")
                    foot -= 1
                    distance += 1
        if distance == 32:
                print("Halfway There!")

        #Makes the pixels red if distance is less than the pixel number
        pixels = [blue if i < distance else red for i in range(64)]
        sense.set_pixels(pixels)

    #subtracts your finish time by your start time    
    fin_time = time.time()-start_time

    #rounds your finish time and start time to closest 100th of a second
    fin_time = round(fin_time,2)


    print("Finish!")
    print (fin_time)


    #checks to see if your time was a high score
    if fin_time < high_score:
        print("You got a high score!")
        name = input("Please Enter your name: ")
        high_score = fin_time
        print("High Score", name, high_score)


    #gives time to prepare for next round
    sleep(5)

    print("Click back on the black pygame window")
    sleep(1)
    print("Next round in...")
    print("5")
    sleep(1)
    print("4")
    sleep(1)
    print("3")
    sleep(1)
    print("2")
    sleep(1)
    print("1")
    sleep(1)

【问题讨论】:

    标签: python while-loop raspberry-pi pygame


    【解决方案1】:

    您应该查看pygame.event.clear() 方法:http://www.pygame.org/docs/ref/event.html#pygame.event.clear。在您的情况下,这应该有效:

    ...
    pygame.event.clear()
    while distance < 64:
        for event in pygame.event.get():
            ...
    

    您还可以查看pygame.time 模块:http://www.pygame.org/docs/ref/time.html

    【讨论】:

    • 完美运行!谢谢你的帮助,善良的陌生人!
    • 如果您对某个答案感到满意,请不要忘记通过检查相应的按钮来验证和投票。在 StackOverflow 上,它就像黄金一样。顺便说一句,祝您有愉快的一天。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-01
    • 2015-12-26
    • 2016-11-05
    • 1970-01-01
    • 2019-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多