第一篇文章,并且只学习了3个星期的Python ...

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

在我尝试添加一种保持得分的方法之前,这种方法效果很好。现在,当游戏运行时,按下按钮时蜂鸣器不会停止,并且我会在窗口中看到重复的错误消息。有人可以帮我看看我做错了什么吗?

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的局部变量。由于该变量尚不存在,因此您将遇到以下错误消息:看到。

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

[...]
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()
[...]

10-04 21:47