position函数中的第一个if语句将
我正在使用朗顿蚂蚁算法制作一个游戏。在这种情况下,我希望列表平铺将数字更新为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)
在线:
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
tiles[posx][posy]
设置为0。下面的下一个if语句将其设置回1。用else语句替换第二个语句:
if the_tiles[posx][posy] == 1:
the_tiles[posx][posy] = 0
else:
the_tiles[posx][posy] = 1