每当我运行这个文件时,我都会得到一个indexer:string索引超出范围,我不确定这里哪里出错了

2024-09-28 17:03:19 发布

您现在位置:Python中文网/ 问答频道 /正文

首先,非常抱歉,如果这不是格式化所有内容的正确方法,但我正在尝试为两名玩家制作一个connect 4游戏,我不明白为什么会出现此错误

#Creates the board
def Boardmaker(field):
    for row in range(12): #0,1,2,3,4,5,6,7,8,9,10,11
        NewRow = int(row/2)
        if row%2 == 0:
            for column in range(13):
                NewColumn = int(column/2)
                if column%2 == 0:
                    if column != 12:
                        print(field[NewColumn][NewRow],end="")
                    else:
                        print(field[NewColumn][NewRow])
                else:
                    print("|",end="")
        else:
            print("-------------")

#Play space
player = 1       #0    1    2    3    4    5    6
Currentfield = [[" ", " ", " ", " ", " ", " ", " "], 
                [" ", " ", " ", " ", " ", " ", " "], 
                [" ", " ", " ", " ", " ", " ", " "], 
                [" ", " ", " ", " ", " ", " ", " "], 
                [" ", " ", " ", " ", " ", " ", " "], 
                [" ", " ", " ", " ", " ", " ", " "], 
                [" ", " ", " ", " ", " ", " ", " "]]

#Player Controller and turn allocator
Boardmaker(Currentfield)
while(True):
    MoveColumn = int(input("Please enter a column"))
    if player == 1:
        #if Currentfield[MoveColumn] == " ":
            Currentfield[MoveColumn] = "X"
            player = 2
    else:
        #if Currentfield[MoveColumn] == " ":
            Currentfield[MoveColumn] = "O"
            player = 1
    Boardmaker(Currentfield)

Tags: infieldforifcolumnelseintrow
2条回答

在connect 4游戏中,您必须设置棋盘的columnrow,这样您的代码将是:

player = 1
Currentfield = [[" ", " ", " ", " ", " ", " ", " "], [" ", " ", " ", " ", " ", " ", " "], [" ", " ", " ", " ", " ", " ", " "], [" ", " ", " ", " ", " ", " ", " "], [" ", " ", " ", " ", " ", " ", " "], [" ", " ", " ", " ", " ", " ", " "], [" ", " ", " ", " ", " ", " ", " "]]
while(True): 
    MoveColumn = int(input("Please enter a column:"))    
    MoveRow = int(input("Please enter a row:"))
    if player == 1:
        #if Currentfield[MoveColumn] == " ":
        Currentfield[MoveColumn][MoveRow] = "X"
        player = 2
    else:
        #if Currentfield[MoveColumn] == " ":
        Currentfield[MoveColumn][MoveRow] = "O"
        player = 1            
    Boardmaker(Currentfield)

另外,我注意到您没有正确地使用列表的索引,首先是row,然后是column,上面的代码应该可以在您的程序中使用,但是,如果您想更改它,您只需将field[NewColumn][NewRow]更改为field[NewRow][NewColumn],将Currentfield[MoveColumn][MoveRow]更改为Currentfield[MoveRow][MoveColumn]

在代码中

if player == 1:
    #if Currentfield[MoveColumn] == " ":
        Currentfield[MoveColumn] = "X"
        player = 2

您正在用字符串"X"替换Currentfield的一个列表,因为您没有指定行索引。然后,在打印游戏板时,您迭代该字符串,由于该字符串的长度为1,因此您会得到索引错误

相关问题 更多 >