标题 我目前正在尝试让用户使用破折号( - )输入棋盘以及与棋子对应的字母。但是这份清单并没有妥善保存。这是代码搞砸了。
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索引超出范围的错误。我做错了什么?
答案 0 :(得分: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)