【发布时间】:2013-11-19 07:15:24
【问题描述】:
我正在尝试为班级项目创建一个简单的井字游戏,但我不确定如何完成其余代码。对于我如何完成剩下的工作,我真的很感激任何见解或意见。该代码目前在技术上可以工作,但它所做的只是显示一个充满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()
【问题讨论】:
-
附带说明,当每行有 3 个成员时,
board[0][0:3]与board[0]相同。 -
请不要编辑您的代码来删除您最初询问的所有问题。这使得问题和答案对任何发现它的人都毫无用处。我已经回滚了。
-
同时,如果您有新问题,请接受答案,或者编写并接受您自己的答案,然后为新问题创建一个新问题(在两者之间粘贴链接,以便人们知道他们是连接的)。不要一直将此问题更改为原始问题的后续问题。
-
附带说明,在您尝试发布的新代码中,
if " " not in board[0] and board[1] and board[2]:并不代表您的想法或任何有用的信息。特别是,它并不意味着if (" " not in board[0]) and (" " not in board[1]) and (" " not in board[2]):。你要么必须明确地写出来,要么使用any或all函数和理解,或者使用循环语句。
标签: python python-2.7 tic-tac-toe