我正在研究模擬兩位玩家之間的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
循環,但那只是不停地提示用戶而不終止(也許我在那裏做了錯誤)。幫助將不勝感激。
提示:看看當你將'if'改爲'while'時會發生什麼。你還必須擺脫'else:'(和un indent'board [userInput] =「X」')。 –
您應該嘗試將這兩個get_input函數壓縮爲一個函數,該函數需要一個參數來指定哪個播放器。 –