这是我运行代码时遇到的错误:Traceback(最近一次调用最近): 文件“ C:/Users/Ian/.PyCharmCE2018.2/config/scratches/pyramid.py”,第95行,在 elif random_roll == 2和(pd [y] [x])!= 3 \ IndexError:列表索引超出范围
每次运行程序时,错误都会更改,因为它遵循不同的路径(或者应该是)。我有四个方向试图从PD中的每个节点向左,向右,向左,向右向下移动,如果在随机方向上没有节点,则将其记录下来,然后重试直到找到正确的方向为止走。从2到DL到5而不是从DL到9时,UR会出界错误。我已经花了几个小时来研究坐标,但仍无济于事。有人可以帮助我,因为我不明白为什么它会越界。
import random
pd = [ #This is the visual of the pyramid
[ 1 ], #[0][0] row and total col# ex [2][1] = 5
[ 2, 3 ], #[1][1]
[ 4, 5, 6, ], #[2][2]
[ 7, 8, 9, 10, ], #[3][3]
[ 11, 12, 13, 14, 15, ], #[4][4]
[ 16, 17, 18, 19, 20, 21, ], #[5][5]
]
dots_list = [[1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21]]
'''
dots_list[0].append('. . . .')
dots_list[6].append('*')
for i in range(len(dots_list)):
for j in range(len(dots_list[i])):
print(dots_list[i][j], end=' ')
print()
'''
x = 0 # represents left and right direction in pd -- adding goes right, subtracting goes left
y = 0 # represents up and down direction in pd -- adding goes down, subtracting goes up
lower_bound = 1 #used as lower bound in dice selection
upper_bound = 4 #used as upper bound in dice selection
move_counter = 0 #used to count the total number of moves made in game
#print("Starting position: ",pd[y][x]) # The starting position used for debugging
start_position = pd[y][x] # The starting point of the game [y][x] up/down y, left/right x
# ---- loop begin ----
print('begin loop')
print('------------------------------------------------------------------')
while any(len(m) < 2 for m in dots_list):
random_roll = random.randint(lower_bound, upper_bound) # Randomly selects a number from 1 to 4 to be used as fair die roll
if random_roll == 1:
print("Upper left Random Roll: " ,random_roll)
elif random_roll == 2:
print("Upper left Random Roll: ", random_roll)
elif random_roll == 3:
print("Upper left Random Roll: ", random_roll)
else:
print("Upper left Random Roll: ", random_roll)
#--------------------------------pd bounds checking-------------------------------------------
if random_roll == 1 and (pd[y][x]) != 2 \
and (pd[y][x]) != 4 and (pd[y][x]) != 11 and (pd[y][x]) != 16:
#--------------------------------pd bounds checking-------------------------------------------
print('upper left x: ', x, 'y:', y)
if pd[y][x] == 1 or pd[y][x] == 2 or pd[y][x] == 4 or pd[y][x] == 7 or pd[y][x] == 11 or pd[y][x] == 16:
print('Invalid Direction -- Move Count Increased')
print('------------------------------------------------------------------')
dots_list[pd[y][x]].append('.')
move_counter += 1
else:
new_pos = pd[y-1][x-1]
y-=1
x-=1
#print('x: ', x, 'y:', y)
print('upper left new pos: ' , new_pos)
print('------------------------------------------------------------------')
start_position = new_pos
# print('st pos', start_position)
dots_list[start_position].append('.')
move_counter += 1
#--------------------------------pd bounds checking-------------------------------------------
elif random_roll == 2 and (pd[y][x]) != 3 \
and (pd[y][x]) != 6 and (pd[y][x]) != 10 and (pd[y][x]) != 15 and (pd[y][x]) != 21:
# --------------------------------pd bounds checking-------------------------------------------
print('upper right x: ', x, 'y:', y)
print()
if pd[y][x] == 1:
print('Invalid Direction -- Move Count Increased')
print('------------------------------------------------------------------')
dots_list[0].append('.')
move_counter += 1
else:
new_pos = pd[y][x]
y-=1
x+=1
print('x: ', x, 'y:', y)
print('upper right new pos: ' , new_pos)
print('------------------------------------------------------------------')
start_position = new_pos
#print('st pos', start_position)
dots_list[start_position].append('.')
move_counter += 1
#--------------------------------pd bounds checking-------------------------------------------
elif random_roll == 3 and (pd[y][x]) != 16 and (pd[y][x]) != 17 \
and (pd[y][x]) != 18 and (pd[y][x]) != 19 and (pd[y][x]) != 20 and (pd[y][x]) != 21 \
and (pd[y][x]) != 6 and (pd[y][x]) != 10 and (pd[y][x]) !=15 :
# --------------------------------pd bounds checking-------------------------------------------
print('down left x: ', x, 'y:', y)
x+1
new_pos = pd[y+1][x]
x-=1
#y+=1
print('x: ', x, 'y:' , y)
print('down left new pos: ' , new_pos)
start_position = new_pos
#print('start_position: ', start_position)
print('------------------------------------------------------------------')
dots_list[start_position-1].append('.')
move_counter += 1
#--------------------------------pd bounds checking-------------------------------------------
elif random_roll == 4 and (pd[y][x]) != 16 and (pd[y][x]) != 17 \
and (pd[y][x]) != 18 and (pd[y][x]) != 19 and (pd[y][x]) != 20 and (pd[y][x]) != 21 :
# --------------------------------pd bounds checking-------------------------------------------
print('down right x: ', x, 'y:', y)
new_pos = pd[y+1][x+1]
x+=1
y+=1
print('x: ', x, 'y:', y)
print('down right new pos: ' , new_pos)
print('------------------------------------------------------------------')
start_position = new_pos
#print('st pos', start_position)
dots_list[start_position-1].append('.')
move_counter += 1
else:
#print('Invalid Direction -- Move Count Increased:: rr: ' , random_roll)
start_position = pd[y][x]
#print('st pos', start_position)
dots_list[start_position-1].append('.')
move_counter += 1
# ---- loop end ----
# ---- Results printing ----
print('Move_counter:' ,move_counter)
for i in range(len(dots_list)):
for j in range(len(dots_list[i])):
print(dots_list[i][j], end=' ')
print()
答案 0 :(得分:0)
我没有调试您的代码,但是尝试编写另一种代码。希望您能找到导致错误的原因的提示。
这是我发出的代码,请检查方法is_node(pos, height)
,我猜答案可能在那里:
import random
def build_a_pyramid_of(n):
res, tmp = [], []
for i in range(n+1):
tmp.append(i)
if len(tmp) > len(res[:-1]):
res.append(tmp)
tmp = []
return res[1:]
def nodes(pyramid):
nodes = []
for line in pyramid: nodes.extend(line)
return nodes
def get_a_move():
moves = [(1,0),(0,1),(-1,0),(0,-1)] # change the moves as you will
return random.choice(moves)
def is_node(pos, height):
x, y = pos[0], pos[1]
if y >= 0 and y <= x and x <= height: return True
else: return False
def next_pos_from(pos, height):
try_pos = (0,0)
while True:
move = get_a_move()
try_pos = (pos[0] + move[0], pos[1] + move[1])
if is_node(try_pos, height): break
return try_pos
# initialize
pyramid = build_a_pyramid_of(21)
nodes = nodes(pyramid)
heigth = len(pyramid)-1 # to just pass the heigh, not all the pyramid
# to visualize the pyramyd and nodes
for e in pyramid: print(e)
print('-'*20)
print(nodes)
print('-'*20)
# loop to transverse the pramyd
pos=(0,0)
while len(nodes) > 0:
node = pyramid[pos[0]][pos[1]]
if node in nodes: nodes.remove(node)
old_pos = pos
pos = next_pos_from(pos, heigth)
print(old_pos, "->", pos, node, nodes) # to visuzlize the proces
print(nodes) #=> should return empty list