我正在制作一个鲁米纸牌游戏,但是在mouse[]
,cardx[]
,cardy[]
上有一些问题。在程序开始时,我有所有的变量,但是在子程序()
中,它似乎忘记了它们是什么。
def image(img,imgx,imgy):
screen.blit(img, (imgx,imgy))
def getmouse():
mouse=pygame.mouse.get_pos()
click=pygame.mouse.get_pressed()
mousex,mousey=mouse[0],mouse[1]
print("Mouse x:y",mousex,mousey, "Mouse Click",click[0]) #works fine here
def movableimgs():
getmouse()
for d in range(1,6):
print("Mouse x:y",mousex,mousey, "Mouse Click",click[0]) #Error here nameError: name 'mousex'is not defined
if cardx[d]<mousex>cardx[d]+71 and cardy[d]<mousey>cardy[d]+96:
drag=1
if click[0]==0:
drag=0
我对click[]
也有问题。它在getmouse()
中工作,但是当它从getmouse()
回来后就不能工作了。我在cardx[]
和cardy[]
上也遇到了麻烦。我在节目开始的时候就有全球性的了。
发布于 2019-11-30 04:47:12
全局变量和局部变量
从代码/函数
def getmouse():
mouse=pygame.mouse.get_pos()
click=pygame.mouse.get_pressed()
mousex,mousey=mouse[0],mouse[1]
print("Mouse x:y",mousex,mousey, "Mouse Click",click[0]) #works fine here
将mouse
、click
、mousex
、mousey
设置为local
变量,需要global
命令来访问在函数中设置的变量,因此您的getmouse
所以你的代码会是这样的
def getmouse():
global mouse, click, mousex, mousey
mouse=pygame.mouse.get_pos()
click=pygame.mouse.get_pressed()
mousex,mousey=mouse[0],mouse[1]
print("Mouse x:y",mousex,mousey, "Mouse Click",click[0]) #works fine here
但是这不是一种有效的方法,所以您应该将getmouse
函数更改为
def getmouse():
mouse=pygame.mouse.get_pos()
click=pygame.mouse.get_pressed()
mousex,mousey=mouse[0],mouse[1]
print("Mouse x:y",mousex,mousey, "Mouse Click",click[0]) #works fine here
globals().update(locals()) #this is the effective way, and pythonic
所以你的完整代码是
def image(img,imgx,imgy):
screen.blit(img, (imgx,imgy))
def getmouse():
mouse=pygame.mouse.get_pos()
click=pygame.mouse.get_pressed()
mousex,mousey=mouse[0],mouse[1]
print("Mouse x:y",mousex,mousey, "Mouse Click",click[0]) #works fine here
globals().update(locals())
def movableimgs():
getmouse()
for d in range(1,6):
print("Mouse x:y",mousex,mousey, "Mouse Click",click[0]) #Error here nameError: name 'mousex'is not defined
if cardx[d]<mousex>cardx[d]+71 and cardy[d]<mousey>cardy[d]+96:
drag=1
if click[0]==0:
drag=0
发布于 2019-11-30 04:13:39
局部变量
mousex
、mousey
和click
是被调用函数getmouse
中的局部变量。
要在调用方函数movableimgs
中使用它,您应该返回被调用函数中的值,然后将值解压到调用方函数中的变量中。
def getmouse():
mouse=pygame.mouse.get_pos()
click=pygame.mouse.get_pressed()
mousex,mousey=mouse[0],mouse[1]
print("Mouse x:y",mousex,mousey, "Mouse Click",click[0])
return mousex, mousey, click # Return the values
def movableimgs():
mousex, mousey, click = getmouse() # Unpack the values into variables
...
全局变量
问题围绕着
mouse[]
,cardx[]
,cardy[]
。click[]
的问题..。我在节目开始的时候就有全球性的了。
要将函数中的全局变量mouse
和click
赋值给它们,需要将它们声明为global
。
def getmouse():
global mouse, click # Declare global variables
mouse=pygame.mouse.get_pos()
click=pygame.mouse.get_pressed()
...
https://stackoverflow.com/questions/59112982
复制相似问题