0

标题 我目前正试图让用户使用破折号 (-) 和与棋子对应的字母来输入棋盘。但是列表没有正确保存。这是搞砸的代码。

def make_a_chessboard():
 chessboard = []

 possible_char = ["-","K","k","Q","q","R","r","N","n","B","b","P","p"]
 rows = 8
 cols = 8
 for r in range(rows):
     user_input = input("")
     while len(user_input) != 8:
         print("That is not the correct length. Please try again.")
         user_input = input("")
 for i in range(len(user_input)):
     flag1 = False
     while flag1 == False:
         if user_input[i] not in possible_char:
             print("One of the characters used is not supported. Please try again.")
             user_input = input("")
         else:
             for c in range(cols):

                 chessboard[r][c].append(user_input[c])
             flag1 = True
 return(chessboard)

这给了我 IndexError: list index out of range 错误。我究竟做错了什么?

4

1 回答 1

0

我建议对代码进行一些重组,以便您对每一行的输入进行一次完整的有效性测试,然后我们可以在特定行上构建每个位置的列表,并将其附加到棋盘列表中。以下内容完全未经测试,因此如果有语法错误,请告诉我,我会对其进行编辑。

 def is_valid_row(user_in):
    possible_char = ["-","K","k","Q","q","R","r","N","n","B","b","P","p"]
    if len(user_in) != 8:
        print("Please enter a string of 8 characters")
        return False
    for each_char in user_in:
        if each_char not in possible_char:
            print("You have entered illegal char {}".format(each_char))
            return False
    # Neither of those other two have returned false
    # so we're good to assume it's valid
    return True

 def make_a_chessboard():
     chessboard = []
     rows = 8

     # Process each row (you do this line by line, right?)
     for r in range(rows):
        user_input = input("")
        while not is_valid_row(user_input):
             user_input = input("")

        # We now have valid input (or we're stuck in while-loop-hell)
        # break the input into a list (of 8 valid chars)
        each_row = [x for x in user_input]

        # Now append it to chessboard
        chessboard.append(each_row)


    return(chessboard)
于 2017-12-01T01:25:59.163 回答