Tic_Tac_Toe_txt
Tic_Tac_Toe_txt
### SKELETON FOR THE TIC TAC TOE GAME (defining a class and its methods)
### IT PRINTS THE BOARD
### PLAYER 1: USER CHOOSES
### PLAYER 2: COMPUTER uses AI to never lose. Minimax algorithm for the optimal
move.
while True:
user_wants_kick_off = input("Please inform 'Y' if you wish to start the
game or 'N' if you wish the computer/AI starts:")
if user_wants_kick_off.lower() == 'y':
self.current_player = " X "
break
elif user_wants_kick_off.lower() == 'n':
self.current_player = " O "
break
else:
print("Invalid input. Please enter 'Y' or 'N'.")
def display_board(self):
"""
Function to display the current state of the board
"""
print(" Tic Tac Toe ")
print(self.board[0] + "|" + self.board[1] + "|" + self.board[2])
print(self.board[3] + "|" + self.board[4] + "|" + self.board[5])
print(self.board[6] + "|" + self.board[7] + "|" + self.board[8])
print(" ")
def play_game(self):
"""
Function to start the game
"""
self.display_board()
while True:
# Get the current player's position choice
if self.current_player == " X ":
player_pos = self.get_player_pos()
else:
player_pos = self.get_computer_pos()
# Update the board with the current player's position
self.board[player_pos] = self.current_player
self.display_board()
def get_player_pos(self):
"""
Function to get the current choice of player1
"""
while True:
try:
# this line, we read the user's choice, but since the board index
is between 0 and 8, and the user provide any number between 1 - 9, we subtract -1
for the current/real index in the board
player_pos = int(input("Player 1, choose a free position in the
board (1-9):")) - 1
# check if the current choice is free
if player_pos in range(9):
if self.board[player_pos] == " - ":
return player_pos
else:
print("That position is already taken. Please choose
another position.")
else:
print("Please choose a position between 1 and 9.")
except ValueError:
print("Please enter a valid number.")
# Function to check who the current player is, and then switch the turn
def switch_player(self, current_player):
"""
Function to check who the current player is, and then switch the turn
"""
if current_player == " X ":
return " O "
else:
return " X "
# Iterate through all possible moves and determine the best score and best
move
for i, pos in enumerate(board):
if pos == " - ":
board[i] = player
score, _ = self.minimax(board, opponent)
board[i] = " - "