第一篇文章,并且只学习Python 3周......
我正在尝试创建一个游戏,其中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
答案 0 :(得分:1)
问题是范围界定的问题。两个变量<table id="table">
<thead>
<tr>
<th data-field="state" data-checkbox="true"></th>
<th data-field="name">Name</th>
<th data-field="stargazers_count">Stars</th>
<th data-field="forks_count">Forks</th>
</tr>
</thead>
</table>
JSON temp.json
{
"Name": "Julie own",
"Account": "C0010",
"LoanApproved": "12/5/2015",
"LastActivity": "4/1/2016",
"PledgedPortfolio": "1000000",
"MaxApprovedLoanAmt": "1000000",
"LoanBalance": "1849000",
"AvailableCredit": "201877.824375",
"Aging": "3",
"Brokerage": "My Broker",
"Contact": "R Johnson",
"ContactPhone": "-3614",
"RiskCategory": "Yellow",
"rows": [{
"Account": "086-1234",
"ClientName": "Sal Smith",
"AccountType": "Ret",
"LongMarketValue": "$450000"
}, {
"Account": "086-1235",
"ClientName": "y Smith",
"AccountType": "Trust",
"LongMarketValue": "$550000"
},
{
"Account": "086-1236",
"ClientName": "y Smith",
"AccountType": "Retail",
"LongMarketValue": "$550000"
}]
}
和score1
位于所谓的全局范围内。但是你想在函数中本地使用它们。 Python尝试通过分配局部变量score2
或score1
然后添加1来分别创建一个名为score2
或score1
的局部变量。由于该变量尚不存在,受到您看到的错误消息。
要访问全局变量,您必须明确标记它们:
score2