Python Turtle Maze Generator: Solving the 'IndexError: list index out of range' Error
The error 'IndexError: list index out of range' in your Python Turtle maze generator code occurs because the variable 'column' is being incremented inside the nested loop, while the loop is already iterating over the range of 'column' values.
To fix this error, you should remove the line 'column += 1' from inside the nested loop. The 'column' variable will be automatically incremented by the 'for' loop itself. Here's the corrected code:
import turtle
import random
turtle.ht()
turtle.speed(0)
row = 0
column = 0
cell_list = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
cell_opening = 0
def down_opening1():
global cell_opening
turtle.fd(10)
turtle.bk(1)
turtle.penup()
turtle.rt(90)
turtle.fd(10)
turtle.pendown()
turtle.rt(90)
turtle.fd(10)
cell_opening = 0
def down_opening2():
global cell_opening
turtle.fd(10)
turtle.rt(90)
turtle.fd(11)
cell_opening = 1
def left_opening1():
global cell_opening
turtle.rt(90)
turtle.fd(10)
turtle.lt(90)
turtle.fd(11)
cell_opening = 0
def left_opening2():
global cell_opening
turtle.rt(90)
turtle.fd(10)
turtle.bk(1)
turtle.penup()
turtle.lt(90)
turtle.fd(10)
turtle.pendown()
turtle.lt(90)
turtle.fd(10)
cell_opening = 1
def ceiling():
global cell_opening
turtle.penup()
turtle.fd(10)
turtle.rt(90)
turtle.pendown()
turtle.fd(10)
cell_opening = 1
def cell():
global cell_list, row, cell_opening,column
cell_random = random.randint(0, 1)
turtle.setheading(0)
if row == 0:
if cell_opening == 0:
if cell_random == 0:
down_opening1()
cell_list[column] = 1
elif cell_random == 1:
down_opening2()
cell_list[column] = 0
else:
if cell_random == 0:
left_opening1()
cell_list[column] = 1
elif cell_random == 1:
left_opening2()
cell_list[column] = 0
else:
if cell_list[column] == 0:
if cell_opening == 0:
if cell_random == 0:
ceiling()
cell_list[column] = 0
elif cell_random == 1:
cell_list[column] = 1
elif cell_opening == 1:
if cell_random == 0:
left_opening1()
cell_list[column] = 1
elif cell_random == 1:
left_opening2()
cell_list[column] = 0
elif cell_list[column] == 1:
if cell_opening == 0:
if cell_random == 0:
down_opening1()
cell_list[column] = 1
elif cell_random == 1:
ceiling()
cell_list[column] = 0
if cell_opening == 1:
if cell_random == 0:
down_opening2()
cell_list[column] = 0
elif cell_random == 1:
cell_list[column] = 1
for i in range(10):
for column in range(len(cell_list)):
turtle.penup()
turtle.goto(10 * column, 10 * row)
turtle.pendown()
# column += 1 # Remove this line
print(column)
print(cell_list)
cell()
row += 1
cell_opening = 0
column = 0
turtle.mainloop()
By removing 'column += 1', the 'for' loop will now correctly iterate over the 'column' values within the range of your 'cell_list', avoiding the 'IndexError' and ensuring your maze generation works as intended.
原文地址: https://www.cveoy.top/t/topic/qFnk 著作权归作者所有。请勿转载和采集!