0% found this document useful (0 votes)
26 views16 pages

Practical 1

The document describes a student's practical assignment to implement different methods for playing Tic-Tac-Toe against a computer opponent, including a random method, magic square method, and minmax method. It includes code for functions to print the game board, check for a winner or draw, get player/computer moves, and play a game using each approach. The output sections for each method are blank, suggesting the programs were run but no example outputs are shown.

Uploaded by

Dhruv Vyas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views16 pages

Practical 1

The document describes a student's practical assignment to implement different methods for playing Tic-Tac-Toe against a computer opponent, including a random method, magic square method, and minmax method. It includes code for functions to print the game board, check for a winner or draw, get player/computer moves, and play a game using each approach. The output sections for each method are blank, suggesting the programs were run but no example outputs are shown.

Uploaded by

Dhruv Vyas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Name – Raj Bhuva Enrollment no – 201310132060

PRACTICAL - 1

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

Random Method :-
Input :
import random

# A function to print the board


def print_board(board):
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]} ")

# A function to check if the board is full


def is_board_full(board):
return " " not in board

# A function to check if a player has won


def check_for_winner(board, player):
if (board[0] == player and board[1] == player and board[2] == player) or \
(board[3] == player and board[4] == player and board[5] == player) or \
(board[6] == player and board[7] == player and board[8] == player) or \
(board[0] == player and board[3] == player and board[6] == player) or \
(board[1] == player and board[4] == player and board[7] == player) or \
(board[2] == player and board[5] == player and board[8] == player) or \
(board[0] == player and board[4] == player and board[8] == player) or \
(board[2] == player and board[4] == player and board[6] == player):
return True
Name – Raj Bhuva Enrollment no – 201310132060

else:
return False

# A function to make a player's move


def get_player_move(board):
while True:
move = input("Enter your move (1-9): ")
if move.isdigit() and int(move) in range(1, 10) and board[int(move)-1] == " ":
return int(move) - 1
else:
print("Invalid move. Please try again.")

# A function to make the computer's move (random)


def get_computer_move(board):
while True:
move = random.randint(0, 8)
if board[move] == " ":
return move

# The main game loop


def play_game():
board = [" "] * 9
print("Welcome to Tic Tac Toe!")
print_board(board)

while not is_board_full(board):


# Human player's turn
player_move = get_player_move(board)
board[player_move] = "X"
print_board(board)
if check_for_winner(board, "X"):
print("Congratulations, you won!")
Name – Raj Bhuva Enrollment no – 201310132060

return

# Computer player's turn


computer_move = get_computer_move(board)
board[computer_move] = "O"
print("The computer played move", computer_move+1)
print_board(board)
if check_for_winner(board, "O"):
print("Sorry, you lost.")
return

print("It's a tie!")

# Start the game


play_game()

Output:-
Name – Raj Bhuva Enrollment no – 201310132060

Magic Square method :-


Input :
import random

board = [1,2,3,4,5,6,7,8,9]
magic_square = [[2, 7, 6],[9, 5, 1], [4, 3, 8]]
magic_square_l = [2, 7, 6,9, 5, 1, 4, 3, 8]
occupied = []
computer = "O"
Human = "X"
n=3

def print_board(board):
print(f" {board[0][0]} | {board[0][1]} | {board[0][2]} ")
print("------------")
print(f" {board[1][0]} | {board[1][1]} | {board[1][2]} ")
print("------------")
print(f" {board[2][0]} | {board[2][1]} | {board[2][2]} ")

def rowcheck(board):
for i in range(n):
if (board[i][0] == board[i][1]) and (board[i][1] == board[i][2]) and (board[i][0] != "*"):
print("here")
return True
return False

def colcheck(board):
for i in range(n):
if (board[0][i] == board[1][i]) and (board[2][i] == board[0][i]) and (board[0][i] != "*"):
print("here")
return True
Name – Raj Bhuva Enrollment no – 201310132060

return False

def diagonalcheck(board):
if (board[0][0] == board[1][1]) and (board[1][1] == board[2][2]) and (board[0][0] != "*"):
print("here")

return True
if (board[0][2] == board[1][1]) and (board[1][1] == board[2][0]) and (board[0][2] != "*"):
print("here")

