Tic Tac Toe
Tic Tac Toe
4. play_game Function
This is the heart of the game.
def play_game(vs_ai=False, scores={"X": 0, "O": 0, "Ties": 0}):
board = [[" " for _ in range(3)] for _ in range(3)]
Creates a 3x3 empty board:
[
[" ", " ", " "],
[" ", " ", " "],
[" ", " ", " "]
]
5. Game Turns
while True:
if vs_ai and current_player == "O":
row, col = ai_move(board)
else:
row = int(input(...)) - 1
col = int(input(...)) - 1
If it's AI’s turn, it uses the ai_move function to pick a random empty cell.
If it’s a player’s turn, it takes manual input.
6. Making a Move
if board[row][col] == " ":
board[row][col] = current_player
Puts 'X' or 'O' in the chosen cell
Prints the updated board after each move
9. Game Replay
again = input(" Play again? (y/n): ").lower()
if again != 'y':
break
Lets the player decide whether to replay or exit