2015-11-01 52 views
0

我正在研究模拟两位玩家之间的tic-tac-toe游戏的程序。这个节目到目前为止是我想要的,除了我要求玩家输入的部分。我想让程序检查(3 x 3)网格是否已经包含一个标记(例如'X'或'o'),并在切换转弯之前继续提示同一个播放器输入正确的输入。以下是我迄今为止:提示用户输入正确的输入 - tic tac toe游戏

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循环,但那只是不停地提示用户而不终止(也许我在那里做了错误)。帮助将不胜感激。

+0

提示:看看当你将'if'改为'while'时会发生什么。你还必须摆脱'else:'(和un indent'board [userInput] =“X”')。 –

+0

您应该尝试将这两个get_input函数压缩为一个函数,该函数需要一个参数来指定哪个播放器。 –

回答

1

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

while userInput < 0 or userInput > 8 or board[userInput] == "X" or board[userInput] == "o": 
    print("Wrong input! You cannot move there! ") 
    userInput = input("Please give a valid move.") 
board[userInput] = "X" 
+0

谢谢,这部分解决了它。现在,如果我第一次输入错误的输入,我会收到“请给出一个有效的举动”的消息,这正是我想要的。但是,如果我插入一个不同的整数(一个有效的),我得到一个形式错误“TypeError:unorderable types:str() Kamil

+0

是的,一个简单的解决方法是使用int(input(..) 。)) – Vinay