使用 python3 和树莓派 pi3 的两个按钮反应游戏

two button reaction game using python3 and raspberry pi3

第一个 post 并且只学习了 Python 3 周...

我正在尝试创建一个游戏,其中 2 名玩家必须等待连接到面包板的蜂鸣器声音,然后按下按钮以查看谁是第一个。

在我尝试添加一种保持分数的方法之前,它工作得很好。现在,当游戏运行时,按下按钮时蜂鸣器不会停止,并且我收到几条在 window 中重复出现的错误消息。谁能帮我看看我做错了什么?

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

led1 = LED(17)
led2 = LED(27)
btn1 = Button(14)
btn2 = Button(15)
buz = Buzzer(22)
score1 = 0
score2 = 0

btn1_name = input('right player name is ')
btn2_name = input('left player name is ')

while True:
    print(btn1_name + ' ' + str(score1) + ' - ' + btn2_name + ' ' + str(score2))
    sleep(randint(1,10))
    buz.on()
    def pressed(button):
        if button.pin.number == 14:
            print(btn1_name + ' won the game')
            score1 += 1
        else:
            print(btn2_name + ' won the game')
            score2 += 1
        buz.off()
    btn1.when_pressed = pressed
    btn2.when_pressed = pressed

输出信息如下

dave 0 - keith 0
keith won the game
Traceback (most recent call last):
  File "/usr/local/lib/python3.4/dist-packages/gpiozero/pins/rpigpio.py", line 232, in <lambda>
    callback=lambda channel: self._when_changed(),
  File "/usr/local/lib/python3.4/dist-packages/gpiozero/mixins.py", line 311, in _fire_events
    self._fire_activated()
  File "/usr/local/lib/python3.4/dist-packages/gpiozero/mixins.py", line 343, in _fire_activated
    super(HoldMixin, self)._fire_activated()
  File "/usr/local/lib/python3.4/dist-packages/gpiozero/mixins.py", line 289, in _fire_activated
    self.when_activated()
  File "/usr/local/lib/python3.4/dist-packages/gpiozero/mixins.py", line 279, in wrapper
    return fn(self)
  File "/home/d.chilver/twobuttonreaction.py", line 26, in pressed
    score2 += 1
UnboundLocalError: local variable 'score2' referenced before assignment
dave 0 - keith 0

问题是范围的问题。 score1score2 这两个变量在所谓的全局范围内。但是您想在函数中本地使用它们。 Python 尝试通过分配局部变量 score1score2 然后加 1 来分别创建一个名为 score1score2 的局部变量。由于变量不存在,您将看到您看到的错误消息。

为了访问 global 变量,您必须像这样明确标记它们:

[...]
def pressed(button):
    global score1
    global score2
    if button.pin.number == 14:
        print(btn1_name + ' won the game')
        score1 += 1
    else:
        print(btn2_name + ' won the game')
        score2 += 1
    buz.off()
[...]