第一篇文章,并且只学习了 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
请您参考如下方法:
问题是范围界定的问题。 score1 和 score2 这两个变量在所谓的全局范围内。但是您想在函数中本地使用它们。 Python 尝试通过分配一个局部变量 score1 或 score2 来分别创建一个名为 score1 或 score2 的局部变量,然后添加 1. 由于该变量尚不存在,因此您会看到您看到的错误消息。
为了访问全局变量,您必须像这样显式标记它们:
[...]
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()
[...]
