Write code to build a graph of all the possible tic-tac-toe games that uses the
ID: 3769254 • Letter: W
Question
Write code to build a graph of all the possible tic-tac-toe games that uses the pythons.graphs Graph and Vertex classes.
Each vertex represents a unique board, and each edge represents a legal move from a given board position to the new board.
Assume that X always moves first.
Then print the following
How many vertex represent a win for X (should be 626)
How many vertex represent a win for O (should be 316)
How many vertex represent a tie (board must be full, should be only 16)
Total number of legal boards that occur in the tic-tac-toe game (that count the number of vertices, should be
5,478 )
Just use a string like: "XO X OX " where the string is always 9 chars long and uses X, O, and spaces to represent the board. use this string as the id of the vertex. That way the id also has everything you need to represent the board.
I recommend writing a set of methods to find legal moves for O or X give a current board, and a method to test if X or O has won. And way to detect if game is tie (no more moves, and no one has won).
Example of vertex and edges within graph
" " -----> " X " edge for beginning board transition where X plays into center square.
" X " -----> "O X " edge from previous move where O now plays in upper left corner
"O X " -----> "OX X " edge from previous move where X now plays in upper middle square
Explanation / Answer
def tic_tac_toe():
board = [None] + list(range(1, 10))
WIN_COMBINATIONS = [
(1, 2, 3),
(4, 5, 6),
(7, 8, 9),
(1, 4, 7),
(2, 5, 8),
(3, 6, 9),
(1, 5, 9),
(3, 5, 7),
]
def draw():
print(board[7], board[8], board[9])
print(board[4], board[5], board[6])
print(board[1], board[2], board[3])
print()
def choose_number():
while True:
try:
a = int(input())
if a in board:
return a
else:
print(" Invalid move. Try again")
except ValueError:
print(" That's not a number. Try again")
def is_game_over():
for a, b, c in WIN_COMBINATIONS:
if board[a] == board[b] == board[c]:
print("Player {0} wins! ".format(board[a]))
print("Congratulations! ")
return True
if 9 == sum((pos == 'X' or pos == 'O') for pos in board):
print("The game ends in a tie ")
return True
for player in 'XO' * 9:
draw()
if is_game_over():
break
print("Player {0} pick your move".format(player))
board[choose_number()] = player
print()
while True:
tic_tac_toe()
if input("Play again (y/n) ") != "y":
break
thank you
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.