SlideShare a Scribd company logo
Practical-7
1 | P a g e
Name:- Nayan Oza
Enrollment No :- 19012011102
AIM:- Write a program to create tic-tac-toe game using minimax
algorithm.
Consider following steps to create a program in python:
1. Create class StateNode with its proper members (getScoreValue(),
isValidMove(), isGameOver(), drawboard(), getEmptyCells(),
setMove(),
isWin(), etc.)
2. Create class ticTacToe with its proper members (minimax(),
computerMove(),
playerMove(), execution(), etc.)
3. Output should be according shown in Output image
4. Use only math, random, matplotlib libraries in python
Input :-
from math import inf as infinity
from random import choice
import platform
import time
print("19012011102_Nayan Oza")
from os import system
HUMAN = -1
COMP = +1
board = [
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],]
def evaluate(state):
if wins(state, COMP):
Practical-7
2 | P a g e
Name:- Nayan Oza
Enrollment No :- 19012011102
score = +1
elif wins(state, HUMAN):
score = -1
else:
score = 0
return score
def wins(state, player):
win_state = [
[state[0][0], state[0][1], state[0][2]],
[state[1][0], state[1][1], state[1][2]],
[state[2][0], state[2][1], state[2][2]],
[state[0][0], state[1][0], state[2][0]],
[state[0][1], state[1][1], state[2][1]],
[state[0][2], state[1][2], state[2][2]],
[state[0][0], state[1][1], state[2][2]],
[state[2][0], state[1][1], state[0][2]],
]
if [player, player, player] in win_state:
return True
else:
return False
def game_over(state):
return wins(state, HUMAN) or wins(state, COMP)
def empty_cells(state):
cells = []
for x, row in enumerate(state):
Practical-7
3 | P a g e
Name:- Nayan Oza
Enrollment No :- 19012011102
for y, cell in enumerate(row):
if cell == 0:
cells.append([x, y])
return cells
def valid_move(x, y):
if [x, y] in empty_cells(board):
return True
else:
return False
def set_move(x, y, player):
if valid_move(x, y):
board[x][y] = player
return True
else:
return False
def minimax(state, depth, player):
if player == COMP:
best = [-1, -1, -infinity]
else:
best = [-1, -1, +infinity]
if depth == 0 or game_over(state):
score = evaluate(state)
return [-1, -1, score]
for cell in empty_cells(state):
x, y = cell[0], cell[1]
state[x][y] = player
score = minimax(state, depth - 1, -player)
Practical-7
4 | P a g e
Name:- Nayan Oza
Enrollment No :- 19012011102
state[x][y] = 0
score[0], score[1] = x, y
if player == COMP:
if score[2] > best[2]:
best = score
else:
if score[2] < best[2]:
best = score
return best
def clean():
os_name = platform.system().lower()
if 'windows' in os_name:
system('cls')
else:
system('clear')
def render(state, c_choice, h_choice):
chars = {
-1: h_choice,
+1: c_choice,
0: ' '
}
str_line = '---------------'
print('n' + str_line)
for row in state:
for cell in row:
symbol = chars[cell]
print(f'| {symbol} |', end='')
Practical-7
5 | P a g e
Name:- Nayan Oza
Enrollment No :- 19012011102
print('n' + str_line)
def ai_turn(c_choice, h_choice):
depth = len(empty_cells(board))
if depth == 0 or game_over(board):
return
clean()
print(f'Computer turn [{c_choice}]')
render(board, c_choice, h_choice)
if depth == 9:
x = choice([0, 1, 2])
y = choice([0, 1, 2])
else:
move = minimax(board, depth, COMP)
x, y = move[0], move[1]
set_move(x, y, COMP)
time.sleep(1)
def human_turn(c_choice, h_choice):
depth = len(empty_cells(board))
if depth == 0 or game_over(board):
return
move = -1
moves = {
1: [0, 0], 2: [0, 1], 3: [0, 2],
Practical-7
6 | P a g e
Name:- Nayan Oza
Enrollment No :- 19012011102
4: [1, 0], 5: [1, 1], 6: [1, 2],
7: [2, 0], 8: [2, 1], 9: [2, 2],
}
clean()
print(f'Human turn [{h_choice}]')
render(board, c_choice, h_choice)
while move < 1 or move > 9:
try:
move = int(input('Use numpad (1..9): '))
coord = moves[move]
can_move = set_move(coord[0], coord[1], HUMAN)
if not can_move:
print('Bad move')
move = -1
except (EOFError, KeyboardInterrupt):
print('Close')
exit()
except (KeyError, ValueError):
print('Bad choice')
def main():
clean()
h_choice = ''
c_choice = ''
first = ''
while h_choice != 'O' and h_choice != 'X':
try:
print('')
Practical-7
7 | P a g e
Name:- Nayan Oza
Enrollment No :- 19012011102
h_choice = input('Choose X or OnChosen: ').upper()
except (EOFError, KeyboardInterrupt):
print('Close')
exit()
except (KeyError, ValueError):
print('Bad choice')
if h_choice == 'X':
c_choice = 'O'
else:
c_choice = 'X'
clean()
while first != 'Y' and first != 'N':
try:
first = input('First to start?[y/n]: ').upper()
except (EOFError, KeyboardInterrupt):
print('Close')
exit()
except (KeyError, ValueError):
print('Bad choice')
while len(empty_cells(board)) > 0 and not game_over(board):
if first == 'N':
ai_turn(c_choice, h_choice)
first = ''
human_turn(c_choice, h_choice)
ai_turn(c_choice, h_choice)
if wins(board, HUMAN):
Practical-7
8 | P a g e
Name:- Nayan Oza
Enrollment No :- 19012011102
clean()
print(f'Human turn [{h_choice}]')
render(board, c_choice, h_choice)
print('YOU WIN!')
elif wins(board, COMP):
clean()
print(f'Computer turn [{c_choice}]')
render(board, c_choice, h_choice)
print('YOU LOSE!')
else:
clean()
render(board, c_choice, h_choice)
print('DRAW!')
#exit()
if __name__ == '__main__':
main()
Output :-
Practical-7
9 | P a g e
Name:- Nayan Oza
Enrollment No :- 19012011102
Practical-7
10 | P a g e
Name:- Nayan Oza
Enrollment No :- 19012011102

