首页 > 解决方案 > Pygame:添加一个 Escape 键以使用秒表功能退出整个游戏

问题描述

我正在Raspberry Pi上通过Python制作游戏。我正在使用 GPIO 来点亮 LED 并检测按钮开关。

我想在键盘上加入一个 ESC,这样我们就可以随时退出。

但是每当我将 ESC 键代码添加到主 while 循环中时。它不起作用。LED 和按钮工作,但是当我按下 ESC 键时,它什么也没做。循环运行以刷新/运行秒表并通过 GPIO 监听 LED 按钮。

我想要一些关于如何在游戏中处理诸如 ESC 键之类的东西的建议。特别是对于循环和循环非常快的快节奏游戏。

任何提示或建议将不胜感激。提前致谢。

请看下面的代码:

# Importing all libraries
import RPi.GPIO as GPIO
import sys, time, atexit, pygame

# Setup GPIO and Pygame
GPIO.setmode(GPIO.BCM)
pygame.init()

# Define Tuples and Variables
leds = (16,17,22,9,5)
switches = (19,4,27,10,11)
button_pressed = False
taskcomplete = False

# Pygame visual variables
screen = pygame.display.set_mode( (1024,240) )
counterfont = pygame.font.Font('DSEG14Modern-Regular.ttf', 70)

# Set Pygame refresh rate variable = clock 
clock = pygame.time.Clock()

# Clock variables
sec_val = 0
sec = 0
mins = 0
hours = 0

# Status variables
paused  = False
running = True

# Start the clock
start_time = pygame.time.get_ticks() 

# Defining Functions

# Function that renders segment display on screen 
def time_convert(sec):
    sec = sec % 60
    sec_val = ("Timer: {0}".format(round((sec), 2)))
    counting_text = counterfont.render(str(sec_val), 3, (134,145,255))
    counting_rect = counting_text.get_rect(left = screen.get_rect().left)
    screen.fill( (0,0,0) )
    screen.blit(counting_text, (300,40))
    pygame.display.update()
    
# Stopwatch function to compute for a SS:MS based stopwatch
def stop_Watch():
    end_time = time.time()
    time_lapsed = end_time - start_time
    sec_val = time_convert(time_lapsed)

# Press Button 1 to start the game
def but_3():
    while GPIO.input(switches[2]) == GPIO.LOW:
        GPIO.output(leds[2],True)
        time.sleep(0.01)
        stop_Watch()
    GPIO.output(leds[2],False)
    print(" Button 3 is pressed! Exit")

start_time = time.time()

def buttonPress(channel):
    # This function gets called every time a button is pressed, if the button pressed is the same as the button
    # that is illuminated, then we set the "correct_button" variable to True,
    # otherwise we set the "incorrect_button" variable to True.
    # We need to set some variables to global so that this function can change their value.
    button_pressed = True

def exit():
    # This function gets called when we exit our script, using Ctrl+C
    print("GPIO Clean Up!")
    GPIO.cleanup()
    pygame.quit()


# This tells our script to use the "exit()" without this, our "exit()" function would never be called.
atexit.register(exit)

#Loop through the leds to set them up
for led in leds:
    # Set the led to be an ouput
    GPIO.setup(led, GPIO.OUT)
    # Turn the led off
    GPIO.output(led,False)

# Loop through the switches to set them up
for switch in switches:
    # Set the switch to be an input
    GPIO.setup(switch, GPIO.IN)
    # Add rising edge detection
    GPIO.add_event_detect(switch, GPIO.RISING, bouncetime=300)
    # Add the function "buttonPress" to be called when switch is pressed.
    GPIO.add_event_callback(switch, buttonPress)


# Main sequence code
# Setup Pygame refresh rate to 120 fps
clock.tick(120)
# Start timer
start_time = time.time()

# Main loop
while running:
    # Press Button 1 to start the game
    while GPIO.input(switches[0]) == GPIO.LOW:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    print("escape pressed")
                    running = False

        GPIO.output(leds[0],True)
        time.sleep(0.01)
        stop_Watch()
    GPIO.output(leds[0],False)
    print(" Button 1 is pressed! Exit")
    running = False
exit()

标签: pythonpygame

解决方案


这是因为我猜它在另一个while循环中,所以它不再在runningwhile循环中。您可以添加pygame.quit()以使其退出这种方式:

# Main loop
while running:
    # Press Button 1 to start the game
    while GPIO.input(switches[0]) == GPIO.LOW:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                running = False

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    print("escape pressed")
                    pygame.quit()
                    running = False

        GPIO.output(leds[0],True)
        time.sleep(0.01)
        stop_Watch()
    GPIO.output(leds[0],False)
    print(" Button 1 is pressed! Exit")
    running = False
exit()

或者,由于您有一个名为的函数exit()执行相同的操作,因此您可以添加exit()到这些位置。


推荐阅读