我正在研究模拟两位玩家之间的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函数压缩为一个函数,该函数需要一个参数来指定哪个播放器。 –