AI PRACTICAL PROJECT: Tic-Tac-Toe Game
Submitted by: Hardik Shukla
Submitted to: Mr. Shekhar Srivastava
What is an AI Game?
An AI game is a video game that uses artificial intelligence to control elements like non-player
characters (NPCs), game environments, or gameplay mechanics, creating dynamic and adaptive
experiences. The Game that we have created using AI is TIC-TAC-TOE.
What is Tic-Tac-Toe?
Tic Tac Toe is a simple two-player game played on a 3x3 grid. Players take turns marking one of the
empty squares with either an 'X' or an 'O.' The objective is to get three of your marks in a row, either
horizontally, vertically, or diagonally, before your opponent does.
Python Code for Tic-Tac-Toe
import random
def print_board(board):
for row in board:
print(" | ".join(row))
print("---------")
def check_win(board, player):
for i in range(3):
if all(board[i][j] == player for j in range(3)):
return True
if all(board[j][i] == player for j in range(3)):
return True
if all(board[i][i] == player for i in range(3)):
return True
if all(board[i][2 - i] == player for i in range(3)):
return True
return False
def check_draw(board):
return all(board[i][j] != " " for i in range(3) for j in range(3))
def ai_move(board):
empty_cells = [(i, j) for i in range(3) for j in range(3) if board[i][j] == " "]
return [Link](empty_cells)
def tic_tac_toe():
board = [[" " for _ in range(3)] for _ in range(3)]
current_player = "X"
while True:
print_board(board)
if current_player == "X":
try:
row = int(input("Player X, enter the row (0-2): "))
col = int(input("Player X, enter the column (0-2): "))
if row < 0 or row > 2 or col < 0 or col > 2:
print("Invalid input! Please enter values between 0 and 2.")
continue
if board[row][col] != " ":
print("Cell already taken. Try again.")
continue
except ValueError:
print("Invalid input! Please enter integers between 0 and 2.")
continue
board[row][col] = current_player
else:
print("AI (O) is making a move...")
row, col = ai_move(board)
board[row][col] = current_player
if check_win(board, current_player):
print_board(board)
print(f"Player {current_player} wins!")
break
if check_draw(board):
print_board(board)
print("It's a draw!")
break
current_player = "O" if current_player == "X" else "X"
if __name__ == "__main__":
tic_tac_toe()
Sample Gameplay and Result
Sample gameplay session between Player X and AI (O):
X | X | X
---------
| O |
---------
| | O
Player X wins by completing a row!
This visual representation helps players understand game progress.