为什么我的自动生成代码有时会陷入中途?

时间:2017-04-26 11:51:25

标签: 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 == 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

它有时有效,但有时会卡住,我不知道为什么

1 个答案:

答案 0 :(得分:0)

Chris_Rands,你让我意识到我所要做的就是在while循环的开头加一个cont = True