The TicTacToe
class represents a standard Tic Tac Toe game. The game consists of a 3x3 board where
two players, typically represented as "X" and "O", take turns marking the spaces in a grid. The player who
succeeds in placing three of their marks in a horizontal, vertical, or diagonal row wins the game.
To win in Tic Tac Toe, a player must have three of their symbols (either X
or O
) consecutively in a row. This can be achieved in the following ways:
Students are required to implement the following methods:
do_move
: Make a move on the boardis_valid_move
: Check if a move is validcheck_game_over
: Check if the game is over
Once these methods are implemented correctly, the play_game
function will allow you to play a
complete game of Tic Tac Toe in the console.
The list comprehension used to initialize the board is a concise way to create a 3x3 grid with all spaces empty. The outer loop iterates through the rows, and the inner loop iterates through the columns.
[[self.EMPTY for _ in range(3)] for _ in range(3)]
This double for-loop list comprehension creates a list of three lists, where each inner list contains three EMPTY spaces, effectively creating a 3x3 grid.
This can be equivalently expressed using two nested for loops:
board = []
for _ in range(3):
row = []
for _ in range(3):
row.append(self.EMPTY)
board.append(row)
do_move
in Tic Tac ToeThe do_move
function is responsible for handling the player's move. Here's a breakdown of how to implement it:
is_valid_move
. Use this method in do_move
.
In this method:
X
or O
).self.current_player
symbol (X
or O
) to the chosen cell.True
if we successfully updated the game board and False
otherwise.
Once the three methods are implemented, you can run the play_game()
function to start the game.
Players will be prompted to input their moves in the format of row and column separated by a space. The game
will continue until a player wins or all cells are filled, resulting in a tie.
Have fun implementing and playing Tic Tac Toe! This game is a great example of a program you can create for your final project if you decide to use Python!