我正在尝试构建一个迷宫,但某些变量必须保存在 .txt 文件中。该文件中的一个部分是多个 4 位二进制数的列表。每个二进制数都与迷宫网格上的一个正方形相关联(即(0,3)也可以用0101表示)。 4 位数字中的每个字符代表用户是否可以朝该方向行驶,其中 1 表示可以,0 表示不可以。我正在尝试编写一个子例程,当用户位于该方块中时,该子例程将循环遍历列表中的每个元素,并检查每个字符是否是 1 或 0 以确定它们可以或不能去哪里。每个方向(从北到西)都有一个数值0-3,墙壁用数值4表示。
(这只是部分代码)
def position():
“none” == 4
“west” == 3
“south” == 2
“east” == 1
“north” == 0
return
def direction():
for i in binary: #binary is list name held in file
if [i][1] == ‘1’:
position = “west”
if [i][2] == ‘1
position = “south”
if [i][3] == ‘1’:
position = “east”
if [i][4] == ‘1
position = “north”
else:
position = 0
return direction
当我运行此命令时,我收到列表索引超出范围的错误:if [i][1] == ‘1’: 但我确信我的处理方式还存在其他错误。
我对编码还很陌生,并且已经坚持了好几天了,这是我能得到的最好的结果。
不清楚你想对我做什么,你的代码也对我没有帮助,但也许这会帮助你开始:
def get_directions(binary):
directions = []
if binary[0] == '1':
directions.append("west")
if binary[1] == '1':
directions.append("south")
if binary[2] == '1':
directions.append("east")
if binary[3] == '1':
directions.append("north")
return directions
numbers = ['0101','1011','0010'] # some test numbers
for binary in numbers:
directions = get_directions(binary)
print('directions:', directions)
输出:
directions: ['south', 'north']
directions: ['west', 'east', 'north']
directions: ['east']
将你的问题分成更小的部分。一次解决一部分。打印一些测试数据以检查其是否正常工作,必要时进行修复。然后才能进入下一部分。