[英]Validating input in a connect 4 game in python
我希望用户输入 select 一个数字 1-7,然后检查这是否为真,如果不是,则他们再次输入一个数字。
我可以检查这个,但如果选择了错误的数字,即使输入了正确的值,它也会使过程重复 3 次。我尝试了许多不同的解决方案,但都无济于事。 我只想检查该值直到它正确,然后将正确的值返回给游戏。
board = [['⚪', '⚪', '⚪', '⚪', '⚪', '⚪', '⚪'],
['⚪', '⚪', '⚪', '⚪', '⚪', '⚪', '⚪'],
['⚪', '⚪', '⚪', '⚪', '⚪', '⚪', '⚪'],
['⚪', '⚪', '⚪', '⚪', '⚪', '⚪', '⚪'],
['⚪', '⚪', '⚪', '⚪', '⚪', '⚪', '⚪'],
['⚪', '⚪', '⚪', '⚪', '⚪', '⚪', '⚪'],
['1️⃣ ', '2️⃣ ', '3️⃣ ', '4️⃣ ', '5️⃣ ', '6️⃣ ', '7️⃣']]
ROWS = 7
COLUMNS = 7
def print_board():
'''
Prints out the game board
'''
for row in range(0, ROWS):
for col in range(0, COLUMNS):
print(board[row][col], end=' ')
print(" ")
def place_chip(col, player):
'''
Places chip in the first empty slot from the bottom in a column
'''
col = col - 1
for rows in range(ROWS-1, -1, -1):
if board[rows][col] == '⚪':
board[rows][col] = player
break
def validate_input(x):
while True:
if x < 1:
x = int(input(f'Column {x} does not exist. Please choose column 1-7: '))
return x
elif x > 7:
x = int(input(f'Column {x} does not exist. Please choose column 1-7: '))
return x
else:
break
return x
def play_game():
print_board()
x = int(input('Player 1 select a column(1-7): '))
validate_input(x)
place_chip(validate_input(x), '🔴')
print_board()
play_game()
对于控制台游戏,另一种方法是循环迭代而不是三次,直到获得正确的数字,介于 1 或 7 之间,或者用户指示 -1(例如)以防他想要结束游戏!
问题未解决?试试以下方法:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.