2
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。求助!

4

3 回答 3

9

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

(python 中可变对象的一个​​示例是列表,您可以对其进行修改,并且指向该列表的所有变量都会注意到更改 - 因为 LIST 已更改。)

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

为了解决这个问题,将返回的 playerX,playerY 分配给方法外的变量:

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

于 2013-04-09T00:16:07.937 回答
1

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

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

希望这可以帮助!

于 2013-04-09T00:15:51.547 回答
0

如前所述,解决方案是您没有使用返回的值来更新您的值,playerX, playerY这可以通过上述方法修复

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

我要解决的是您if陈述中的逻辑。您构建if语句的方式将导致仅更新 X 或 Y,而不是两者。例如,如果mouseX, mouseY两者都大于playerX, playerY相应,您将到达if语句的第一行,它将被评估为True并相应地更新playerX,但是因为第一个语句已经执行,其他elif语句都不会执行,导致你只更新playerX变量。

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

    if mouseX >= playerX:
        playerX = movePos + playerX
        running = 0
    elif mouseX <= playerX:
        playerX = moveNeg + playerX           
        running = 0

    #By having the second if, it allows you to check Y even if X has changed
    if mouseY >= playerY:
        playerY = movePos + playerY            
        running = 0
    elif mouseY <= playerY:
        playerY = moveNeg + playerY            
        running = 0
于 2013-04-09T01:21:05.670 回答