Python为什么每次迭代都会超出范围?

时间:2018-12-20 03:15:33

标签: python indexoutofboundsexception

每次我运行程序时,它似乎都在不同的地方,我不确定为什么。我非常接近完成这部分工作,这使我发疯。有人可以在他们的机器上运行它,让我知道他们的想法吗?我试图用不同的if语句来控制范围,但是过一会儿它变成一堆废话。

import os.path
import random
import math
import sys
import os
import re



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]

]

#The list used to store visited nodes
dots_list = [[1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21]]



#Do not remove this sentence

TOTAL_NUMBERS = 21 # the total numbers in the pyramid
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 set at 1, the top of pyramid
dots_list[start_position - 1].append('.') # Adds dot to number one to indicate start of game
move_counter  += 1 #this counts as a move

# ----  loop begin ----
print('begin loop')
print('------------------------------------------------------------------')
while any(len(m) < 2 for m in dots_list):

    random_roll = random.randint(upper_bound-2, upper_bound) # Randomly selects a number from 1 to 4 to be used as fair die roll
   # debugging output removing will cause errors
    if random_roll == 1:
        print("Upper left Roll: " ,random_roll)
        print('X is:', x)
        print('Y is:', y)
        print()

        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[start_position - 1].append('.')
            for i in range(len(dots_list)):
                for j in range(len(dots_list[i])):
                    print(dots_list[i][j], end=' ')
            print()
            move_counter += 1
        else:
            if y > 0:
                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 = pd[y - 1][x - 1]
                # print('st pos', start_position)


            dots_list[start_position - 1].append('.')
            for i in range(len(dots_list)):
                for j in range(len(dots_list[i])):
                    print(dots_list[i][j], end=' ')
                print()
            move_counter += 1
            print('Rolling again')



    elif random_roll == 2:
        print("Upper right Roll: ", random_roll)
        print('X is:', x)
        print('Y is:', y)
        print('moving the next element before changes')
        print()

        if y > 5:
            y-=1
        if x > 5:
            x-=1
        if y > 3:
            y-=1

        if y > x:
            new_pos = pd[y][x]
            start_position = new_pos
            print('new start_pos', start_position)
            dots_list[start_position - 1].append('.')
            for i in range(len(dots_list)):
                for j in range(len(dots_list[i])):
                    print(dots_list[i][j], end=' ')
                print()
        print('X is:', x)
        print('Y is:', y)
        print("after changes")

        start_position = new_pos
        print('new start_pos', start_position)
        dots_list[start_position - 1].append('.')
        for i in range(len(dots_list)):
            for j in range(len(dots_list[i])):
                print(dots_list[i][j], end=' ')
            print()

        print()

        if y <= 5 and y > -1 and x > -1 and x <= 5 and x < y:
            if pd[y][x] == 3 or pd[y][x] == 6 or pd[y][x] == 10 or pd[y][x] == 15 or pd[y][x] == 21:
                new_pos = pd[y][x]
                start_position = new_pos
                # start_position = pd[y][x]
                print(' new start_pos', start_position)
                dots_list[(pd[y][x]) - 1].append('.')
                for i in range(len(dots_list)):
                    for j in range(len(dots_list[i])):
                        print(dots_list[i][j], end=' ')
                    print()
                move_counter += 1
                print('Rolling again')
                print()

        else:
            if y > -1 and y < 5:

                print('X is:', x)
                print('Y is:', y)
                print()
                print('moving the next element ')

                y -= 1

                print('X is:', x)
                print('Y is:', y)
                print()
                new_pos = pd[y][x]
                #print('upper right new pos: ', new_pos)
               # print('------------------------------------------------------------------')
                start_position = new_pos
                print(' new start_pos', start_position)
                dots_list[start_position - 1].append('.')
                for i in range(len(dots_list)):
                    for j in range(len(dots_list[i])):
                        print(dots_list[i][j], end=' ')
                    print()
                move_counter += 1


        print('Rolling again')
        print()


    elif random_roll == 3:
        print("Lower left Roll: ", random_roll)
        print('X is:', x)
        print('Y is:', y)

        print('moving the next element ')
        print()

        if y <= 5 and y > -1 and x > -1 and x <= 5:

            if y != 5:
                y += 1
            print('X is:', x)
            print('Y is:', y)
            new_pos = pd[y][x]
            start_position = new_pos
            print('new start_pos', start_position)
            dots_list[start_position - 1].append('.')
            for i in range(len(dots_list)):
                for j in range(len(dots_list[i])):
                    print(dots_list[i][j], end=' ')
                print()
            move_counter += 1
        elif y > 5:
            print('start pos' ,start_position)
            dots_list[start_position - 1].append('.')
            for i in range(len(dots_list)):
                for j in range(len(dots_list[i])):
                    print(dots_list[i][j], end=' ')
                print()
            move_counter += 1
            y-=1
        elif x > 5:
            print('start pos', start_position)
            dots_list[start_position - 1].append('.')
            for i in range(len(dots_list)):
                for j in range(len(dots_list[i])):
                    print(dots_list[i][j], end=' ')
                print()
            move_counter += 1
            x-=1

        else:
            x-=1
            y-=1



        # if pd[y][x] == 17 :
        #   break;

    else:
        print("Lower right Roll: ", random_roll)
        # print('Invalid Direction --  Move Count Increased:: rr: ' , random_roll)
        print('X is:', x)
        print('Y is:', y)

        print('moving the next element ')
        print()
        x += 1
        y += 1

        print('X is:', x)
        print('Y is:', y)
        print()

        if y <= 5 and y > -1 and x > -1 and x <= 5:
            new_pos = pd[y][x]
            start_position = new_pos
            # start_position = pd[y][x]
            print(' new start_pos', start_position)
            dots_list[start_position - 1].append('.')
            for i in range(len(dots_list)):
                for j in range(len(dots_list[i])):
                    print(dots_list[i][j], end=' ')
                print()
            move_counter += 1
            print('Rolling again')
            print()
        elif y > 5:
            print('start pos' ,start_position)
            dots_list[start_position - 1].append('.')
            for i in range(len(dots_list)):
                for j in range(len(dots_list[i])):
                    print(dots_list[i][j], end=' ')
                print()
            move_counter += 1
            y-=1
            print('Rolling again')
        elif x > 5:
            print('start pos', start_position)
            dots_list[start_position - 1].append('.')
            for i in range(len(dots_list)):
                for j in range(len(dots_list[i])):
                    print(dots_list[i][j], end=' ')
                print()
            move_counter += 1
            x-=1
            print('Rolling again')
            print()
        else:
            x-=1
            y-=1
            print('Rolling again')
            print()








print('outside loop')

# ---- loop end ----

# ---- Results printing ----

print('Move_counter:' ,move_counter)
avg_dots = move_counter/TOTAL_NUMBERS
print('Average number of dots', avg_dots)
for i in range(len(dots_list)):
    for j in range(len(dots_list[i])):
        print(dots_list[i][j], end=' ')
    print()

错误消息:

Traceback (most recent call last):
  File "C:/Users/.PyCharmCE2018.2/config/scratches/pyramid.py", line 199, in <module>
    new_pos = pd[y][x]
IndexError: list index out of range

Process finished with exit code 1

1 个答案:

答案 0 :(得分:0)

我不确定这是否是您的错误的根源,但我确实注意到了这一点

random_roll = random.randint(upper_bound-2, upper_bound)  # Randomly selects a number from 1 to 4 to be used as fair die roll

使用upper_bound = 4,它将是random.randint(2, 4),而不是(1, 4),就像您想要的那样。

但是,我也同意DYZ的评论,即您应该将程序分成多个函数,而不是将其全部包含在多个if语句的单个循环中。