More Related Content

What's hot

Lab manual operating system [cs 502 rgpv] (usefulsearch.org) (useful search)
Lab manual operating system [cs 502 rgpv] (usefulsearch.org)  (useful search)Lab manual operating system [cs 502 rgpv] (usefulsearch.org)  (useful search)
Lab manual operating system [cs 502 rgpv] (usefulsearch.org) (useful search)
Make Mannan
 
Gui programming
Gui programmingGui programming
Gui programming
manikanta361
 
Guaranteeing Memory Safety in Rust
Guaranteeing Memory Safety in RustGuaranteeing Memory Safety in Rust
Guaranteeing Memory Safety in Rust
nikomatsakis
 
Introduction to PowerShell
Introduction to PowerShellIntroduction to PowerShell
Introduction to PowerShell
Boulos Dib
 
Python Pandas for Data Science cheatsheet
Python Pandas for Data Science cheatsheet Python Pandas for Data Science cheatsheet
Python Pandas for Data Science cheatsheet
Dr. Volkan OBAN
 
Webinar: The Visual Query Profiler and MongoDB Compass
Webinar: The Visual Query Profiler and MongoDB CompassWebinar: The Visual Query Profiler and MongoDB Compass
Webinar: The Visual Query Profiler and MongoDB Compass
MongoDB
 
Security DevOps - Free pentesters' time to focus on high-hanging fruits // Ha...
Security DevOps - Free pentesters' time to focus on high-hanging fruits // Ha...Security DevOps - Free pentesters' time to focus on high-hanging fruits // Ha...
Security DevOps - Free pentesters' time to focus on high-hanging fruits // Ha...
Christian Schneider
 
Protecting browsers’ secrets in a domain environment
Protecting browsers’ secrets in a domain environmentProtecting browsers’ secrets in a domain environment
Protecting browsers’ secrets in a domain environment
Itai Grady
 
Time Sensitive Networking in the Linux Kernel
Time Sensitive Networking in the Linux KernelTime Sensitive Networking in the Linux Kernel
Time Sensitive Networking in the Linux Kernel
henrikau
 
Python Programming: Lists, Modules, Exceptions
Python Programming: Lists, Modules, ExceptionsPython Programming: Lists, Modules, Exceptions
Python Programming: Lists, Modules, Exceptions
Sreedhar Chowdam
 
Code injection
Code injectionCode injection
Code injection
Gayatri Patel
 
Python Programming
Python ProgrammingPython Programming
Python Programming
Sreedhar Chowdam
 
Cloud Storage - Nirvanix Overview
Cloud Storage - Nirvanix OverviewCloud Storage - Nirvanix Overview
Cloud Storage - Nirvanix Overview
Nirvanix
 
A Solution Manual For A First Course In Probability
A Solution Manual For  A First Course In ProbabilityA Solution Manual For  A First Course In Probability
A Solution Manual For A First Course In Probability
Mary Calkins
 
ReVaulting! Decryption and opportunities
ReVaulting! Decryption and opportunitiesReVaulting! Decryption and opportunities
ReVaulting! Decryption and opportunities
Reality Net System Solutions
 
CodeChecker summary 21062021
CodeChecker summary 21062021CodeChecker summary 21062021
CodeChecker summary 21062021
Olivera Milenkovic
 
tkinter final ppt.ppt
tkinter final ppt.ppttkinter final ppt.ppt
tkinter final ppt.ppt
KanuAgrawal2
 
Dictionary in python
Dictionary in pythonDictionary in python
Dictionary in python
vikram mahendra
 
DMA Survival Guide
DMA Survival GuideDMA Survival Guide
DMA Survival Guide
Kernel TLV
 
Python matplotlib cheat_sheet
Python matplotlib cheat_sheetPython matplotlib cheat_sheet
Python matplotlib cheat_sheet
Nishant Upadhyay
 

What's hot (20)

