我正在尝试使用Zelle的graphics.py来模拟Langton的蚂蚁(我无法更改库,因为这是针对特定的类)而且我被卡住了!
我创建了一个正方形网格,每个网格都是一个独特的对象,这样我就可以根据蚂蚁对象“触摸”哪个方格(占据相同的坐标)来修改单个方格的颜色。对于蚂蚁的每次移动,我想要检测其中网格片共享相同坐标的填充(即“白色”,“黑色”),以便我可以改变该方块的颜色并相应地移动蚂蚁。我创建了正方形网格,并将每个正方形存储到这样的字典中:
def drawgrid():
"""draws a grid of white squares, each individual objects instead of
intersecting lines so that the position of each square can be determined and
the color of each square can be individually changed"""
square = Rectangle(Point(0,0), Point(1,1))
square.setFill("white")
coordinate_dict={}
for x in range (0, 51):
for y in range (0, 51):
newsquare = square.clone()
newsquare.move(x, y)
newsquare.draw(win)
coordinate_dict[str(x+.5) + "," + str(y+.5)] = newsquare #offset to match center coordinates
return coordinate_dict
我在我的moveant()函数中使用了coordinate_dict:
def moveant(ant):
"""
moves the ant according to rules of langton's ant
detects the coordinate of the square below the ant
changes the ant's position
and changes the color of the lower block
"""
ant.draw(win)
coordinate_dict = drawgrid()
rules = [("white", "up", "right", "black"),
("white", "down", "left", "black"),
("white", "right", "down", "black"),
("white", "left", "up", "black"),
("black", "up", "left", "white"),
("black", "down", "right", "white"),
("black", "left", "down", "white"),
("black", "right", "up", "white")]
for (color, direction, new_direction, new_color) in rules:
for key in coordinate_dict:
current_location = ant.getLocation()
xcoord = str(current_location.getX())
#print xcoord
ycoord = str(current_location.getY())
#print ycoord
current_direction = ant.getDirection()
if ((xcoord + "," + ycoord) == key) and \
(key.getConfig("fill") == color) and \
(current_direction == direction):
# print "hello"
ant._move(new_direction)
# print new_direction
key.setFill(new_color)
# print new_color
然而,我收到此错误:
Traceback (most recent call last):
File "langton.py", line 156, in <module>
main()
File "langton.py", line 133, in main
moveant(langton)
File "langton.py", line 120, in moveant
(key.getConfig("fill") == color) and \
AttributeError: 'str' object has no attribute 'getConfig'
根据我的理解,我编写此循环的方式是程序试图在键上使用.getConfig()而不是存储在键下的方形对象。但是,我不确定如何访问方形对象,以便我可以在if语句中使用其“填充”值。任何帮助表示赞赏!