我对编程非常陌生,但是我认为尝试对Langton的蚂蚁进行编程会很有趣。对于不认识的人来说,它是一只在木板上四处走动的蚂蚁。当它碰到一个红色方块时,它会向右转并为红色方块涂上白色,当它碰到一个白色方块时,它会向左转,将上一个白色方块涂成红色。利用我非常原始的编程知识,我想到了以下程序:
def Move(direction):
global x
global y
if direction % 4 == 0:
y += 1
elif direction % 4 == 1:
x += 1
elif direction % 4 == 2:
y -= 1
else:
x -= 1
Lred = []
Lwhite = []
# To make sure the program recognizes the squares as being white initially.
for i in range(-4, 5):
for i2 in range(-4, 5):
Lwhite.append([i2,i])
x = 0
y = 0
direct = 0
# Here I try to make the first 10 steps.
for i in range(10):
print [x,y]
if [x,y] in Lred:
Lred.remove([x,y])
Lwhite.append([x,y])
direct-=1
if [x,y] in Lwhite:
print "white square"
Lwhite.remove([x,y])
Lred.append([x,y])
direct+=1
Move(direct)
print Lwhite
print Lred
如您所见,当您运行该程序时,它说方块在第二次达到[0,0]时是白色的,但是当它开始时,它应该已经被涂成红色。[0,0]在最后打印的红色正方形列表中,而不在白色正方形列表中。这就是我想要的。
但是,为什么它仍然认为“ Lwhite中的[if,x,y]”是正确的呢?
每次您的蚂蚁碰到方形时,它都会检查它是否为红色。如果为红色,则将正方形变成白色并旋转蚂蚁。然后,它检查正方形是否为白色,这始终是正确的,因为如果正方形为红色,则上一步将其变为白色。使用elif
语句而不是if
语句将解决此问题。
# Here I try to make the first 10 steps.
for i in range(10):
print [x,y]
if [x,y] in Lred:
Lred.remove([x,y])
Lwhite.append([x,y])
direct-=1
elif [x,y] in Lwhite:
print "white square"
Lwhite.remove([x,y])
Lred.append([x,y])
direct+=1
Move(direct)
print Lwhite
print Lred
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句