【问题标题】:Board not updating position in python. The variable resets itself董事会未在 python 中更新位置。变量自行重置
【发布时间】:2021-05-11 10:05:19
【问题描述】:

我在文件 a 中有以下代码:

while(won == False):
    game.userY = setGameRow(row, counter)
    game.userX = setGameCol(col, counter)
    counter+=1
    printBoard(bd, game.userX , game.userY)
    move(row, col, bd, mines, game.userX, game.userY)
    won = retWon() 

在文件 b 中:

def move(row, col, bd, mines, userX, userY):
    i = inp()
    if(i == "w"):
        movX = 0
        movY = -1
    elif(i == "a"):
        movX = -1
        movY = 0
    elif(i == "s"):
        movX = 0
        movY = 1
    elif(i == "d"):
        movX = 1
        movY = 0

    if((userY == 0 and inp == "w") or (userY == col-1 and inp == "s") or (userX == 0 and inp == "a") or (userX == row-1 and inp == "d")):
        print("Invalid movement")
        move(row, col, bd, mines)

    userX += movX
    userY += movY
    

    if(getNumbers(userX, userY, bd) == 9):
        lost(mines, row, col)
    if(userX==0 and userY == 0):
        win(mines, row, col)

电路板如下所示:

Where do you want to go? w
+----------+
|··········|
|··········|
|··········|
|··········|
|··········|
|··········|
|··········|
|··········|
|········00|
|········0*|
+----------+

玩家是·

执行printBoard() 时,userX 和 userY 再次更改为默认值。我知道它们确实会发生变化,但它们最终总是会变回默认值,因此当我移动播放器时棋盘不会更新。

【问题讨论】:

  • 由于我们看不到您的完整代码,因此很难说您是如何在函数之间传递属性的。我从你的代码 sn-p 的猜测是 userX 和 userY 只在你的 move 函数中本地更新,而不是在你的脚本中全局更新

标签: python loops variables


【解决方案1】:

当你这样做时:

userX += movX
userY += movY

move() 函数中,您只需要修改在收到game.userXgame.userY 作为参数时创建的局部变量。 game 对象的属性不会更改(除非该值不太可能就地更新)。

您可能需要将game 对象传递给move 函数,以便它可以直接进行属性更新。或者类似的东西,你只展示了足够少的代码,并不完全清楚最好的设计是什么。例如,我可能认为创建一个Player 类可能有意义,它可以跟踪自己的xy 坐标。那么move() 函数可能会成为该类的方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-04
    相关资源
    最近更新 更多