我正在尝试为类项目创建一个简单的tic-tac-toe游戏,但我不确定如何完成剩下的代码。我真的很感激任何见解或输入,我将如何完成剩下的这一切。该代码目前在技术上有效,但它所做的只是显示一块充满none
和“游戏是平局的”。
PLAYERS = ["X", "O"]
def display_board(board):
print board[0][0:3]
print board[1][0:3]
print board[2][0:3]
def create_empty_board():
return [[None, None, None], [None, None, None], [None, None, None]]
def board_is_full(board):
for row in board:
if None not in board:
return True
def winner(board):
if board[0][0] == board[0][1] == board[0][2] != None:
return board[0][0]
elif board[1][0] == board[1][1] == board[1][2] != None:
return board[1][0]
elif board[2][0] == board[2][1] == board[2][2] != None:
return board[2][0]
elif board[0][0] == board[1][0] == board[2][0] != None:
return board[0][0]
elif board[0][1] == board[1][1] == board[2][1] != None:
return board[0][1]
elif board[0][2] == board[1][2] == board[2][2] != None:
return board[0][2]
elif board[0][0] == board[1][1] == board[2][2] != None:
return board[0][0]
else:
return None
def game_over(board):
if board_is_full(board) == True:
return True
def player_turn(board, playerid):
""" Ask the player to select a coordinates for their next move. The player needs to select a row and a column. If the coordinates the player selects are outside of the board, or are already occupied, they need to be prompted to select coordinates again, until their input is valid."""
return 1, 1 # by default, return row 1, column 1 as the player's desired location on the board; you need to implement this
def play():
""" This is the main function that implements a hot seat version of Tic Tac Toe."""
# the code below is just an example of how you could structure your play() function
# if you implement all the functions above correctly, this function will work
# however, feel free to change it if you want to organize your code differently
board = create_empty_board()
display_board(board)
current_player = 0
while not game_over(board):
board = player_turn(board, PLAYERS[current_player])
current_player = (current_player + 1) % len(PLAYERS)
display_board(board)
who_won = winner(board)
if who_won is None:
print "The game was a tie."
else:
print "The winning player is", who_won
if __name__ == "__main__":
play()
答案 0 :(得分:2)
您的第一个问题是您的board_is_full
错了。对于每一行,而不是检查您是否正在检查None not in board
。这总是如此; board
是三个列表的列表,因此None
永远不会出现在其中。你想检查每一行,而不是整个板。但只有if None not in row
不是正确的 - 只要任何行已满,就会成立,而不是所有行。所以当你找到一个非完整的行时你想要返回False
,如果你没有找到任何行,你想要返回True
。你应该能够自己做到这一点。
您的下一个问题是您尚未实施player_turn
。对于真正的hacky实现,您可以使用return input('row, col: ')
。除非你能理解为什么这样有效,否则你不应该把它作为你的作业(如果你 理解它为什么有效,你就不想使用它)。此外,它不是非常用户友好 - 它不会告诉你轮到它,或者向你展示董事会或其他什么。你将这些东西作为参数,这样你就可以使用它们。无论如何,单线程足以让你现在接下来的问题,所以你可以稍后再回来。
您的下一个问题是player_turn
会返回一对数字,而您只是将这对数字分配给board
。你不能这样做。你想要的是这样的:
row, col = player_turn(board, PLAYERS[current_player])
board[row][col] = PLAYERS[current_player]
即使有人已经赢了,游戏也会让你继续玩,直到董事会满员为止。但实际上,如果董事会已满,你想完成,或那里是胜利者。 (事实上,理想情况下,你想在胜利不可能的时候尽快完成,但这有点复杂。你可以通过将前一句翻译成while
的替代来做一件简单的事情。语句。)
这应该让你找到任何其他小错误,写一个正确的player_turn
函数,寻找简化现有代码的方法等等。