简体   繁体   English

在 python 的 connect 4 游戏中验证输入

[英]Validating input in a connect 4 game in python

I want the user to select a number 1-7 and then check if that this is true, if not then they input a number again.我希望用户输入 select 一个数字 1-7,然后检查这是否为真,如果不是,则他们再次输入一个数字。

I am able to check this but if a wrong number is chosen it will ittirate the process 3 times even if a correct value is entered.. I have tried many different solutions to no avail.我可以检查这个,但如果选择了错误的数字,即使输入了正确的值,它也会使过程重复 3 次。我尝试了许多不同的解决方案,但都无济于事。 I just want to check the value until its right and then return the correct value to the game.我只想检查该值直到它正确,然后将正确的值返回给游戏。

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()

Another approach, for a console game, is that the loop iterates, instead of three times, until a correct number is obtained, between 1 or 7 or the user indicates -1 (for example) in case he wants to end game!对于控制台游戏,另一种方法是循环迭代而不是三次,直到获得正确的数字,介于 1 或 7 之间,或者用户指示 -1(例如)以防他想要结束游戏!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM