正在用 Python 开发战舰游戏。我的功能是检查用户的“猜测”输入,从而导致无限的验证循环。我想要猜测 10x10 网格上“a10”的格式。我为帮助验证而构建的验证函数如下:
def validate_guess(self,guess):
while True:
if (len(guess)) in range(2, 4):
if guess[0] not in 'abcdefghij' or guess[1:] not in '1,2,3,4,5,6,7,8,9,10':
print("Sorry the Grid is a 10x10 square you must enter a valid position. Try again...")
continue
else:
return guess
else:
if len(guess) < 2 or len(guess) > 3:
print("Oops! That's too not the right amount of characters. Please try again...")
continue
如果用户猜测了一个不正确的值——它确实发现了它——但错误将返回一个带有打印错误语句的永无止境的循环。
这是我的游戏中使用验证函数的部分:
while True:
print("\n")
# get guess from player one in coordinate form (example: a10)
guess = input("{}'s turn to guess: ".format(player1.player))
# strip characters from the guess input
guess = guess.strip()
# validate the guess
guess = self.validate_guess(guess)
# append the guess to a list for player 1
player1.guesses.append(guess)
# break down the coordinates into x and y variables
x, y = ship1.split_guess(guess)
# increment guesses
guesses += 1
# loop to assess whether, hit, miss or a won game
if any(guess in ship for ship in grid2.play_two_board):
print("HIT")
grid2.print_guess_board(x, y, "h")
for ship in grid2.play_two_board:
try:
ship.remove(guess)
print(len(Board.play_two_board))
self.check_if_sunk(ship)
win = self.play_one_win_check(player1.player)
if win == 1:
print ("GAVE OVER!")
break
except ValueError:
pass
else:
print("Miss!")
grid2.print_guess_board(x, y, "m")
不确定是否是因为我有两个 While 语句?只是真的被困在这里,希望得到任何指导。谢谢。
********************************8 编辑 --changed 函数以包含猜测,但实际上没有从输入语句中传递该值,但仍然遇到相同的问题。
def validate_guess(self):
guess = input("Please enter a location:")
while True:
if len(guess) in range(2, 4):
if guess[0] not in 'abcdefghij' or guess[1:] not in '1,2,3,4,5,6,7,8,9,10':
print("Sorry the Grid is a 10x10 square you must enter a valid position. Try again...")
continue
else:
return guess
else:
if len(guess) < 2 or len(guess) > 3:
print("Oops! That's too not the right amount of characters. Please try again...")
continue
并像这样调用它:
while True:
print("\n")
# get guess from player one in coordinate form (example: a10)
# guess = input("{}'s turn to guess: ".format(player1.player))
# strip characters from the guess input
# guess = guess.strip()
# validate the guess
guess = self.validate_guess()
最佳答案
在validate_guess中,当用户输入错误值时,您必须在再次检查之前获取新的输入。请参阅here .
要么从函数返回错误代码(True/False?),要么让函数循环直到输入有效。只需在函数的 while 循环底部添加一个用于新输入的命令即可。
关于python - Python 中永无休止的验证检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42794802/