Here's a complete Python script for a Tic-Tac-Toe game that can be played in the console:
python
import random
def print_board(board):
"""Prints the current state of the board."""
print("\n")
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]} ")
print("\n")
def check_winner(board):
"""Checks if there's a winner or if the game is a tie."""
# Check rows
for i in range(0, 9, 3):
if board[i] == board[i+1] == board[i+2] != " ":
return board[i]
# Check columns
for i in range(3):
if board[i] == board[i+3] == board[i+6] != " ":
return board[i]
# Check diagonals
if board[0] == board[4] == board[8] != " ":
return board[0]
if board[2] == board[4] == board[6] != " ":
return board[2]
# Check for tie
if " " not in board:
return "Tie"
return None
def player_move(board):
"""Handles the player's move."""
while True:
try:
move = int(input("Enter your move (1-9): ")) - 1
if 0 <= move <= 8 and board[move] == " ":
return move
else:
print("Invalid move. Try again.")
except ValueError:
print("Please enter a number between 1 and 9.")
def computer_move(board, computer_char):
"""Handles the computer's move (simple AI)."""
# Check for winning move
for i in range(9):
if board[i] == " ":
board_copy = board.copy()
board_copy[i] = computer_char
if check_winner(board_copy) == computer_char:
return i
# Check for blocking player's winning move
player_char = "O" if computer_char == "X" else "X"
for i in range(9):
if board[i] == " ":
board_copy = board.copy()
board_copy[i] = player_char
if check_winner(board_copy) == player_char:
return i
# Choose center if available
if board[4] == " ":
return 4
# Choose a random corner
corners = [0, 2, 6, 8]
available_corners = [c for c in corners if board[c] == " "]
if available_corners:
return random.choice(available_corners)
# Choose a random side
sides = [1, 3, 5, 7]
available_sides = [s for s in sides if board[s] == " "]
if available_sides:
return random.choice(available_sides)
# This should never be reached if the game is properly checked for ties
return random.choice([i for i, spot in enumerate(board) if spot == " "])
def play_game():
"""Main game loop."""
print("Welcome to Tic-Tac-Toe!")
print("The board positions are numbered as follows:")
print_board(["1", "2", "3", "4", "5", "6", "7", "8", "9"])
while True:
# Choose who goes first
choice = input("Do you want to go first? (y/n): ").lower()
if choice in ['y', 'yes']:
player_char = "X"
computer_char = "O"
player_turn = True
elif choice in ['n', 'no']:
player_char = "O"
computer_char = "X"
player_turn = False
else:
print("Invalid choice. Please enter 'y' or 'n'.")
continue
# Initialize the board
board = [" "] * 9
game_over = False
while not game_over:
if player_turn:
print_board(board)
move = player_move(board)
board[move] = player_char
else:
print("Computer's turn...")
move = computer_move(board, computer_char)
board[move] = computer_char
print(f"Computer chose position {move + 1}")
# Check for winner or tie
result = check_winner(board)
if result:
print_board(board)
if result == "Tie":
print("It's a tie!")
elif result == player_char:
print("Congratulations! You win!")
else:
print("Computer wins!")
game_over = True
# Switch turns
player_turn = not player_turn
# Ask to play again
play_again = input("Do you want to play again? (y/n): ").lower()
if play_again not in ['y', 'yes']:
print("Thanks for playing!")
break
if __name__ == "__main__":
play_game()
Features of this Tic-Tac-Toe game:
Player vs Computer - You can choose to go first or second
Simple AI - The computer makes strategic moves (tries to win, block, take center, etc.)