Python 为什么我的自动生成代码有时会中途卡住?
代码如下Python 为什么我的自动生成代码有时会中途卡住?,python,python-3.x,Python,Python 3.x,代码如下 import random file_name = 'room_gen' room_no = 0 direction = 0 cont = True method = "a" while room_no != 6: last_dir = direction direction = random.randrange(1,5) print(direction) layout = random.randrange(2,6) if room_no ==
import random
file_name = 'room_gen'
room_no = 0
direction = 0
cont = True
method = "a"
while room_no != 6:
last_dir = direction
direction = random.randrange(1,5)
print(direction)
layout = random.randrange(2,6)
if room_no == 0:
direction = 'b'
layout = 0
method = "w"
elif room_no == 5:
layout = 1
else:
if direction == 1:
direction = 'n'
elif direction == 2:
direction = 'e'
elif direction == 3:
direction = 's'
elif direction == 4:
direction = 'w'
if direction == 'n' and last_dir == 's':
cont = False
elif direction == 's' and last_dir == 'n':
cont = False
elif direction == 'e' and last_dir == 'w':
cont = False
elif direction == 'w' and last_dir == 'e':
cont = False
if cont == True:
direction = str(direction)
layout = str(layout)
room_no = str(room_no)
file = open((file_name),(method))
write = (direction + layout + room_no + "\n")
file.write(write)
room_no = int(room_no)
file.close()
room_no = room_no + 1
method = "a"
file = open((file_name),"a")
write = ("x")
file.write(write)
file.close
这意味着创建一个类似这样的文件,并在再次运行时删除然后替换文件中的旧文本:
b00
n41
e22
s33
s44
w15
x
它有时会工作,但有时会卡住,我不知道为什么克里斯•兰兹,你让我意识到我所要做的就是在while循环的开头添加一个
cont=True
。当你将cont
更改为False
时,room\u no
从不递增,因此您会陷入循环,而循环将其作为答案,因为它包含答案