我正在尝试使用面包板,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
答案 0 :(得分:0)
这应该有效:
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
让我知道是否可以。
欢呼