I'm creating a procedural map generator for a text-based game. Running the code repeatedly with the following shell command (cmd.exe):
python map.py
I just run this, wait for the output to show (code not shown here) then press:
↑Enter
to run the previous command quickly. Rinse and repeat.
For the first couple of times, it works. But then, running it another time, it will hang. Pressing Ctrl-C to send a KeyboardInterrupt, I always get the below traceback, after which the code will work again, but the cycle repeats again later:
File "map.py", line 44, in <module>
map1 = create_map(8)
File "map.py", line 15, in create_map
room2 = random.choice(rooms)
File "C:\Users\...\Python36-32\lib\random.py", line 255, in choice
i = self._randbelow(len(seq))
File "C:\Users\...\Python36-32\lib\random.py", line 232, in _randbelow
r = getrandbits(k) # 0 <= r < 2**k
It seems that there is something wrong with the random module. Here is the code the traceback refers to:
7 def create_map(num_rooms = 5):
8 rooms = [Room(create_rand_string()) for i in range(num_rooms)]
9
10 for i in range(num_rooms):
11 room1 = random.choice(rooms)
12 room2 = random.choice(rooms)
13
14 while room2 in room1.adjacent_rooms or room1 == room2:
15 room2 = random.choice(rooms)
16
17 link_rooms(room1, room2)
18
19 return rooms if all(room.adjacent_rooms != [] for room in rooms) else create_map(num_rooms)
The link_rooms() function just adds each Room to the other's adjacent_rooms list. The create_rand_string() function also works perfectly fine, despite using random.choice() as well.
The way the above code works is that I generate n rooms. I then link two random rooms together n times as long as they aren't already linked or the two rooms aren't the same room. Then, at the end, I make sure to only return the rooms list if all the rooms have at least one connection. Otherwise, recurse and return the result of another call to the function.
Is Python running something in the background, that causes it to crash if I run this script repeatedly too many times?
Aucun commentaire:
Enregistrer un commentaire