Tic- tac- toe is a classic two- player game that has been enjoyed by people of all periods for generations. The ideal of the game is to get three of your symbol( either” x” or” o”) in a row, either horizontally, vertically, or transversely, before your opponent does. The first player to do so wins thegame.However, the game is a draw, If all of the spaces on the tic- tac- toe board are filled and no bone has won.
import random
# The board is represented as a list of strings. Each string is a row on the board,
# and the characters in the string are either " ", "x", or "o"
board = [ " ", " ", " ",
" ", " ", " ",
" ", " ", " " ]
# The minimax function
def minimax(board, depth, maximizingPlayer):
# Base case: the game is over and someone has won (or it's a draw)
winner = check_win(board)
if winner != " ":
if winner == "x":
return 1
elif winner == "o":
return -1
else:
return 0
# Recursive case: the game is not over yet
if maximizingPlayer:
# Maximizing player's turn (computer)
bestValue = -float("inf")
for i in range(9):
if board [ i ] == " ":
board [ i ] = "o"
value = minimax(board, depth + 1, False)
board [ i ] = " "
bestValue = max(bestValue, value)
return bestValue
else:
# Minimizing player's turn (human)
bestValue = float("inf")
for i in range(9):
if board [ i ] == " ":
board [ i ] = "x"
value = minimax(board, depth + 1, True)
board [ i ] = " "
bestValue = min(bestValue, value)
return bestValue
# The function to determine the best move for the computer
def get_best_move(board):
bestValue = -float("inf")
bestMove = None
for i in range(9):
if board [ i ] == " ":
board [ i ] = "o"
value = minimax(board, 0, False)
board [ i ] = " "
if value > bestValue:
bestValue = value
bestMove = i
return bestMove
def check_win(board):
# Check rows
for i in range(3):
if board[3*i] == board[3*i+1] == board[3*i+2] and board[3*i] != " ":
return board[3*i]
# Check columns
for i in range(3):
if board[i] == board[i+3] == board[i+6] and board[i] != " ":
return board[i]
# Check diagonals
if board[0] == board[4] == board[8] and board[0] != " ":
return board[0]
if board[2] == board[4] == board[6] and board[2] != " ":
return board[2]
# No one has won yet
return " "
# The main game loop
def play_game():
# Print the initial board
print_board(board)
# Keep playing until the game is over
while True:
# Get the human player's move
move = get_human_move(board)
# Update the board with the move
board [ move ] = "x"
# Check if the game is over
winner = check_win(board)
if winner != " ":
print_board(board)
print(winner, "wins!")
break
# Check if the board is full (tie game)
if is_full(board):
print_board(board)
print("It's a draw!")
break
# Get the computer's move
move = get_best_move(board)
# Update the board with the move
board [ move ] = "o"
# Print the updated board
print_board(board)
# Check if the game is over
winner = check_win(board)
if winner != " ":
print(winner, "wins!")
break
# Check if the board is full (tie game)
if is_full(board):
print("It's a draw!")
break
# The function to get the human player's move
def get_human_move(board):
# Get the human player's move
while True:
move = input("Enter your move (0-8): ")
try:
move = int(move)
if move >= 0 and move <= 8 and board [ move ] == " ":
return move
else:
print("Invalid move. Try again.")
except ValueError:
print("Invalid input. Try again.")
# The function to check if the board is full
def is_full(board):
for i in range(9):
if board [ i ] == " ":
return False
return True
# The function to print the board
def print_board(board):
print(" " + board [ 0 ] + " | " + board [ 1 ] + " | " + board [ 2 ] + " ")
print("---+---+---")
print(" " + board [ 3 ] + " | " + board [ 4 ] + " | " + board [ 5 ] + " ")
print("---+---+---")
print(" " + board [ 6 ] + " | " + board [ 7 ] + " | " + board [ 8 ] + " ")
# Start the game!
play_game()
This tic- tac- toe game is enforced in Python and allows you to play against a computer opponent. The computer uses the minimax algorithm to choose its moves, which means that it’ll always play optimally and try to block your attempts to win or force a draw. To start a new game, simply run theplay_game function. The x player will be controlled by the stoner, and the o player will be the computer.
The game consists of a main game circle that continues until the game is over. On each turn, the mortal player is urged to enter their move( a number from 0 to 8, representing the spaces on the tic- tac- toe board). If the move is valid( i.e., the chosen space is empty), the board is streamlined with the player’s symbol and the computer’s turn begins. The computer uses theget_best_move function, which employs the minimax algorithm, to choose its move. The board is also streamlined with the computer’s symbol, and the game checks to see if either player has won or if the game is adraw.However, the winner( if there’s one) is blazoned or the game is declared a draw, If the game isover.However, the circle continues and the mortal player’s turn begins again, If the game isn’t yet over.
Thecheck_win function is used to determine if either player has won the game. It checks each row, column, and slant on the board to see if any of them are filled by the same player’ssymbol.However, column, or slant, If it finds a winningrow.However, it returns an empty string(“”), If the board is full and no bone haswon.However, it returns the string””, If the game isn’t yet over and no bone has won.