Lab manual operating system [cs 502 rgpv] (usefulsearch.org) (useful search)
Lab manual operating system [cs 502 rgpv] (usefulsearch.org)  (useful search)Lab manual operating system [cs 502 rgpv] (usefulsearch.org)  (useful search)
Lab manual operating system [cs 502 rgpv] (usefulsearch.org) (useful search)
 
Gui programming
Gui programmingGui programming
Gui programming
 
Guaranteeing Memory Safety in Rust
Guaranteeing Memory Safety in RustGuaranteeing Memory Safety in Rust
Guaranteeing Memory Safety in Rust
 
Introduction to PowerShell
Introduction to PowerShellIntroduction to PowerShell
Introduction to PowerShell
 
Python Pandas for Data Science cheatsheet
Python Pandas for Data Science cheatsheet Python Pandas for Data Science cheatsheet
Python Pandas for Data Science cheatsheet
 
Webinar: The Visual Query Profiler and MongoDB Compass
Webinar: The Visual Query Profiler and MongoDB CompassWebinar: The Visual Query Profiler and MongoDB Compass
Webinar: The Visual Query Profiler and MongoDB Compass
 
Security DevOps - Free pentesters' time to focus on high-hanging fruits // Ha...
Security DevOps - Free pentesters' time to focus on high-hanging fruits // Ha...Security DevOps - Free pentesters' time to focus on high-hanging fruits // Ha...
Security DevOps - Free pentesters' time to focus on high-hanging fruits // Ha...
 
Protecting browsers’ secrets in a domain environment
Protecting browsers’ secrets in a domain environmentProtecting browsers’ secrets in a domain environment
Protecting browsers’ secrets in a domain environment
 
Time Sensitive Networking in the Linux Kernel
Time Sensitive Networking in the Linux KernelTime Sensitive Networking in the Linux Kernel
Time Sensitive Networking in the Linux Kernel
 
Python Programming: Lists, Modules, Exceptions
Python Programming: Lists, Modules, ExceptionsPython Programming: Lists, Modules, Exceptions
Python Programming: Lists, Modules, Exceptions
 
Code injection
Code injectionCode injection
Code injection
 
Python Programming
Python ProgrammingPython Programming
Python Programming
 
Cloud Storage - Nirvanix Overview
Cloud Storage - Nirvanix OverviewCloud Storage - Nirvanix Overview
Cloud Storage - Nirvanix Overview
 
A Solution Manual For A First Course In Probability
A Solution Manual For  A First Course In ProbabilityA Solution Manual For  A First Course In Probability
A Solution Manual For A First Course In Probability
 
ReVaulting! Decryption and opportunities
ReVaulting! Decryption and opportunitiesReVaulting! Decryption and opportunities
ReVaulting! Decryption and opportunities
 
CodeChecker summary 21062021
CodeChecker summary 21062021CodeChecker summary 21062021
CodeChecker summary 21062021
 
tkinter final ppt.ppt
tkinter final ppt.ppttkinter final ppt.ppt
tkinter final ppt.ppt
 
Dictionary in python
Dictionary in pythonDictionary in python
Dictionary in python
 
DMA Survival Guide
DMA Survival GuideDMA Survival Guide
DMA Survival Guide
 
Python matplotlib cheat_sheet
Python matplotlib cheat_sheetPython matplotlib cheat_sheet
Python matplotlib cheat_sheet
 

Similar to 19012011102_Nayan Oza_Practical-7_AI.pdf

