Tic Tac Toe Program
Tic Tac Toe Program
Step 1
The following line initializes a list called board with 9 spaces, representing the 9 spaces on the Tic Tac
Toe board.
board = [" " for x in range(9)]
Step 2
The following function print_board() will print the Tic Tac Toe board. It creates 3 strings, row1, row2,
and row3, to represent each row of the board. The spaces in the board are filled with the values from
the board list. The function then prints each row with separators to create the appearance of a 3×3
grid.
def print_board():
print()
print(row1)
print(row2)
print(row3)
print()
Step 3
The following function then prints each row with separators to create the appearance of a 3×3 grid.
The player_move() function allows a player to make a move by marking a space on the board with
their icon (X or O). It takes the player’s icon as an argument and asks the player to enter their move
(1-9) in the terminal. If the space the player chooses is blank, the function will place the player’s icon
in that space. Otherwise, it will inform the player that the space is full.
def player_move(icon):
if icon == "X":
number = 1
number = 2
board[choice - 1] = icon
else:
print()
This function is_victory() checks if a player has won the game. It takes the player’s icon as an
argument and checks if there are three of that icon in a row on the board. It returns True if a player
has won, otherwise it returns False.
def is_victory(icon):
return True
else:
return False
Step 5
This function is_draw() checks if the game is a draw by checking if all spaces on the board are filled.
When all spaces are filled and no player has won, it returns True, otherwise it returns False.
def is_draw():
return True
else:
return False
Step 6
The while loop continues the game until a player has won or the game is a draw. Within the loop, the
board is printed. Then, the player_move() function calls and allows the first player to make a move.
The board prints again to show the updated state. Then, calling the is_victory() function will check if
the first player has won. When they win, the game ends and a victory message shows If not, the
is_draw() function is called to check if the game is a draw.
If the game is a draw, a message is displayed and the game ends. If neither the first player nor the
game has won or ended in a draw, the second player makes a move and the process repeats.
while True:
print_board()
player_move("X")
print_board()
if is_victory("X"):
break
elif is_draw():
print("It's a draw!")
break
player_move("O")
if is_victory("O"):
print_board()
break
elif is_draw():
print("It's a draw!")
break