我的python函数不会返回或更新值

时间:2013-04-09 00:12:42

标签: python function return return-value

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.帮助!

3 个答案:

答案 0 :(得分:9)

在python中,整数是不可变的 - 当你为变量赋一个新的整数值时,你只是让变量指向一个新的整数,而不是改变它指向的值的旧整数。

(python中可变对象的一个​​例子就是列表,你可以修改它,指向该列表的所有变量都会注意到这个变化 - 因为LIST已经改变了。)

类似地,当您将变量传递给python中的方法然后更改该变量指向该方法的内容时,您不会更改该变量指向该方法之外的内容,因为它是一个新变量。

要解决此问题,请将返回的playerX,playerY分配给方法之外的变量:

playerX, playerY = getMove(win,playerX,playerY)

答案 1 :(得分:1)

调用getMove()时,应明确重新分配这些变量:

playerX, playerY = getMove(win, playerX, playerY)

希望这有帮助!

答案 2 :(得分:0)

正如已经提到的,解决方案是您没有使用返回的值来更新playerX, playerY,可以使用上面提到的

来修复
playerX, playerY = getMove(win,playerX,playerY)

我想要解决的是if语句中的逻辑。构建if语句的方式将导致仅更新X或Y,而不是两者。例如,如果mouseX, mouseY分别大于playerX, playerY,那么您将转到if语句的第一行,它将被评估为True并更新{ {1}}因此,但是因为第一个语句已经执行,其他playerX语句都不会执行,导致您只更新elif变量。

您要做的是将playerX语句拆分为两个单独的语句(一个用于X,一个用于Y),以便X,Y的调整彼此独立。类似于

的东西
if