Skip to content

Instantly share code, notes, and snippets.

@Terieyenike
Last active September 11, 2024 10:11
Show Gist options
  • Select an option

  • Save Terieyenike/8c274780954af99835de81f78d11d39f to your computer and use it in GitHub Desktop.

Select an option

Save Terieyenike/8c274780954af99835de81f78d11d39f to your computer and use it in GitHub Desktop.
Tic Tac Toe with AI opponent
import random
# Board setup and functions
def print_board(board):
print(f'{board[0]} | {board[1]} | {board[2]}')
print('---------')
print(f'{board[3]} | {board[4]} | {board[5]}')
print('---------')
print(f'{board[6]} | {board[7]} | {board[8]}')
def check_win(board, player):
win_conditions = [(0, 1, 2), (3, 4, 5), (6, 7, 8),
(0, 3, 6), (1, 4, 7), (2, 5, 8),
(0, 4, 8), (2, 4, 6)]
return any(board[i] == board[j] == board[k] == player for i, j, k in win_conditions)
def check_draw(board):
return all(space != ' ' for space in board)
def available_moves(board):
return [i for i, space in enumerate(board) if space == ' ']
# AI logic
def ai_move(board, player, opponent):
# Check for a winning move for AI
for move in available_moves(board):
board[move] = player
if check_win(board, player):
return move
board[move] = ' ' # Reset move
# Check for a block move to prevent opponent's win
for move in available_moves(board):
board[move] = opponent
if check_win(board, opponent):
board[move] = ' '
return move
board[move] = ' ' # Reset move
# Otherwise, pick a random move
return random.choice(available_moves(board))
# Main game function
def play_game():
player_symbol = 'X' # Player will be 'X'
ai_symbol = 'O' # AI will be 'O'
player_score = 0
ai_score = 0
draw_count = 0
print("Welcome to Tic-Tac-Toe!")
print(f"You are '{player_symbol}' and the AI is '{ai_symbol}'")
print("Enter your move by typing a number between 1 and 9 as follows:")
print_board([str(i+1) for i in range(9)]) # Display the board with positions 1-9
while True:
board = [' '] * 9
current_player = player_symbol
while True:
print_board(board)
# Player's move
if current_player == player_symbol:
move = int(input(f"Your turn, you are '{player_symbol}'. Enter your move (1-9): ")) - 1
if board[move] != ' ':
print("Invalid move! Try again.")
continue
else:
print(f"AI's turn, it is '{ai_symbol}'...")
move = ai_move(board, ai_symbol, player_symbol)
board[move] = current_player
# Check for win or draw
if check_win(board, current_player):
print_board(board)
if current_player == player_symbol:
print(f'Congratulations! You win this round!')
player_score += 1
else:
print(f'The AI wins this round.')
ai_score += 1
break
elif check_draw(board):
print_board(board)
print('The game is a draw!')
draw_count += 1
break
# Switch player
current_player = ai_symbol if current_player == player_symbol else player_symbol
# Display current score
print(f"\nScoreboard: You: {player_score} | AI: {ai_score} | Draws: {draw_count}")
# Ask if player wants to continue or quit
play_again = input("Do you want to play again? (y or n): ").lower()
if play_again != 'y':
print("Thanks for playing!")
print(f"Final Score: You: {player_score} | AI: {ai_score} | Draws: {draw_count}")
break
if __name__ == '__main__':
play_game()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment