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.求助!
I am using a graphics library to create a game. My player and key are drawn in the correct places. However, when calling the getMove function, my playerX and playerY do not update. I have added debug print statements to find their values while running the game and it is always 75 and 125. Help!
在python中,整数是不可变的——当你给一个变量分配一个新的整数值时,你只是让变量指向一个新的整数,而不是改变什么它指向的旧整数的值是.
In python, integers are immutable - when you assign a new integer value to a variable, you are just making the variable point to a new integer, not changing what the old integer it pointed to's value was.
(python 中可变对象的一个示例是列表,您可以对其进行修改,并且指向该列表的所有变量都会注意到更改 - 因为 LIST 已更改.)
(An example of a mutable object in python is the list, which you can modify and all variables pointing to that list will notice the change - since the LIST has changed.)
同样,当您将变量传递给 python 中的方法,然后更改该变量在该方法中指向的内容时,您不会更改该变量指向该方法之外的内容,因为它是一个新变量.
Similarly, when you pass a variable into a method in python and then alter what the variable points to in that method, you do not alter what the variable points to outside of that method because it is a new variable.
为了解决这个问题,将返回的 playerX,playerY 分配给方法外的变量:
To fix this, assigned the returned playerX,playerY to your variables outside the method:
playerX, playerY = getMove(win,playerX,playerY)
这篇关于我的 python 函数不会返回或更新值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!