Python列表变量未被ifstatement子句修改

2024-09-29 06:26:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用Langton's ant算法做一个游戏。在这种情况下,我希望列表平铺将数字更新为0。。。但是没有。为什么?你知道吗

注:方向变量基于指南针(n、e、w、s)

posx = 4
posy = 4
direction = 'w'

tiles = [[1,1,1,1,1,1,1,1,1,1],
     [1,1,1,1,1,1,1,1,1,1],
     [1,1,1,1,1,1,1,1,1,1],
     [1,1,1,1,1,1,1,1,1,1],
     [1,1,1,1,1,1,1,1,1,1],
     [1,1,1,1,1,1,1,1,1,1],
     [1,1,1,1,1,1,1,1,1,1],
     [1,1,1,1,1,1,1,1,1,1],
     [1,1,1,1,1,1,1,1,1,1],
     [1,1,1,1,1,1,1,1,1,1]]
def posision(posx, posy, tiles, direction):
    if tiles[posx][posy] == 1:
        tiles[posx][posy] = 0
    if tiles[posx][posy] == 0:
        tiles[posx][posy] = 1

    oldTiles = tiles

    if direction == 'n':
        if oldTiles[posx][posy] == 1:
            posx = posx+1
            return 'w', tiles
        if oldTiles[posx][posy] == 0:
            posx = posx-1
            return 'e', tiles
    if direction == 's':
        if oldTiles[posx][posy] == 0:
            posx = posx+1
            return 'w', tiles
        if oldTiles[posx][posy] == 1:
            posx = posx-1
            return 'e', tiles
    if direction == 'e':
        if oldTiles[posx][posy] == 1:
            posy = posy +1
            return 'n', tiles
        if oldTiles[posx][posy] == 0:
            posy = posy -1
            return 's', tiles
    if direction == 'w':
        if oldTiles[posx][posy] == 0:
            posy = posy +1
            return 'n', tiles
        if oldTiles[posx][posy] == 1:
            posy = posy -1
            return 's', tiles

direction, tiles = posision(posx, posy, tiles, direction)
print(tiles)

Tags: 算法游戏列表returnif情况tiles平铺
3条回答

在这条线上:

if tiles[posx][posy] == 1:
        tiles[posx][posy] = 0
    if tiles[posx][posy] == 0:
        tiles[posx][posy] = 1

你是说:

IF some_var IS 1
    change it to 0  # I've changed it to 0 already
   IF some_var IS 0 # BUt now I am changing back to 1?
     change it to 1

我不确定这是否是你的游戏逻辑?您可能应该将其更改为:

if tiles[posx][posy] == 1:
        tiles[posx][posy] = 0
elif tiles[posx][posy] == 0:  # An else-if condition
        tiles[posx][posy] = 1

我还建议您重新访问您的流控制逻辑,即所有的IF-ELSE逻辑,看看我的解释是否对您有意义。IF-ELSE-sphagetti是一个常见的问题,甚至有时专家也会提出。但一旦你想清楚了,就没事了。你知道吗

一个明显的问题是代码后面IF块中的oldTiles修改。你知道吗

不要使用所有if语句,请尝试:

the_tiles[posx][posy] ^= 1

position函数中的第一个if语句将tiles[posx][posy]设置为0。下面的下一个if语句将其设置回1。将第二个替换为else语句:

if the_tiles[posx][posy] == 1:
    the_tiles[posx][posy] = 0
else:
    the_tiles[posx][posy] = 1

相关问题 更多 >