Ai PRA1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

Practical-1

1. Write a program to implement Tic-Tac-Toe game problem.


Tic-Tac-Toe, also known as Noughts and Crosses, is a simple two-player game played on
a 3x3 grid. The objective is for one player to form a line of their symbol (either "X" or
"O") horizontally, vertically, or diagonally before the other player does. The game can
result in three possible outcomes: a win for Player 1, a win for Player 2, or a draw (also
known as a "cat's game").
 Algorithm:
Here's a high-level algorithm for implementing a two-player Tic-Tac-Toe game in
Python:
1. Initialize the Game Board:
→ Create a 3x3 grid (matrix) to represent the game board.
→ Initialize the grid with empty cells, typically represented as spaces or some other
placeholder.
2. Define Players:
→ Assign one player to "X" and the other player to "O."
3. Display the Game Board:
→ Create a function to print the game board to the console. The function should display
the current state of the board with grid lines.
4. Game Loop:
→ Create a loop that continues until the game is over (either a player wins or it's a
draw).
→ Inside the loop, alternate between the two players (Player 1 and Player 2).
→ For each player's turn, do the following:
→ Prompt the current player for their move (usually the row and column they want to
place their symbol).
→ Check if the chosen cell is empty. If it is, update the cell with the player's symbol.
→ After each move, check for a win condition by calling a function that checks rows,
columns, and diagonals for three matching symbols.
→ Also, check for a draw condition by verifying if all cells are filled with symbols.
→ If either a win or a draw is detected, end the game loop.
5. End of Game:
→ When the game loop ends, display the result:
→ If a player has won, announce the winner.
→ If it's a draw, announce a draw.
6. Play Again (Optional):
→ Ask the players if they want to play another game. If yes, reset the game board and
repeat the game loop. If not, exit the program.

 Implementation of Tic Tac Toe using Python:

# Function to print the tic-tac-toe board


def print_board(board):
for row in board:
print(" | ".join(row))
print("-" * 9)

# Function to check if a player has won


def check_win(board, player):
for row in board:
if all(cell == player for cell in row):
return True
for col in range(3):
if all(board[row][col] == player for row in range(3)):
return True
if all(board[i][i] == player for i in range(3)) or all(board[i][2 - i] == player for i in
range(3)):
return True
return False

# Function to play against the computer


def play_vs_computer():
board = [[" " for _ in range(3)] for _ in range(3)]
player_symbol = input("Choose your symbol (X or O): ").upper()
computer_symbol = "X" if player_symbol == "O" else "O"

print("You are playing as", player_symbol)


print("The computer is playing as", computer_symbol)

# Determine who goes first


if input("Do you want to go first? (yes/no): ").lower() == "yes":
current_player = player_symbol
else:
current_player = computer_symbol

for _ in range(9):
print_board(board)
if current_player == player_symbol:
while True:
try:
row = int(input("Enter row (0, 1, or 2): "))
col = int(input("Enter column (0, 1, or 2): "))
if board[row][col] == " ":
board[row][col] = player_symbol
break
else:
print("That cell is already occupied. Try again.")
except (ValueError, IndexError):
print("Invalid input. Please enter valid row and column numbers.")
else:
print("Computer's turn...")
make_computer_move(board, computer_symbol)

if check_win(board, current_player):
print_board(board)
if current_player == player_symbol:
print("You win!")
else:
print("The computer wins!")
break
current_player = player_symbol if current_player == computer_symbol else
computer_symbol
else:
print_board(board)
print("It's a draw!")

# Function to make the computer's move


def make_computer_move(board, computer_symbol):
# Check for a possible winning move for the computer
for row in range(3):
for col in range(3):
if board[row][col] == " ":
board[row][col] = computer_symbol
if check_win(board, computer_symbol):
return
board[row][col] = " "

# Check for a possible winning move for the player and block it
player_symbol = "X" if computer_symbol == "O" else "O"
for row in range(3):
for col in range(3):
if board[row][col] == " ":
board[row][col] = player_symbol
if check_win(board, player_symbol):
board[row][col] = computer_symbol
return
board[row][col] = " "

# If no winning moves are found, make a random move


import random

while True:
row = random.randint(0, 2)
col = random.randint(0, 2)
if board[row][col] == " ":
board[row][col] = computer_symbol
return

# Function to play against another user


def play_vs_user():
board = [[" " for _ in range(3)] for _ in range(3)]
players = ["X", "O"]
current_player = "X"

print("Welcome to Tic-Tac-Toe! Player 1 is X, and Player 2 is O.")

for _ in range(9):
print_board(board)
while True:
try:
row = int(input(f"Player {current_player}'s turn. Enter row (0, 1, or 2): "))
col = int(input(f"Player {current_player}'s turn. Enter column (0, 1, or 2): "))
if board[row][col] == " ":
board[row][col] = current_player
break
else:
print("That cell is already occupied. Try again.")
except (ValueError, IndexError):
print("Invalid input. Please enter valid row and column numbers.")
if check_win(board, current_player):
print_board(board)
print(f"Player {current_player} wins!")
break
elif " " not in board[0] and " " not in board[1] and " " not in board[2]:
print_board(board)
print("It's a draw!")
break

current_player = "X" if current_player == "O" else "O"

# Main game loop


while True:
print("Choose a mode:")
print("1. Play against the computer")
print("2. Play against another user")
print("3. Quit")

choice = input("Enter your choice (1/2/3): ")

if choice == "1":
play_vs_computer()
elif choice == "2":
play_vs_user()
elif choice == "3":
print("Goodbye!")
break
else:
print("Invalid choice. Please choose 1, 2, or 3.")

 Output:

You might also like