2015-11-01 106 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