我想做一个隐藏的按钮,当你在它上面移动时,它会显示出来,然后在短时间按下它时亮起(在我的脚本中是2秒),然后运行一个函数。我实现了一个在我看来合乎逻辑的机制来完成这个任务。我得到一个变量引用错误。你知道吗
这是我的按钮类:
class Button:
def __init__(self, imgInAc, imgAc, posX, posY, width, height, function, gameInstance, hiddenButton):
self.imgInAc = pygame.image.load(imgInAc)
self.imgAc = pygame.image.load(imgAc)
self.posX = posX
self.posY = posY
self.w = width
self.h = height
self.function = function
self.gameInstance = gameInstance
self.hiddenButton = hiddenButton
# Make clickDump false, to make sure, refTiem gets measured only once after the button press,
# because otherweise it would get overwritten over and over again while the game loop is running
self.clickDump = False
def button(self):
# Measure the current time to later run the button function while displaying the active image before doing so.
curTime = time.clock()
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if self.posX+self.w > mouse[0] > self.posX and self.posY+self.h > mouse[1] > self.posY:
if self.hiddenButton == False:
self.gameInstance.gameDisplay.blit(self.imgAc,(self.posX,self.posY))
if click[0] == 1:
buttonFunctions.buttonFunctions(self.function)
# If the button is a ahidden one, go through teh following protocol
elif self.hiddenButton == True:
# Display the off version if the mouse hovers over it
self.gameInstance.gameDisplay.blit(self.imgInAc,(self.posX,self.posY))
if click[0] == 1:
# if you click on it, display teh active version
self.gameInstance.gameDisplay.blit(self.imgAc,(self.posX,self.posY))
###print curTime
# If clickDump is false, defien teh reference time relative to teh current time.
# Then make it true, so the ref time doesn't get changed again, while the game loop is running
if self.clickDump == False:
refTime = time.clock()+2
###print refTime
self.clickDump = True
# If ClickDump is true, check if teh time condition is satiesfied. Note, that this check is run outside the "if click[0] == 1"-scope,
# to make sure, it also gets checked if the click happened in a previoues cycle.
if self.clickDump == True:
# If the time interval between the click event and the current time has elapsed
# set clickDUmp back to flase, so it can be used for teh next button press protocol
# and finally run the button function.
if curTime > refTime:
self.clickDump = False
buttonFunctions.buttonFunctions(self.function)
else:
if self.hiddenButton == False:
self.gameInstance.gameDisplay.blit(self.imgInAc,(self.posX,self.posY))
错误是:
“…第296行,输入按钮
如果curTime>;参考时间:
UnboundLocalError:赋值前引用了局部变量'refTime'”
我真的不明白这一点,因为我以为只有在refTime初始化的情况下才执行比较时间变量的部分,因为在refTime赋值的部分,条件或运行比较onyl得到满足。你知道吗
对不起,我的通讯可能有很多错别字。。。我只是为自己写的。你知道吗
所以。。。我很困惑。你知道吗
这是由于
refTime
的范围造成的。你知道吗reftime
在某些if
循环中赋值,而在另一个if
循环中使用。你知道吗像这样分配。你知道吗
相关问题 更多 >
编程相关推荐