The main class of the tictoe game looks like.public class Main {.pdf
The main class of the tictoe game looks like.public class Main {.pdfThe main class of the tictoe game looks like.public class Main {.pdf
The main class of the tictoe game looks like.public class Main {.pdf
asif1401
 
Need help writing the code for a basic java tic tac toe game Tic.pdf
Need help writing the code for a basic java tic tac toe game Tic.pdfNeed help writing the code for a basic java tic tac toe game Tic.pdf
Need help writing the code for a basic java tic tac toe game Tic.pdf
hainesburchett26321
 
Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語
ikdysfm
 
AI CHALLENGE ADMIN
AI CHALLENGE ADMINAI CHALLENGE ADMIN
AI CHALLENGE ADMIN
Ankit Gupta
 
The Ring programming language version 1.10 book - Part 71 of 212
The Ring programming language version 1.10 book - Part 71 of 212The Ring programming language version 1.10 book - Part 71 of 212
The Ring programming language version 1.10 book - Part 71 of 212
Mahmoud Samir Fayed
 
Python From Scratch (1).pdf
Python From Scratch  (1).pdfPython From Scratch  (1).pdf
Python From Scratch (1).pdf
NeerajChauhan697157
 
calculator_new (1).pdf
calculator_new (1).pdfcalculator_new (1).pdf
calculator_new (1).pdf
ni30ji
 
Hello, I need some assistance in writing a java program THAT MUST US.pdf
Hello, I need some assistance in writing a java program THAT MUST US.pdfHello, I need some assistance in writing a java program THAT MUST US.pdf
Hello, I need some assistance in writing a java program THAT MUST US.pdf
FashionColZone
 
p.pdf
p.pdfp.pdf
Intro to OTP in Elixir
Intro to OTP in ElixirIntro to OTP in Elixir
Intro to OTP in Elixir
Jesse Anderson
 
Hello!This is Java assignment applet.Can someone help me writing.pdf
Hello!This is Java assignment applet.Can someone help me writing.pdfHello!This is Java assignment applet.Can someone help me writing.pdf
Hello!This is Java assignment applet.Can someone help me writing.pdf
jyothimuppasani1
 
#include stdio.h #include string.h #include stdlib.h #in.pdf
#include stdio.h #include string.h #include stdlib.h #in.pdf#include stdio.h #include string.h #include stdlib.h #in.pdf
#include stdio.h #include string.h #include stdlib.h #in.pdf
singhanubhav1234
 
ObjectiveCreate a graphical game of minesweeper IN JAVA. The boar.pdf
ObjectiveCreate a graphical game of minesweeper IN JAVA. The boar.pdfObjectiveCreate a graphical game of minesweeper IN JAVA. The boar.pdf
ObjectiveCreate a graphical game of minesweeper IN JAVA. The boar.pdf
rajkumarm401
 
The Ring programming language version 1.3 book - Part 52 of 88
The Ring programming language version 1.3 book - Part 52 of 88The Ring programming language version 1.3 book - Part 52 of 88
The Ring programming language version 1.3 book - Part 52 of 88
Mahmoud Samir Fayed
 
goal_state = [1, 8, 7, 2, 0, 6, 3, 4, 5] #goal_state = [1, 0, 7, 2, .pdf
  goal_state = [1, 8, 7, 2, 0, 6, 3, 4, 5] #goal_state = [1, 0, 7, 2, .pdf  goal_state = [1, 8, 7, 2, 0, 6, 3, 4, 5] #goal_state = [1, 0, 7, 2, .pdf
goal_state = [1, 8, 7, 2, 0, 6, 3, 4, 5] #goal_state = [1, 0, 7, 2, .pdf
ANJALIENTERPRISES1
 
In Java using Eclipse, Im suppose to write a class that encapsulat.pdf
In Java using Eclipse, Im suppose to write a class that encapsulat.pdfIn Java using Eclipse, Im suppose to write a class that encapsulat.pdf
In Java using Eclipse, Im suppose to write a class that encapsulat.pdf
anjandavid
 
Need to make a ReversiOthello Board game in JAVAThe board size ca.pdf
Need to make a ReversiOthello Board game in JAVAThe board size ca.pdfNeed to make a ReversiOthello Board game in JAVAThe board size ca.pdf
Need to make a ReversiOthello Board game in JAVAThe board size ca.pdf
flashfashioncasualwe
 
Here is the code for youimport java.util.Scanner; import java.u.pdf
Here is the code for youimport java.util.Scanner; import java.u.pdfHere is the code for youimport java.util.Scanner; import java.u.pdf
Here is the code for youimport java.util.Scanner; import java.u.pdf
anithareadymade
 
Lập trình Python cơ bản
Lập trình Python cơ bảnLập trình Python cơ bản
Lập trình Python cơ bản
Nguyen Thi Lan Phuong
 
Basics
BasicsBasics

Similar to 19012011102_Nayan Oza_Practical-7_AI.pdf (20)

The main class of the tictoe game looks like.public class Main {.pdf
The main class of the tictoe game looks like.public class Main {.pdfThe main class of the tictoe game looks like.public class Main {.pdf
The main class of the tictoe game looks like.public class Main {.pdf
 
Need help writing the code for a basic java tic tac toe game Tic.pdf
Need help writing the code for a basic java tic tac toe game Tic.pdfNeed help writing the code for a basic java tic tac toe game Tic.pdf
Need help writing the code for a basic java tic tac toe game Tic.pdf
 
Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語
 
AI CHALLENGE ADMIN
AI CHALLENGE ADMINAI CHALLENGE ADMIN
AI CHALLENGE ADMIN
 
The Ring programming language version 1.10 book - Part 71 of 212
The Ring programming language version 1.10 book - Part 71 of 212The Ring programming language version 1.10 book - Part 71 of 212
The Ring programming language version 1.10 book - Part 71 of 212
 
Python From Scratch (1).pdf
Python From Scratch  (1).pdfPython From Scratch  (1).pdf
Python From Scratch (1).pdf
 
calculator_new (1).pdf
calculator_new (1).pdfcalculator_new (1).pdf
calculator_new (1).pdf
 
Hello, I need some assistance in writing a java program THAT MUST US.pdf
Hello, I need some assistance in writing a java program THAT MUST US.pdfHello, I need some assistance in writing a java program THAT MUST US.pdf
Hello, I need some assistance in writing a java program THAT MUST US.pdf
 
p.pdf
p.pdfp.pdf
p.pdf
 
Intro to OTP in Elixir
Intro to OTP in ElixirIntro to OTP in Elixir
Intro to OTP in Elixir
 
Hello!This is Java assignment applet.Can someone help me writing.pdf
Hello!This is Java assignment applet.Can someone help me writing.pdfHello!This is Java assignment applet.Can someone help me writing.pdf
Hello!This is Java assignment applet.Can someone help me writing.pdf
 
#include stdio.h #include string.h #include stdlib.h #in.pdf
#include stdio.h #include string.h #include stdlib.h #in.pdf#include stdio.h #include string.h #include stdlib.h #in.pdf
#include stdio.h #include string.h #include stdlib.h #in.pdf
 
ObjectiveCreate a graphical game of minesweeper IN JAVA. The boar.pdf
ObjectiveCreate a graphical game of minesweeper IN JAVA. The boar.pdfObjectiveCreate a graphical game of minesweeper IN JAVA. The boar.pdf
ObjectiveCreate a graphical game of minesweeper IN JAVA. The boar.pdf
 
The Ring programming language version 1.3 book - Part 52 of 88
The Ring programming language version 1.3 book - Part 52 of 88The Ring programming language version 1.3 book - Part 52 of 88
The Ring programming language version 1.3 book - Part 52 of 88
 
goal_state = [1, 8, 7, 2, 0, 6, 3, 4, 5] #goal_state = [1, 0, 7, 2, .pdf
  goal_state = [1, 8, 7, 2, 0, 6, 3, 4, 5] #goal_state = [1, 0, 7, 2, .pdf  goal_state = [1, 8, 7, 2, 0, 6, 3, 4, 5] #goal_state = [1, 0, 7, 2, .pdf
goal_state = [1, 8, 7, 2, 0, 6, 3, 4, 5] #goal_state = [1, 0, 7, 2, .pdf
 
In Java using Eclipse, Im suppose to write a class that encapsulat.pdf
In Java using Eclipse, Im suppose to write a class that encapsulat.pdfIn Java using Eclipse, Im suppose to write a class that encapsulat.pdf
In Java using Eclipse, Im suppose to write a class that encapsulat.pdf
 
Need to make a ReversiOthello Board game in JAVAThe board size ca.pdf
Need to make a ReversiOthello Board game in JAVAThe board size ca.pdfNeed to make a ReversiOthello Board game in JAVAThe board size ca.pdf
Need to make a ReversiOthello Board game in JAVAThe board size ca.pdf
 
Here is the code for youimport java.util.Scanner; import java.u.pdf
Here is the code for youimport java.util.Scanner; import java.u.pdfHere is the code for youimport java.util.Scanner; import java.u.pdf
Here is the code for youimport java.util.Scanner; import java.u.pdf
 
Lập trình Python cơ bản
Lập trình Python cơ bảnLập trình Python cơ bản
Lập trình Python cơ bản
 
Basics
BasicsBasics
Basics
 

Recently uploaded

Barbie Movie Review - The Astras.pdfffff
Barbie Movie Review - The Astras.pdfffffBarbie Movie Review - The Astras.pdfffff
Barbie Movie Review - The Astras.pdfffff
theastras43
 
DIGIDEVTV A New area of OTT Distribution
DIGIDEVTV  A New area of OTT DistributionDIGIDEVTV  A New area of OTT Distribution
DIGIDEVTV A New area of OTT Distribution
joeqsm
 
Modern Radio Frequency Access Control Systems: The Key to Efficiency and Safety
Modern Radio Frequency Access Control Systems: The Key to Efficiency and SafetyModern Radio Frequency Access Control Systems: The Key to Efficiency and Safety
Modern Radio Frequency Access Control Systems: The Key to Efficiency and Safety
AITIX LLC
 
Authenticity in Motion Pictures: How Steve Greisen Retains Real Stories
Authenticity in Motion Pictures: How Steve Greisen Retains Real StoriesAuthenticity in Motion Pictures: How Steve Greisen Retains Real Stories
Authenticity in Motion Pictures: How Steve Greisen Retains Real Stories
Steve Greisen
 
The Evolution of the Leonardo DiCaprio Haircut: A Journey Through Style and C...
The Evolution of the Leonardo DiCaprio Haircut: A Journey Through Style and C...The Evolution of the Leonardo DiCaprio Haircut: A Journey Through Style and C...
The Evolution of the Leonardo DiCaprio Haircut: A Journey Through Style and C...
greendigital
 
I Know Dino Trivia: Part 3. Test your dino knowledge
I Know Dino Trivia: Part 3. Test your dino knowledgeI Know Dino Trivia: Part 3. Test your dino knowledge
I Know Dino Trivia: Part 3. Test your dino knowledge
Sabrina Ricci
 
From Swing Music to Big Band Fame_ 5 Iconic Artists.pptx
From Swing Music to Big Band Fame_ 5 Iconic Artists.pptxFrom Swing Music to Big Band Fame_ 5 Iconic Artists.pptx
From Swing Music to Big Band Fame_ 5 Iconic Artists.pptx
Swing Street Radio
 
_7 OTT App Builders to Support the Development of Your Video Applications_.pdf
_7 OTT App Builders to Support the Development of Your Video Applications_.pdf_7 OTT App Builders to Support the Development of Your Video Applications_.pdf
_7 OTT App Builders to Support the Development of Your Video Applications_.pdf
Mega P
 
定制(uow毕业证书)卧龙岗大学毕业证文凭学位证书原版一模一样
定制(uow毕业证书)卧龙岗大学毕业证文凭学位证书原版一模一样定制(uow毕业证书)卧龙岗大学毕业证文凭学位证书原版一模一样
定制(uow毕业证书)卧龙岗大学毕业证文凭学位证书原版一模一样
0md20cgg
 
The Ultimate Guide to Setting Up Eternal IPTV on Your Devices.docx
The Ultimate Guide to Setting Up Eternal IPTV on Your Devices.docxThe Ultimate Guide to Setting Up Eternal IPTV on Your Devices.docx
The Ultimate Guide to Setting Up Eternal IPTV on Your Devices.docx
Xtreame HDTV
 
Top IPTV UK Providers of A Comprehensive Review.pdf
Top IPTV UK Providers of A Comprehensive Review.pdfTop IPTV UK Providers of A Comprehensive Review.pdf
Top IPTV UK Providers of A Comprehensive Review.pdf
Xtreame HDTV
 
Everything You Need to Know About IPTV Ireland.pdf
Everything You Need to Know About IPTV Ireland.pdfEverything You Need to Know About IPTV Ireland.pdf
Everything You Need to Know About IPTV Ireland.pdf
Xtreame HDTV
 
高仿(nyu毕业证书)美国纽约大学毕业证文凭毕业证原版一模一样
高仿(nyu毕业证书)美国纽约大学毕业证文凭毕业证原版一模一样高仿(nyu毕业证书)美国纽约大学毕业证文凭毕业证原版一模一样
高仿(nyu毕业证书)美国纽约大学毕业证文凭毕业证原版一模一样
9u08k0x
 
Orpah Winfrey Dwayne Johnson: Titans of Influence and Inspiration
Orpah Winfrey Dwayne Johnson: Titans of Influence and InspirationOrpah Winfrey Dwayne Johnson: Titans of Influence and Inspiration
Orpah Winfrey Dwayne Johnson: Titans of Influence and Inspiration
greendigital
 
Unveiling Paul Haggis Shaping Cinema Through Diversity. .pdf
Unveiling Paul Haggis Shaping Cinema Through Diversity. .pdfUnveiling Paul Haggis Shaping Cinema Through Diversity. .pdf
Unveiling Paul Haggis Shaping Cinema Through Diversity. .pdf
kenid14983
 
Snoopy boards the big bow wow musical __
Snoopy boards the big bow wow musical __Snoopy boards the big bow wow musical __
Snoopy boards the big bow wow musical __
catcabrera
 
Divertidamente SLIDE muito lindo e criativo, pptx
Divertidamente SLIDE muito lindo e criativo, pptxDivertidamente SLIDE muito lindo e criativo, pptx
Divertidamente SLIDE muito lindo e criativo, pptx
lunaemel03
 
The Unbelievable Tale of Dwayne Johnson Kidnapping: A Riveting Saga
The Unbelievable Tale of Dwayne Johnson Kidnapping: A Riveting SagaThe Unbelievable Tale of Dwayne Johnson Kidnapping: A Riveting Saga
The Unbelievable Tale of Dwayne Johnson Kidnapping: A Riveting Saga
greendigital
 
Emcee Profile_ Subbu from Bangalore .pdf
Emcee Profile_ Subbu from Bangalore .pdfEmcee Profile_ Subbu from Bangalore .pdf
Emcee Profile_ Subbu from Bangalore .pdf
subran
 
240529_Teleprotection Global Market Report 2024.pdf
240529_Teleprotection Global Market Report 2024.pdf240529_Teleprotection Global Market Report 2024.pdf
240529_Teleprotection Global Market Report 2024.pdf
Madhura TBRC
 

Recently uploaded (20)

Barbie Movie Review - The Astras.pdfffff
Barbie Movie Review - The Astras.pdfffffBarbie Movie Review - The Astras.pdfffff
Barbie Movie Review - The Astras.pdfffff
 
DIGIDEVTV A New area of OTT Distribution
DIGIDEVTV  A New area of OTT DistributionDIGIDEVTV  A New area of OTT Distribution
DIGIDEVTV A New area of OTT Distribution
 
Modern Radio Frequency Access Control Systems: The Key to Efficiency and Safety
Modern Radio Frequency Access Control Systems: The Key to Efficiency and SafetyModern Radio Frequency Access Control Systems: The Key to Efficiency and Safety
Modern Radio Frequency Access Control Systems: The Key to Efficiency and Safety
 
Authenticity in Motion Pictures: How Steve Greisen Retains Real Stories
Authenticity in Motion Pictures: How Steve Greisen Retains Real StoriesAuthenticity in Motion Pictures: How Steve Greisen Retains Real Stories
Authenticity in Motion Pictures: How Steve Greisen Retains Real Stories
 
The Evolution of the Leonardo DiCaprio Haircut: A Journey Through Style and C...
The Evolution of the Leonardo DiCaprio Haircut: A Journey Through Style and C...The Evolution of the Leonardo DiCaprio Haircut: A Journey Through Style and C...
The Evolution of the Leonardo DiCaprio Haircut: A Journey Through Style and C...
 
I Know Dino Trivia: Part 3. Test your dino knowledge
I Know Dino Trivia: Part 3. Test your dino knowledgeI Know Dino Trivia: Part 3. Test your dino knowledge
I Know Dino Trivia: Part 3. Test your dino knowledge
 
From Swing Music to Big Band Fame_ 5 Iconic Artists.pptx
From Swing Music to Big Band Fame_ 5 Iconic Artists.pptxFrom Swing Music to Big Band Fame_ 5 Iconic Artists.pptx
From Swing Music to Big Band Fame_ 5 Iconic Artists.pptx
 
_7 OTT App Builders to Support the Development of Your Video Applications_.pdf
_7 OTT App Builders to Support the Development of Your Video Applications_.pdf_7 OTT App Builders to Support the Development of Your Video Applications_.pdf
_7 OTT App Builders to Support the Development of Your Video Applications_.pdf
 
定制(uow毕业证书)卧龙岗大学毕业证文凭学位证书原版一模一样
定制(uow毕业证书)卧龙岗大学毕业证文凭学位证书原版一模一样定制(uow毕业证书)卧龙岗大学毕业证文凭学位证书原版一模一样
定制(uow毕业证书)卧龙岗大学毕业证文凭学位证书原版一模一样
 
The Ultimate Guide to Setting Up Eternal IPTV on Your Devices.docx
The Ultimate Guide to Setting Up Eternal IPTV on Your Devices.docxThe Ultimate Guide to Setting Up Eternal IPTV on Your Devices.docx
The Ultimate Guide to Setting Up Eternal IPTV on Your Devices.docx
 
Top IPTV UK Providers of A Comprehensive Review.pdf
Top IPTV UK Providers of A Comprehensive Review.pdfTop IPTV UK Providers of A Comprehensive Review.pdf
Top IPTV UK Providers of A Comprehensive Review.pdf
 
Everything You Need to Know About IPTV Ireland.pdf
Everything You Need to Know About IPTV Ireland.pdfEverything You Need to Know About IPTV Ireland.pdf
Everything You Need to Know About IPTV Ireland.pdf
 
高仿(nyu毕业证书)美国纽约大学毕业证文凭毕业证原版一模一样
高仿(nyu毕业证书)美国纽约大学毕业证文凭毕业证原版一模一样高仿(nyu毕业证书)美国纽约大学毕业证文凭毕业证原版一模一样
高仿(nyu毕业证书)美国纽约大学毕业证文凭毕业证原版一模一样
 
Orpah Winfrey Dwayne Johnson: Titans of Influence and Inspiration
Orpah Winfrey Dwayne Johnson: Titans of Influence and InspirationOrpah Winfrey Dwayne Johnson: Titans of Influence and Inspiration
Orpah Winfrey Dwayne Johnson: Titans of Influence and Inspiration
 
Unveiling Paul Haggis Shaping Cinema Through Diversity. .pdf
Unveiling Paul Haggis Shaping Cinema Through Diversity. .pdfUnveiling Paul Haggis Shaping Cinema Through Diversity. .pdf
Unveiling Paul Haggis Shaping Cinema Through Diversity. .pdf
 
Snoopy boards the big bow wow musical __
Snoopy boards the big bow wow musical __Snoopy boards the big bow wow musical __
Snoopy boards the big bow wow musical __
 
Divertidamente SLIDE muito lindo e criativo, pptx
Divertidamente SLIDE muito lindo e criativo, pptxDivertidamente SLIDE muito lindo e criativo, pptx
Divertidamente SLIDE muito lindo e criativo, pptx
 
The Unbelievable Tale of Dwayne Johnson Kidnapping: A Riveting Saga
The Unbelievable Tale of Dwayne Johnson Kidnapping: A Riveting SagaThe Unbelievable Tale of Dwayne Johnson Kidnapping: A Riveting Saga
The Unbelievable Tale of Dwayne Johnson Kidnapping: A Riveting Saga
 
Emcee Profile_ Subbu from Bangalore .pdf
Emcee Profile_ Subbu from Bangalore .pdfEmcee Profile_ Subbu from Bangalore .pdf
Emcee Profile_ Subbu from Bangalore .pdf
 
240529_Teleprotection Global Market Report 2024.pdf
240529_Teleprotection Global Market Report 2024.pdf240529_Teleprotection Global Market Report 2024.pdf
240529_Teleprotection Global Market Report 2024.pdf
 

19012011102_Nayan Oza_Practical-7_AI.pdf

  • 1. Practical-7 1 | P a g e Name:- Nayan Oza Enrollment No :- 19012011102 AIM:- Write a program to create tic-tac-toe game using minimax algorithm. Consider following steps to create a program in python: 1. Create class StateNode with its proper members (getScoreValue(), isValidMove(), isGameOver(), drawboard(), getEmptyCells(), setMove(), isWin(), etc.) 2. Create class ticTacToe with its proper members (minimax(), computerMove(), playerMove(), execution(), etc.) 3. Output should be according shown in Output image 4. Use only math, random, matplotlib libraries in python Input :- from math import inf as infinity from random import choice import platform import time print("19012011102_Nayan Oza") from os import system HUMAN = -1 COMP = +1 board = [ [0, 0, 0], [0, 0, 0], [0, 0, 0],] def evaluate(state): if wins(state, COMP):
  • 2. Practical-7 2 | P a g e Name:- Nayan Oza Enrollment No :- 19012011102 score = +1 elif wins(state, HUMAN): score = -1 else: score = 0 return score def wins(state, player): win_state = [ [state[0][0], state[0][1], state[0][2]], [state[1][0], state[1][1], state[1][2]], [state[2][0], state[2][1], state[2][2]], [state[0][0], state[1][0], state[2][0]], [state[0][1], state[1][1], state[2][1]], [state[0][2], state[1][2], state[2][2]], [state[0][0], state[1][1], state[2][2]], [state[2][0], state[1][1], state[0][2]], ] if [player, player, player] in win_state: return True else: return False def game_over(state): return wins(state, HUMAN) or wins(state, COMP) def empty_cells(state): cells = [] for x, row in enumerate(state):
  • 3. Practical-7 3 | P a g e Name:- Nayan Oza Enrollment No :- 19012011102 for y, cell in enumerate(row): if cell == 0: cells.append([x, y]) return cells def valid_move(x, y): if [x, y] in empty_cells(board): return True else: return False def set_move(x, y, player): if valid_move(x, y): board[x][y] = player return True else: return False def minimax(state, depth, player): if player == COMP: best = [-1, -1, -infinity] else: best = [-1, -1, +infinity] if depth == 0 or game_over(state): score = evaluate(state) return [-1, -1, score] for cell in empty_cells(state): x, y = cell[0], cell[1] state[x][y] = player score = minimax(state, depth - 1, -player)
  • 4. Practical-7 4 | P a g e Name:- Nayan Oza Enrollment No :- 19012011102 state[x][y] = 0 score[0], score[1] = x, y if player == COMP: if score[2] > best[2]: best = score else: if score[2] < best[2]: best = score return best def clean(): os_name = platform.system().lower() if 'windows' in os_name: system('cls') else: system('clear') def render(state, c_choice, h_choice): chars = { -1: h_choice, +1: c_choice, 0: ' ' } str_line = '---------------' print('n' + str_line) for row in state: for cell in row: symbol = chars[cell] print(f'| {symbol} |', end='')
  • 5. Practical-7 5 | P a g e Name:- Nayan Oza Enrollment No :- 19012011102 print('n' + str_line) def ai_turn(c_choice, h_choice): depth = len(empty_cells(board)) if depth == 0 or game_over(board): return clean() print(f'Computer turn [{c_choice}]') render(board, c_choice, h_choice) if depth == 9: x = choice([0, 1, 2]) y = choice([0, 1, 2]) else: move = minimax(board, depth, COMP) x, y = move[0], move[1] set_move(x, y, COMP) time.sleep(1) def human_turn(c_choice, h_choice): depth = len(empty_cells(board)) if depth == 0 or game_over(board): return move = -1 moves = { 1: [0, 0], 2: [0, 1], 3: [0, 2],
  • 6. Practical-7 6 | P a g e Name:- Nayan Oza Enrollment No :- 19012011102 4: [1, 0], 5: [1, 1], 6: [1, 2], 7: [2, 0], 8: [2, 1], 9: [2, 2], } clean() print(f'Human turn [{h_choice}]') render(board, c_choice, h_choice) while move < 1 or move > 9: try: move = int(input('Use numpad (1..9): ')) coord = moves[move] can_move = set_move(coord[0], coord[1], HUMAN) if not can_move: print('Bad move') move = -1 except (EOFError, KeyboardInterrupt): print('Close') exit() except (KeyError, ValueError): print('Bad choice') def main(): clean() h_choice = '' c_choice = '' first = '' while h_choice != 'O' and h_choice != 'X': try: print('')
  • 7. Practical-7 7 | P a g e Name:- Nayan Oza Enrollment No :- 19012011102 h_choice = input('Choose X or OnChosen: ').upper() except (EOFError, KeyboardInterrupt): print('Close') exit() except (KeyError, ValueError): print('Bad choice') if h_choice == 'X': c_choice = 'O' else: c_choice = 'X' clean() while first != 'Y' and first != 'N': try: first = input('First to start?[y/n]: ').upper() except (EOFError, KeyboardInterrupt): print('Close') exit() except (KeyError, ValueError): print('Bad choice') while len(empty_cells(board)) > 0 and not game_over(board): if first == 'N': ai_turn(c_choice, h_choice) first = '' human_turn(c_choice, h_choice) ai_turn(c_choice, h_choice) if wins(board, HUMAN):
  • 8. Practical-7 8 | P a g e Name:- Nayan Oza Enrollment No :- 19012011102 clean() print(f'Human turn [{h_choice}]') render(board, c_choice, h_choice) print('YOU WIN!') elif wins(board, COMP): clean() print(f'Computer turn [{c_choice}]') render(board, c_choice, h_choice) print('YOU LOSE!') else: clean() render(board, c_choice, h_choice) print('DRAW!') #exit() if __name__ == '__main__': main() Output :-
  • 9. Practical-7 9 | P a g e Name:- Nayan Oza Enrollment No :- 19012011102
  • 10. Practical-7 10 | P a g e Name:- Nayan Oza Enrollment No :- 19012011102