提示用户正确输入 - tic tac toe游戏

时间:2015-11-01 13:54:56

标签: python

我正在开发一个模拟两个玩家之间的井字游戏的程序。到目前为止,该程序完成了我想要的,除了我要求玩家输入的部分。我希望程序检查(3 x 3)网格是否已经包含一个标记(例如,'X'或'o'),并在切换之前继续提示相同的播放器输入正确的输入。以下是我到目前为止的情况:

board = [
        0, 1, 2,
        3, 4, 5,
        6, 7, 8
        ]

def main():
    print_instructions()
    start = str(input("Your game is about to begin. Press 'Q' if you want to quit, or 'K' to proceed: "))
    while start != "Q":
        get_input1()
        get_input2()


def display_board(board):
    print(board[0], "|" , board[1] , "|" , board[2])
    print("----------")
    print(board[3] , "|" , board[4] , "|" , board[5])
    print("----------")
    print(board[6] , "|" , board[7] , "|" , board[8])


def print_instructions():
    print("Please use the following cell numbers to make your move: ")
    display_board(board)


def get_input1():
    userInput = input("The first player marks with a 'X'. Type an integer between 0 up to 8 to indiciate where you want to move: ")
    userInput = int(userInput)
    if userInput < 0 or userInput > 8 or board[userInput] == "X" or board[userInput] == "o":
        print("Wrong input! You cannot move there! ")
    else:
        board[userInput] = "X"

    display_board(board)

def get_input2():
    userInput = input("Turn of second player. You mark with a 'o'. Where would you like to move? Type an integer between 0 and 8: ")
    userInput = int(userInput)
    if userInput < 0 or userInput > 8 or board[userInput] == "X" or board[userInput] == "o":
        print("Wrong input! You cannot move there! ")
    else:
        board[userInput] = "o"

    display_board(board)



main()

我仍然需要编写程序决定胜者是谁的部分,但我想先让def get_input函数正确。在这种情况下如何检查有效输入?我尝试使用while循环,但是这个循环只是不停地提示用户而没有终止(也许我在那里做错了)。帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

也许你忘记在while循环中输入了! 试试这个。

tab_index_array