A Game of Tic-Tac-Toe in Python Algorithm

A Game of Tic-Tac-Toe in Python Algorithm

Tic-tac-toe is a two-player game played on a 3×3 grid. The players take turns placing their marks (X or O) on the grid. The first player to get three of their marks in a row, column, or diagonal wins the game.

The program should be able to play a game of tic-tac-toe against a human opponent. The program should also be able to print the game to the console.

Python implementation of automatic Tic Tac Toe game

Here is a solution to the exercise:

def tic_tac_toe(board):
"""
Plays a game of tic-tac-toe on a given board.

Args:
board: A 3×3 array of characters.

Returns:
The winner of the game, or None if the game is a tie.
“””

for row in range(3):
if board[row][0] == board[row][1] == board[row][2] != “.”:
return board[row][0]
if board[0][row] == board[1][row] == board[2][row] != “.”:
return board[0][row]
if board[0][0] == board[1][1] == board[2][2] != “.”:
return board[0][0]
if board[0][2] == board[1][1] == board[2][0] != “.”:
return board[0][2]

for i in range(3):
for j in range(3):
if board[i][j] == “.”:
return None

return “Tie”

def print_board(board):
for row in board:
print(” “.join(row))

board = [“.”, “.”, “.”, “.”, “.”, “.”, “.”, “.”, “.”]
print_board(board)
winner = tic_tac_toe(board)
if winner is not None:
print(“The winner is {}!”.format(winner))
else:
print(“The game is a tie!”)

Description:

This code will play a game of tic-tac-toe against a human opponent. The code uses a simple algorithm to determine the winner of the game. The algorithm checks if there are three of the same marks in a row, column, or diagonal. If there are, the algorithm returns the winner. If there are no three of the same marks, the algorithm checks if all of the squares are filled in. If they are, the algorithm returns a tie.

The tic_tac_toe() function takes one argument: the board. The function checks if there is a winner, and if there is, the function returns the winner. If there is no winner, the function returns None.

The print_board() function takes one argument: the board. The function prints the board to the console.

Have Fun!

2 thoughts on “A Game of Tic-Tac-Toe in Python Algorithm”

Leave a comment