您如何通过按下游戏手柄按钮(用户输入)来跳出 while 循环

我使用 pygame 只是为了在我的脚本中使用 xbox 控制器。我的目标是按下一个按钮开始一个重复的任务,然后能够按下另一个按钮来打破重复的任务。然后我应该可以按原始按钮恢复任务。

在我发布代码之前,我知道我的问题的症结在这里:(我的缩进有问题,但代码有效)。

while True:
                            schedule.run_pending()
                            time.sleep(1)

如何跳出这个 while 循环以便我可以使用下一个按钮 JOYHATMOTION: 基本上我会使用 JOYHATMOTION 来暂停 job 函数。

这是代码。它每 5 秒打印一次“Hello World”,持续 200 秒。

import schedule
from datetime import datetime,timedelta,time
import time
import sys

import pygame

from pygame.locals import *
pygame.init()


def job():
    print('Hello World')


pygame.joystick.init()
joysticks = [pygame.joystick.Joystick(i) for i in range(pygame.joystick.get_count())]
for joystick in joysticks:
    print(joystick.get_name())

while True:
    for event in pygame.event.get():
        if event.type == JOYBUTTONDOWN:
            print(event)
            if event.button == 8:

                schedule.every(5).seconds.until(timedelta(seconds=200)).do(job)

                while True:
                            schedule.run_pending()
                            time.sleep(1)

        if event.type == JOYHATMOTION:
            if event.value[0] == 1:
                print(event)
                

            if event.value[0] == -1:
                print(event)

        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        if event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                pygame.quit()
                sys.exit()

我试过了:

while True:
                if event.type == JOYHATMOTION:
                    if event.value[0] == 1:
                        break
                    else: 
                           schedule.run_pending()
                           time.sleep(1)

但这似乎有效。提前致谢。

hacldt 回答:您如何通过按下游戏手柄按钮(用户输入)来跳出 while 循环

切勿尝试在应用程序循环内部使用循环来控制应用程序。使用应用程序循环。应用程序循环不断执行。使用 double x = 0; double y = 0; double radius; void updatePosition({ @required double centerX,@required double centerY,}) { radius = min(centerX,centerY); x = centerX + radius * cos(angle * -pi / 90); y = centerX + radius * sin(angle * -pi / 90); angle += 5; } 变量指示应用程序的当前状态。根据变量的状态执行应用程序中的代码。
使用这种方法,您可以在按下另一个键时轻松地将状态改回。

game_state
本文链接:https://www.f2er.com/587.html

大家都在问