Python列表变量未被if语句子句修改

时间:2015-03-21 00:49:38

标签: python python-2.7 if-statement

我正在使用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)

3 个答案:

答案 0 :(得分:2)

在这一行:

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是有时甚至专家都会遇到的常见问题之一。但是一旦你搞清楚,就可以了。

显而易见的一个是在代码块中进一步向下修改oldTiles

答案 1 :(得分:1)

而不是所有if语句,请尝试:

the_tiles[posx][posy] ^= 1

答案 2 :(得分:0)

位置函数中的第一个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