我的python函数不会返回或更新值
作者:互联网
def getMove(win,playerX,playerY):
#Define variables.
movePos = 75
moveNeg = -75
running = 1
#Run while loop constantly to update mouse's coordinates.
while(running):
mouseCoord = win.getMouse()
mouseX = mouseCoord.getX()
mouseY = mouseCoord.getY()
print "Mouse X = ", mouseX
print "Mouse Y = ", mouseY
if mouseX >= playerX:
playerX = movePos + playerX
running = 0
elif mouseX <= playerX:
playerX = moveNeg + playerX
running = 0
elif mouseY >= playerY:
playerY = movePos + playerY
running = 0
elif mouseY <= playerY:
playerY = moveNeg + playerY
running = 0
return playerX,playerY
def main():
#Create game window.
win = GraphWin("Python Game", 500, 500)
drawBoard(win)
#Define variables.
playerX = 75
playerY = 125
keyX = 325
keyY = 375
running = 1
#Create Key and Player objects, draw the key, but don't draw the player yet.
key = Text(Point(keyX,keyY),"KEY")
key.draw(win)
while(running):
print "player X = ", playerX
print "Player Y = ", playerY
drawBoard(win)
getMove(win,playerX,playerY)
player = Circle(Point(playerX,playerY),22)
player.setFill('yellow')
player.draw(win)
main()
我正在使用图形库来创建游戏.我的播放器和钥匙绘制在正确的位置.但是,当调用getMove函数时,我的playerX和playerY不会更新.我添加了调试打印语句以在运行游戏时查找其值,并且始终为75和125.
解决方法:
在python中,整数是不可变的-当您为变量分配新的整数值时,您只是使变量指向新的整数,而不更改其指向的旧整数值.
(列表是python中可变对象的一个示例,您可以对其进行修改,并且指向该列表的所有变量都将注意到更改-因为LIST已更改.)
同样,当您将变量传递给python中的方法,然后更改该方法中该变量指向的内容时,由于该变量是新变量,因此您也无需更改该变量指向该方法之外的内容.
要解决此问题,请将返回的playerX,playerY分配给方法之外的变量:
playerX,playerY = getMove(win,playerX,playerY)
标签:python,function,return,return-value 来源: https://codeday.me/bug/20191011/1893112.html