我的战舰程序中有一个元组超出了范围。我感到困惑的原因是我没有使用元组,除非我错了并且我愿意被纠正。元组是不可变的,并且它所指的字典在启动程序时已添加了项目。 我是初学者,所以如果我犯了一个愚蠢的错误,请不要评判!
from random import randint
#empty list to generate the board.
board = []
messages = {
"win" : "Nooo you won!",
"lose" : "Not my ship haha",
"out" : "Oops, that's not even in the ocean.",
"repeat" : "You guessed that one already"
}
ships = {
'shiprows' : [0]
'shipcols' : [0]
}
#generate board and append to board[] As of now it is a 10*10 grid.
for x in range(0, 10):
board.append(["O"] * 10)
#prints the board every turn.
def print_board(board):
for row in board:
print(" ".join(row))
print_board(board)
#computer chooses where to put battleships' rows
def random_row1(board):
return randint(0, len(board) - 1)
def random_col1(board):
return randint(0, len(board) - 1)
#calling above two functions and storing their values for 5 ships.
#creating variables for 5 ships.
vars = 0
for vars in range(0, 5):
print(vars)
if len(ships.keys()) >= 4:
while ships["shiprow{}".format(vars - 2)] == ships["shiprow{}".format(vars - 1)] and ships["shipcol{}".format(vars - 2)] == ships["shipcol{}".format(vars - 1)]:
ships["shiprow{}".format(vars)] = random_row1(board)
ships["shipcol{}".format(vars)] = random_col1(board)
ships["shiprow{}".format(vars)] = random_row1(board)
ships["shipcol{}".format(vars)] = random_col1(board)
else:
ships["shiprow{}".format(vars)] = random_row1(board)
ships["shipcol{}".format(vars)] = random_col1(board)
#program itself
turn = 0
#enforces four turns before game over. Will possibly extend to unlimited with multiple ships.
print(ships)
for turn in range(20):
turn = turn + 1
print ("Turn {}".format(turn))
print ("Ships Left: {}".format(int(len(ships.keys()) / 2)))
guess_row = int(input("Guess Row: "))
guess_col = int(input("Guess Col: "))
#checking stuff.
i = 0
if guess_row == ships["shiprow{}".format(i = range(0, 10))] and guess_col == ships["shipcol{}".format(i)]:
print (messages["win"])
board[guess_col][guess_row] = u"#"
print_board(board)
elif board[guess_col][guess_row] == "X":
print ("You guessed that one already.")
elif guess_row not in range(len(board)) and guess_col not in range(len(board[0])):
print(messages["out"])
else:
print(messages["lose"])
board[guess_col][guess_row] = "X"
print_board(board)
if turn >= 20:
print ("Game Over")
board[ships["ship_col{}".format(range(0, 10))]][ships["ship_row{}".format(range(0, 10))]] = u"#"
print_board(board)
break
可疑行似乎是第 62 行 - 这看起来很粗略,但我实际上不知道该怎么做。请告知该怎么做: 顺便说一句,这是错误:
Traceback (most recent call last):
File "battleship3.py", line 62, in <module>
if guess_row == ships["shiprow{}".format(i = range(0, 10))] and guess_col == ships["shipcol{}".format(i)]:
IndexError: tuple index out of range
谢谢。
最佳答案
只要您使用具有位置格式规范的格式字符串(例如 {}
或 {1}
),但仅传递关键字参数,您就会收到此错误消息。
类似地,当您使用仅包含关键字格式规范的格式字符串(如 {v}
)但仅传递位置参数时,您会收到 KeyError
:
>>> '{}'.format(i=1)
IndexError: tuple index out of range
>>> '{i}'.format(1)
KeyError: 'i'
修复只是为了使您的规范符合您的论点。无论您喜欢哪种方式都可以,只需保持一致即可:
>>> '{i}'.format(i=1)
1
>>> '{}'.format(1)
1
<小时/>
话虽如此,我不确定这是什么意思:
"shiprow{}".format(i = range(0, 10))
您可以通过任何一种方式修复它,但这真的是您想要的字符串吗?
>>> "shiprow{i}".format(i = range(0, 10))
'shiprowrange(0, 10)'
>>> "shiprow{}".format(range(0, 10))
'shiprowrange(0, 10)'
<小时/>
如果您好奇为什么会出现此错误,稍微简化一下格式
,它的工作原理如下:
def format(self, *args, **kwargs):
result = ''
index = 0
bits = self.parse_format_stuff()
for bit in bits:
if bit is a regular string:
result += bit
elif bit is empty braces:
result = args[index]
index += 1
elif bit is a number in braces:
result += args[number]
elif bit is a valid identifier string in braces:
result += kwargs[identifier]
else:
raise a ValueError
return result
因此,当它看到 {}
格式规范时,它会查找 args[0]
。由于您没有传递任何位置参数,因此 args
是空元组 ()
,因此 args[0]
是一个 IndexError
.
可以说,如果 format
处理这些错误并将其转化为更好的东西,可能会更好,但有时能够以编程方式处理 KeyError
会很有用。 (IndexError
并不常见,但显然两者必须以相同的方式工作。)
关于Python 3 - 元组超出范围错误。但我用的是字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52227707/