我试图为一个类项目创建一个简单的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()
你的第一个问题是你的
board_is_full
是错误的。对于每一行,不是检查而是检查None not in board
。这总是正确的;board
是三个列表的列表,因此None
永远不会在其中。你要检查每一行,而不是整个董事会。但是只要if None not in row
是不对的,只要任何行都满了,而不是所有行都满了,就不会是这样。因此,当您找到一个非整行时,您希望返回False
;如果您到达结尾时没有找到任何行,则返回True
。你应该自己能做到。下一个问题是您还没有实现
player_turn
。对于真正的黑客实现,您只需使用return input('row, col: ')
。除非你能理解它为什么起作用,否则你不应该把它作为你的家庭作业(如果你真的理解它为什么起作用,你就不会想用它了)。而且,它不是很友好的用户-它不告诉你轮到谁了,或给你看板,或任何东西。你把这些东西作为参数,这样你就可以使用它们。不管怎么说,这一行已经足够好了,现在可以让你进入下一个问题,所以你可以稍后再来。下一个问题是
player_turn
返回一对数字,而您只是将这对数字赋给board
。你不能那样做。你想要的是这样的东西:即使有人已经赢了,游戏也会让你一直玩到棋盘满为止。但事实上,如果棋盘满了,你会想结束比赛,或有赢家。(事实上,理想情况下,你想在不可能获胜的情况下尽快结束比赛,但这有点复杂。只需将前面的句子转换为
while
语句的替换语句,就可以完成简单的操作这将使您能够找到任何其他小错误,编写适当的
player_turn
函数,寻找简化现有代码的方法,等等相关问题 更多 >
编程相关推荐