return True
return False

def gameover(board):
return(rowcheck(board) or colcheck(board) or diagonalcheck(board))

def gamedraw(board):
if gameover(board) == True:
return False
if gameover(board) == False:
for i in range(n):
for j in range(n):
if board[i][j] == "*":
return False

def find_best_location(scores, s, e):


scores.sort()
if s == e:
return -1
while s < e:
sum = scores[s] + scores[e]
diff = 15 - sum
Name – Raj Bhuva Enrollment no – 201310132060

if diff in magic_square_l:
if diff not in occupied:
occupied.append(diff)
return diff
else:
return max(find_best_location(scores, s + 1, e), find_best_location(scores, s, e - 1))
elif diff >= 9:
s += 1
elif diff <= 0:
e -= 1
return -1

def win_location(board, player, movidx):


result = [-1,-1]
score = []
for i in range(n):
for j in range(n):
if board[i][j] == player:
score.append(magic_square[i][j])

res = find_best_location(score, 0, len(score)-1)


if res == -1:
if len(score) == 0:
result[0] = -1
result[1] = -1
elif len(score) == 1:
temp_res = -1
if((movidx == 0 and player==computer) or (movidx<=1 and player == Human)):
for i in range(len(score)):
diff = 15 - score[i]
for j in range(len(magic_square_l)):
if (diff - magic_square_l[j] > 0 and diff - magic_square_l[j]<9):
Name – Raj Bhuva Enrollment no – 201310132060

if (diff - magic_square_l[j]) not in occupied:


temp_res = diff - magic_square_l[j]
z = magic_square_l.index(temp_res)
result[0] = z / n
result[1] = z % n
occupied.append(diff - magic_square_l[j])
return result

if temp_res == -1:
result[0] = -1
result[1] = -1
return result

else:
result[0] = -1
result[1] = -1
return result

else:
print("res is not -1")
z = magic_square_l.index(res)
result[0] = z / n
result[1] = z % n

return result

def play_game(board, player, movidx):


loc = []
while (gameover(board)==False and gamedraw(board=board)==False):
if player == computer:
print("computer is thinking")
loc = win_location(board, player, movidx)
Name – Raj Bhuva Enrollment no – 201310132060

if loc[0] == -1:
loc = win_location(board, Human, movidx)
if loc[0] == -1:
x = random.randint(0 ,2)
y = random.randint(0, 2)
while board[x][y] != "*":
x = random.randint(0, 2)
y = random.randint(0, 2)
print(x,y)
board[x][y] = computer
movidx += 1
occupied.append(magic_square[x][y])
else:
print("com play move as human win")
board[int(loc[0])][int(loc[1])] = computer
movidx += 1
occupied.append(magic_square[int(loc[0])][int(loc[1])])
else:
print("com play move as computer win")
board[int(loc[0])][int(loc[1])] = computer
movidx += 1
occupied.append(magic_square[int(loc[0])][int(loc[1])])
print_board(board)
player = Human
elif player == Human:
x = int(input("enter loc x:"))
y = int(input("enter loc y:"))
if (board[x][y] != "*"):
print("already occupied")
else:
board[x][y] = Human
occupied.append(magic_square[x][y])
Name – Raj Bhuva Enrollment no – 201310132060

print_board(board)
player = computer

if gamedraw(board) == True:
print("match draw")
elif player == computer:
print("human won!")
else:
print("computer won")

board = [["*","*","*"],["*","*","*"],["*","*","*"]]
choice = int(input("enter 0 to play first or press 1 to let computer first : "))
while choice != 0 and choice != 1:
choice = int(input("enter 0 to play first or press 1 to let computer first : "))
movidx = 0
if choice == 1:
play_game(board, computer, movidx)
else:
play_game(board, Human, movidx)

Output :
Name – Raj Bhuva Enrollment no – 201310132060
Name – Raj Bhuva Enrollment no – 201310132060

Minmax method :-
Input :
# Function for Disply the tic-tac-toe game
def printBoard(board):
print(' '+ board[1] + ' | ' + board[2] + ' | ' + board[3])
print('---+---+---')
print(' '+ board[4] + ' | ' + board[5] + ' | ' + board[6])
print('---+---+---')
print(' '+ board[7] + ' | ' + board[8] + ' | ' + board[9])
print("\n")

