【问题标题】:Can you run multiple conditions simultaneously in python?你可以在python中同时运行多个条件吗?
【发布时间】:2019-11-19 02:47:43
【问题描述】:

我正在尝试使用面包板、LED 和几个按钮在树莓派上创建游戏。我想要代码做的是同时打开 2 个 LED(每个玩家一个),然后计算反应时间并取平均值,看看谁在回合结束时的平均值最低。我遇到的问题是,以我现在的方式运行 for 循环总是必须先按下按钮 1 (btn1),然后再向下移动代码。有没有办法同时读取两个按钮?

from gpiozero import Button, LED
from time import time, sleep
from random import randint

btn1 = Button(27)

led1 = LED (17)

total1 = 0

btn2= Button(26)

led2 = LED(13)

total2 = 0 

for x in range(3):
    sleep(randint(1,2))
    start = time()
    led1.on()
    led2.on()
    btn1.wait_for_press()
    led1.off()
    end1 = time()
    btn2.wait_for_press()
    led2.off()
    end2 = time()
    reaction_time1 = end1-start
    reaction_time2 = end2-start
    print('PLayer 1: you took', reaction_time1,'seconds')
    total1=total1+reaction_time1
    print('Player 1 average is', total1/(x+1), 'seconds')
    reaction_time1=end1-start
    print('PLayer 2: you took', reaction_time2,'seconds')
    total2=total2+reaction_time2
    print('Player 2 average is', total2/(x+1), 'seconds')
    reaction_time2=end2-start

【问题讨论】:

  • 使用multithreading。您可以等待两个按钮同时按下。
  • 我认为您可能想花一些时间阅读gpiozero 文档。例如,Button class 有一个 .when_pressed 方法,可以让你更接近你想要的。
  • Multiprocessing vs Threading Python 这是您正在寻找的主题。您的进程受 I/O 限制。你需要学习多线程以确保你能正确地做到这一点,但是对于一个单一的答案来说,深入所有这些细节可能太多了,而且你从其他人为你解决所有问题中得到的东西很少。

标签: python raspberry-pi


【解决方案1】:

这应该可行:

from gpiozero import Button, LED
from time import time, sleep
from random import randint

def time1():
    led1.off()
    end1 = time()

def time2():
    led2.off()
    end2 = time()

btn1 = Button(27)

led1 = LED (17)

total1 = 0

btn2= Button(26)

led2 = LED(13)

total2 = 0 

for x in range(3):
    sleep(randint(1,2))
    start = time()
    led1.on()
    led2.on()
    end = 0
    end1 = 0
    end2 = 0
    while(end == 0):
        if(end1 == 0):
            btn1.when_pressed = time1
        if(end2 == 0):
            btn2.when_pressed = time2
        if(end1 != 0 and end2 != 0):
            end = 1
    reaction_time1 = end1-start
    reaction_time2 = end2-start
    print('PLayer 1: you took', reaction_time1,'seconds')
    total1=total1+reaction_time1
    print('Player 1 average is', total1/(x+1), 'seconds')
    reaction_time1=end1-start
    print('PLayer 2: you took', reaction_time2,'seconds')
    total2=total2+reaction_time2
    print('Player 2 average is', total2/(x+1), 'seconds')
    reaction_time2=end2-start

如果有,请告诉我。

干杯

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    • 1970-01-01
    相关资源
    最近更新 更多