我的战舰计划中有一个超出范围的元组。我感到困惑的原因是我没有使用元组,除非我错了,我愿意纠正。元组不是可变的,这里引用的字典在启动程序时添加了项目。我是初学者所以如果我犯了一个愚蠢的错误,请不要判断!
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行 - 这个看起来很粗略,但我实际上并不知道该怎么做。请告知该怎么做:BTW这里是错误:
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}
)时,您都会收到此错误消息,但只传递关键字参数。
类似地,当您使用仅包含关键字格式规范(如KeyError
)的格式字符串时,您会获得{v}
,但只传递位置参数:
>>> '{}'.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)'
如果你很好奇为什么会出现这个错误,过度简化format
,它的工作原理如下:
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
,但显然两者必须以同样的方式工作。)
获得:
Traceback (most recent call last):
File "shiptest.py", line 51, in <module>
ships['shiprows'][vars] += random_row1(board)
IndexError: list index out of range
从var = 0之后的所有内容更改为:
vars = 0
for vars in range(0, 5):
print(vars)
ships['shiprows'][vars] = random_row1(board)
ships['shipcols'][vars] = random_col1(board)
print(ships)
我想我在字典中的列表是错误的。我应该使用.append()吗?编辑:我用.append()我是个白痴。它现在正在工作,谢谢你的帮助!