# Function to check if any place is empty or not


def spaceIsFree(position):
if board[position] == ' ':
return True
else:
return False

# Function for input


def insertLetter(letter, position):
if spaceIsFree(position):
board[position] = letter
printBoard(board)

# Disply the final Output


if (checkDraw()):
print("Draw!")
exit()
if checkForWin():
if letter == 'X':
print("Computer wins!")
exit()
Name – Raj Bhuva Enrollment no – 201310132060

else:
print("Player wins!")
exit()

return

else:
print("Can't insert there!")
position = int(input("Please enter new position: "))
insertLetter(letter, position)
return

# Function to check for a winning combination in the game


def checkForWin():
if (board[1] == board[2] and board[1] == board[3] and board[1] != ' '):
return True
elif (board[4] == board[5] and board[4] == board[6] and board[4] != ' '):
return True
elif (board[7] == board[8] and board[7] == board[9] and board[7] != ' '):
return True
elif (board[1] == board[4] and board[1] == board[7] and board[1] != ' '):
return True
elif (board[2] == board[5] and board[2] == board[8] and board[2] != ' '):
return True
elif (board[3] == board[6] and board[3] == board[9] and board[3] != ' '):
return True
elif (board[1] == board[5] and board[1] == board[9] and board[1] != ' '):
return True
elif (board[7] == board[5] and board[7] == board[3] and board[7] != ' '):
return True
else:
return False
Name – Raj Bhuva Enrollment no – 201310132060

def checkWhichMarkWon(mark):
if board[1] == board[2] and board[1] == board[3] and board[1] == mark:
return True
elif (board[4] == board[5] and board[4] == board[6] and board[4] == mark):
return True
elif (board[7] == board[8] and board[7] == board[9] and board[7] == mark):
return True
elif (board[1] == board[4] and board[1] == board[7] and board[1] == mark):
return True
elif (board[2] == board[5] and board[2] == board[8] and board[2] == mark):
return True
elif (board[3] == board[6] and board[3] == board[9] and board[3] == mark):
return True
elif (board[1] == board[5] and board[1] == board[9] and board[1] == mark):
return True
elif (board[7] == board[5] and board[7] == board[3] and board[7] == mark):
return True
else:
return False

# Function for the user's move


def checkDraw():
for key in board.keys():
if (board[key] == ' '):
return False
return True

def playerMove():
position = int(input("Enter the position for 'O': "))
insertLetter(player, position)
return
Name – Raj Bhuva Enrollment no – 201310132060

# Function for the computer's move


def compMove():
bestScore = -800
bestMove = 0
for key in board.keys():
if (board[key] == ' '):
board[key] = bot
score = minimax(board, 0, False)
board[key] = ' '
if (score > bestScore):
bestScore = score
bestMove = key

insertLetter(bot, bestMove)
return

# applying minmax method


def minimax(board, depth, isMaximizing):
if (checkWhichMarkWon(bot)):
return 1
elif (checkWhichMarkWon(player)):
return -1
elif (checkDraw()):
return 0

if (isMaximizing):
bestScore = -800
for key in board.keys():
if (board[key] == ' '):
board[key] = bot
score = minimax(board, depth + 1, False)
Name – Raj Bhuva Enrollment no – 201310132060

board[key] = ' '


if (score > bestScore):
bestScore = score
return bestScore

else:
bestScore = 800
for key in board.keys():
if (board[key] == ' '):
board[key] = player
score = minimax(board, depth + 1, True)
board[key] = ' '
if (score < bestScore):
bestScore = score
return bestScore

# Play the game


board = {1: ' ', 2: ' ', 3: ' ',
4: ' ', 5: ' ', 6: ' ',
7: ' ', 8: ' ', 9: ' '}

printBoard(board)
print("Computer goes first! Good luck.")
print("Positions are as follow:")
print("1, 2, 3 ")
print("4, 5, 6 ")
print("7, 8, 9 ")
print("\n")
player = 'O'
bot = 'X'

global firstComputerMove
Name – Raj Bhuva Enrollment no – 201310132060

firstComputerMove = True

while not checkForWin():


playerMove()
compMove()

Output :

You might also like