SlideShare a Scribd company logo
1 of 10
Download to read offline
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

[226]NAVER 광고 deep click prediction: 모델링부터 서빙까지
[226]NAVER 광고 deep click prediction: 모델링부터 서빙까지[226]NAVER 광고 deep click prediction: 모델링부터 서빙까지
[226]NAVER 광고 deep click prediction: 모델링부터 서빙까지NAVER D2
 
Splunk App for Stream
Splunk App for StreamSplunk App for Stream
Splunk App for StreamSplunk
 
Recon with Nmap
Recon with Nmap Recon with Nmap
Recon with Nmap OWASP Delhi
 
Integration of neutron, nova and designate how to use it and how to configur...
Integration of neutron, nova and designate  how to use it and how to configur...Integration of neutron, nova and designate  how to use it and how to configur...
Integration of neutron, nova and designate how to use it and how to configur...Miguel Lavalle
 
NFV : Virtual Network Function Architecture
NFV : Virtual Network Function ArchitectureNFV : Virtual Network Function Architecture
NFV : Virtual Network Function Architecturesidneel
 
Choisir entre une API RPC, SOAP, REST, GraphQL? 
Et si le problème était ai...
Choisir entre une API  RPC, SOAP, REST, GraphQL?  
Et si le problème était ai...Choisir entre une API  RPC, SOAP, REST, GraphQL?  
Et si le problème était ai...
Choisir entre une API RPC, SOAP, REST, GraphQL? 
Et si le problème était ai...François-Guillaume Ribreau
 
BlackDuck Suite
BlackDuck SuiteBlackDuck Suite
BlackDuck Suitejeff cheng
 
網路七層架構
網路七層架構網路七層架構
網路七層架構玉俐 鄭
 
오픈스택 멀티노드 설치 후기
오픈스택 멀티노드 설치 후기오픈스택 멀티노드 설치 후기
오픈스택 멀티노드 설치 후기영우 김
 
H/W 규모산정기준
H/W 규모산정기준H/W 규모산정기준
H/W 규모산정기준sam Cyberspace
 
[오픈테크넷서밋2022] 국내 PaaS(Kubernetes) Best Practice 및 DevOps 환경 구축 사례.pdf
[오픈테크넷서밋2022] 국내 PaaS(Kubernetes) Best Practice 및 DevOps 환경 구축 사례.pdf[오픈테크넷서밋2022] 국내 PaaS(Kubernetes) Best Practice 및 DevOps 환경 구축 사례.pdf
[오픈테크넷서밋2022] 국내 PaaS(Kubernetes) Best Practice 및 DevOps 환경 구축 사례.pdfOpen Source Consulting
 
Cloudstack autoscaling
Cloudstack autoscalingCloudstack autoscaling
Cloudstack autoscalingShapeBlue
 
[오픈소스컨설팅] 스카우터 사용자 가이드 2020
[오픈소스컨설팅] 스카우터 사용자 가이드 2020[오픈소스컨설팅] 스카우터 사용자 가이드 2020
[오픈소스컨설팅] 스카우터 사용자 가이드 2020Ji-Woong Choi
 
網頁安全 Web security 入門 @ Study-Area
網頁安全 Web security 入門 @ Study-Area網頁安全 Web security 入門 @ Study-Area
網頁安全 Web security 入門 @ Study-AreaOrange Tsai
 
モナドをつくろう
モナドをつくろうモナドをつくろう
モナドをつくろうdico_leque
 
Reproducible Computational Pipelines with Docker and Nextflow
Reproducible Computational Pipelines with Docker and NextflowReproducible Computational Pipelines with Docker and Nextflow
Reproducible Computational Pipelines with Docker and Nextflowinside-BigData.com
 
SplunkLive 2011 Beginners Session
SplunkLive 2011 Beginners SessionSplunkLive 2011 Beginners Session
SplunkLive 2011 Beginners SessionSplunk
 

What's hot (20)

[226]NAVER 광고 deep click prediction: 모델링부터 서빙까지
[226]NAVER 광고 deep click prediction: 모델링부터 서빙까지[226]NAVER 광고 deep click prediction: 모델링부터 서빙까지
[226]NAVER 광고 deep click prediction: 모델링부터 서빙까지
 
Splunk App for Stream
Splunk App for StreamSplunk App for Stream
Splunk App for Stream
 
Recon with Nmap
Recon with Nmap Recon with Nmap
Recon with Nmap
 
Integration of neutron, nova and designate how to use it and how to configur...
Integration of neutron, nova and designate  how to use it and how to configur...Integration of neutron, nova and designate  how to use it and how to configur...
Integration of neutron, nova and designate how to use it and how to configur...
 
NFV : Virtual Network Function Architecture
NFV : Virtual Network Function ArchitectureNFV : Virtual Network Function Architecture
NFV : Virtual Network Function Architecture
 
Choisir entre une API RPC, SOAP, REST, GraphQL? 
Et si le problème était ai...
Choisir entre une API  RPC, SOAP, REST, GraphQL?  
Et si le problème était ai...Choisir entre une API  RPC, SOAP, REST, GraphQL?  
Et si le problème était ai...
Choisir entre une API RPC, SOAP, REST, GraphQL? 
Et si le problème était ai...
 
BlackDuck Suite
BlackDuck SuiteBlackDuck Suite
BlackDuck Suite
 
網路七層架構
網路七層架構網路七層架構
網路七層架構
 
오픈스택 멀티노드 설치 후기
오픈스택 멀티노드 설치 후기오픈스택 멀티노드 설치 후기
오픈스택 멀티노드 설치 후기
 
Understanding NMAP
Understanding NMAPUnderstanding NMAP
Understanding NMAP
 
Splunk overview
Splunk overviewSplunk overview
Splunk overview
 
H/W 규모산정기준
H/W 규모산정기준H/W 규모산정기준
H/W 규모산정기준
 
[오픈테크넷서밋2022] 국내 PaaS(Kubernetes) Best Practice 및 DevOps 환경 구축 사례.pdf
[오픈테크넷서밋2022] 국내 PaaS(Kubernetes) Best Practice 및 DevOps 환경 구축 사례.pdf[오픈테크넷서밋2022] 국내 PaaS(Kubernetes) Best Practice 및 DevOps 환경 구축 사례.pdf
[오픈테크넷서밋2022] 국내 PaaS(Kubernetes) Best Practice 및 DevOps 환경 구축 사례.pdf
 
Cloudstack autoscaling
Cloudstack autoscalingCloudstack autoscaling
Cloudstack autoscaling
 
[오픈소스컨설팅] 스카우터 사용자 가이드 2020
[오픈소스컨설팅] 스카우터 사용자 가이드 2020[오픈소스컨설팅] 스카우터 사용자 가이드 2020
[오픈소스컨설팅] 스카우터 사용자 가이드 2020
 
網頁安全 Web security 入門 @ Study-Area
網頁安全 Web security 入門 @ Study-Area網頁安全 Web security 入門 @ Study-Area
網頁安全 Web security 入門 @ Study-Area
 
モナドをつくろう
モナドをつくろうモナドをつくろう
モナドをつくろう
 
Uncomplicated Nomad
Uncomplicated NomadUncomplicated Nomad
Uncomplicated Nomad
 
Reproducible Computational Pipelines with Docker and Nextflow
Reproducible Computational Pipelines with Docker and NextflowReproducible Computational Pipelines with Docker and Nextflow
Reproducible Computational Pipelines with Docker and Nextflow
 
SplunkLive 2011 Beginners Session
SplunkLive 2011 Beginners SessionSplunkLive 2011 Beginners Session
SplunkLive 2011 Beginners Session
 

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 {.pdfasif1401
 
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.pdfhainesburchett26321
 
Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語ikdysfm
 
AI CHALLENGE ADMIN
AI CHALLENGE ADMINAI CHALLENGE ADMIN
AI CHALLENGE ADMINAnkit 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 212Mahmoud Samir Fayed
 
calculator_new (1).pdf
calculator_new (1).pdfcalculator_new (1).pdf
calculator_new (1).pdfni30ji
 
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.pdfFashionColZone
 
Intro to OTP in Elixir
Intro to OTP in ElixirIntro to OTP in Elixir
Intro to OTP in ElixirJesse 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.pdfjyothimuppasani1
 
#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.pdfsinghanubhav1234
 
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.pdfrajkumarm401
 
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 88Mahmoud 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, .pdfANJALIENTERPRISES1
 
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.pdfanjandavid
 
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.pdfflashfashioncasualwe
 
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.pdfanithareadymade
 

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

Call Girls Somajiguda Sarani 7001305949 all area service COD available Any Time
Call Girls Somajiguda Sarani 7001305949 all area service COD available Any TimeCall Girls Somajiguda Sarani 7001305949 all area service COD available Any Time
Call Girls Somajiguda Sarani 7001305949 all area service COD available Any Timedelhimodelshub1
 
Book Call Girls in Panchpota - 8250192130 | 24x7 Service Available Near Me
Book Call Girls in Panchpota - 8250192130 | 24x7 Service Available Near MeBook Call Girls in Panchpota - 8250192130 | 24x7 Service Available Near Me
Book Call Girls in Panchpota - 8250192130 | 24x7 Service Available Near Meanamikaraghav4
 
Call Girls in Barasat | 7001035870 At Low Cost Cash Payment Booking
Call Girls in Barasat | 7001035870 At Low Cost Cash Payment BookingCall Girls in Barasat | 7001035870 At Low Cost Cash Payment Booking
Call Girls in Barasat | 7001035870 At Low Cost Cash Payment Bookingnoor ahmed
 
Call Girl Nashik Saloni 7001305949 Independent Escort Service Nashik
Call Girl Nashik Saloni 7001305949 Independent Escort Service NashikCall Girl Nashik Saloni 7001305949 Independent Escort Service Nashik
Call Girl Nashik Saloni 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
Call Girls Nashik Gayatri 7001305949 Independent Escort Service Nashik
Call Girls Nashik Gayatri 7001305949 Independent Escort Service NashikCall Girls Nashik Gayatri 7001305949 Independent Escort Service Nashik
Call Girls Nashik Gayatri 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
Fun Call Girls In Goa 7028418221 Escort Service In Morjim Beach Call Girl
Fun Call Girls In Goa 7028418221 Escort Service In Morjim Beach Call GirlFun Call Girls In Goa 7028418221 Escort Service In Morjim Beach Call Girl
Fun Call Girls In Goa 7028418221 Escort Service In Morjim Beach Call GirlApsara Of India
 
VIP Call Girls In Goa 7028418221 Call Girls In Baga Beach Escorts Service
VIP Call Girls In Goa 7028418221 Call Girls In Baga Beach Escorts ServiceVIP Call Girls In Goa 7028418221 Call Girls In Baga Beach Escorts Service
VIP Call Girls In Goa 7028418221 Call Girls In Baga Beach Escorts ServiceApsara Of India
 
Private Call Girls Bally - 8250192130 | 24x7 Service Available Near Me
Private Call Girls Bally - 8250192130 | 24x7 Service Available Near MePrivate Call Girls Bally - 8250192130 | 24x7 Service Available Near Me
Private Call Girls Bally - 8250192130 | 24x7 Service Available Near MeRiya Pathan
 
VIP Call Girls in Gulbarga Aarohi 8250192130 Independent Escort Service Gulbarga
VIP Call Girls in Gulbarga Aarohi 8250192130 Independent Escort Service GulbargaVIP Call Girls in Gulbarga Aarohi 8250192130 Independent Escort Service Gulbarga
VIP Call Girls in Gulbarga Aarohi 8250192130 Independent Escort Service GulbargaRiya Pathan
 
Russian Call Girl South End Park - Call 8250192130 Rs-3500 with A/C Room Cash...
Russian Call Girl South End Park - Call 8250192130 Rs-3500 with A/C Room Cash...Russian Call Girl South End Park - Call 8250192130 Rs-3500 with A/C Room Cash...
Russian Call Girl South End Park - Call 8250192130 Rs-3500 with A/C Room Cash...anamikaraghav4
 
VIP Call Girl Kolhapur Aashi 8250192130 Independent Escort Service Kolhapur
VIP Call Girl Kolhapur Aashi 8250192130 Independent Escort Service KolhapurVIP Call Girl Kolhapur Aashi 8250192130 Independent Escort Service Kolhapur
VIP Call Girl Kolhapur Aashi 8250192130 Independent Escort Service KolhapurRiya Pathan
 
Call Girls In Karnal O8860008073 Sector 6 7 8 9 Karnal Escorts
Call Girls In Karnal O8860008073 Sector 6 7 8 9 Karnal EscortsCall Girls In Karnal O8860008073 Sector 6 7 8 9 Karnal Escorts
Call Girls In Karnal O8860008073 Sector 6 7 8 9 Karnal EscortsApsara Of India
 
Hot Call Girls In Goa 7028418221 Call Girls In Vagator Beach EsCoRtS
Hot Call Girls In Goa 7028418221 Call Girls In Vagator Beach EsCoRtSHot Call Girls In Goa 7028418221 Call Girls In Vagator Beach EsCoRtS
Hot Call Girls In Goa 7028418221 Call Girls In Vagator Beach EsCoRtSApsara Of India
 
VIP Call Girls Darjeeling Aaradhya 8250192130 Independent Escort Service Darj...
VIP Call Girls Darjeeling Aaradhya 8250192130 Independent Escort Service Darj...VIP Call Girls Darjeeling Aaradhya 8250192130 Independent Escort Service Darj...
VIP Call Girls Darjeeling Aaradhya 8250192130 Independent Escort Service Darj...Neha Kaur
 
Call Girl Nagpur Roshni Call 7001035870 Meet With Nagpur Escorts
Call Girl Nagpur Roshni Call 7001035870 Meet With Nagpur EscortsCall Girl Nagpur Roshni Call 7001035870 Meet With Nagpur Escorts
Call Girl Nagpur Roshni Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
VIP Call Girls Nagpur Megha Call 7001035870 Meet With Nagpur Escorts
VIP Call Girls Nagpur Megha Call 7001035870 Meet With Nagpur EscortsVIP Call Girls Nagpur Megha Call 7001035870 Meet With Nagpur Escorts
VIP Call Girls Nagpur Megha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
GV'S 24 CLUB & BAR CONTACT 09602870969 CALL GIRLS IN UDAIPUR ESCORT SERVICE
GV'S 24 CLUB & BAR CONTACT 09602870969 CALL GIRLS IN UDAIPUR ESCORT SERVICEGV'S 24 CLUB & BAR CONTACT 09602870969 CALL GIRLS IN UDAIPUR ESCORT SERVICE
GV'S 24 CLUB & BAR CONTACT 09602870969 CALL GIRLS IN UDAIPUR ESCORT SERVICEApsara Of India
 
fmovies-Movies hold a special place in the hearts
fmovies-Movies hold a special place in the heartsfmovies-Movies hold a special place in the hearts
fmovies-Movies hold a special place in the heartsa18205752
 
Kolkata Call Girls Service +918240919228 - Kolkatanightgirls.com
Kolkata Call Girls Service +918240919228 - Kolkatanightgirls.comKolkata Call Girls Service +918240919228 - Kolkatanightgirls.com
Kolkata Call Girls Service +918240919228 - Kolkatanightgirls.comKolkata Call Girls
 
VIP Call Girls Asansol Ananya 8250192130 Independent Escort Service Asansol
VIP Call Girls Asansol Ananya 8250192130 Independent Escort Service AsansolVIP Call Girls Asansol Ananya 8250192130 Independent Escort Service Asansol
VIP Call Girls Asansol Ananya 8250192130 Independent Escort Service AsansolRiya Pathan
 

Recently uploaded (20)

Call Girls Somajiguda Sarani 7001305949 all area service COD available Any Time
Call Girls Somajiguda Sarani 7001305949 all area service COD available Any TimeCall Girls Somajiguda Sarani 7001305949 all area service COD available Any Time
Call Girls Somajiguda Sarani 7001305949 all area service COD available Any Time
 
Book Call Girls in Panchpota - 8250192130 | 24x7 Service Available Near Me
Book Call Girls in Panchpota - 8250192130 | 24x7 Service Available Near MeBook Call Girls in Panchpota - 8250192130 | 24x7 Service Available Near Me
Book Call Girls in Panchpota - 8250192130 | 24x7 Service Available Near Me
 
Call Girls in Barasat | 7001035870 At Low Cost Cash Payment Booking
Call Girls in Barasat | 7001035870 At Low Cost Cash Payment BookingCall Girls in Barasat | 7001035870 At Low Cost Cash Payment Booking
Call Girls in Barasat | 7001035870 At Low Cost Cash Payment Booking
 
Call Girl Nashik Saloni 7001305949 Independent Escort Service Nashik
Call Girl Nashik Saloni 7001305949 Independent Escort Service NashikCall Girl Nashik Saloni 7001305949 Independent Escort Service Nashik
Call Girl Nashik Saloni 7001305949 Independent Escort Service Nashik
 
Call Girls Nashik Gayatri 7001305949 Independent Escort Service Nashik
Call Girls Nashik Gayatri 7001305949 Independent Escort Service NashikCall Girls Nashik Gayatri 7001305949 Independent Escort Service Nashik
Call Girls Nashik Gayatri 7001305949 Independent Escort Service Nashik
 
Fun Call Girls In Goa 7028418221 Escort Service In Morjim Beach Call Girl
Fun Call Girls In Goa 7028418221 Escort Service In Morjim Beach Call GirlFun Call Girls In Goa 7028418221 Escort Service In Morjim Beach Call Girl
Fun Call Girls In Goa 7028418221 Escort Service In Morjim Beach Call Girl
 
VIP Call Girls In Goa 7028418221 Call Girls In Baga Beach Escorts Service
VIP Call Girls In Goa 7028418221 Call Girls In Baga Beach Escorts ServiceVIP Call Girls In Goa 7028418221 Call Girls In Baga Beach Escorts Service
VIP Call Girls In Goa 7028418221 Call Girls In Baga Beach Escorts Service
 
Private Call Girls Bally - 8250192130 | 24x7 Service Available Near Me
Private Call Girls Bally - 8250192130 | 24x7 Service Available Near MePrivate Call Girls Bally - 8250192130 | 24x7 Service Available Near Me
Private Call Girls Bally - 8250192130 | 24x7 Service Available Near Me
 
VIP Call Girls in Gulbarga Aarohi 8250192130 Independent Escort Service Gulbarga
VIP Call Girls in Gulbarga Aarohi 8250192130 Independent Escort Service GulbargaVIP Call Girls in Gulbarga Aarohi 8250192130 Independent Escort Service Gulbarga
VIP Call Girls in Gulbarga Aarohi 8250192130 Independent Escort Service Gulbarga
 
Russian Call Girl South End Park - Call 8250192130 Rs-3500 with A/C Room Cash...
Russian Call Girl South End Park - Call 8250192130 Rs-3500 with A/C Room Cash...Russian Call Girl South End Park - Call 8250192130 Rs-3500 with A/C Room Cash...
Russian Call Girl South End Park - Call 8250192130 Rs-3500 with A/C Room Cash...
 
VIP Call Girl Kolhapur Aashi 8250192130 Independent Escort Service Kolhapur
VIP Call Girl Kolhapur Aashi 8250192130 Independent Escort Service KolhapurVIP Call Girl Kolhapur Aashi 8250192130 Independent Escort Service Kolhapur
VIP Call Girl Kolhapur Aashi 8250192130 Independent Escort Service Kolhapur
 
Call Girls In Karnal O8860008073 Sector 6 7 8 9 Karnal Escorts
Call Girls In Karnal O8860008073 Sector 6 7 8 9 Karnal EscortsCall Girls In Karnal O8860008073 Sector 6 7 8 9 Karnal Escorts
Call Girls In Karnal O8860008073 Sector 6 7 8 9 Karnal Escorts
 
Hot Call Girls In Goa 7028418221 Call Girls In Vagator Beach EsCoRtS
Hot Call Girls In Goa 7028418221 Call Girls In Vagator Beach EsCoRtSHot Call Girls In Goa 7028418221 Call Girls In Vagator Beach EsCoRtS
Hot Call Girls In Goa 7028418221 Call Girls In Vagator Beach EsCoRtS
 
VIP Call Girls Darjeeling Aaradhya 8250192130 Independent Escort Service Darj...
VIP Call Girls Darjeeling Aaradhya 8250192130 Independent Escort Service Darj...VIP Call Girls Darjeeling Aaradhya 8250192130 Independent Escort Service Darj...
VIP Call Girls Darjeeling Aaradhya 8250192130 Independent Escort Service Darj...
 
Call Girl Nagpur Roshni Call 7001035870 Meet With Nagpur Escorts
Call Girl Nagpur Roshni Call 7001035870 Meet With Nagpur EscortsCall Girl Nagpur Roshni Call 7001035870 Meet With Nagpur Escorts
Call Girl Nagpur Roshni Call 7001035870 Meet With Nagpur Escorts
 
VIP Call Girls Nagpur Megha Call 7001035870 Meet With Nagpur Escorts
VIP Call Girls Nagpur Megha Call 7001035870 Meet With Nagpur EscortsVIP Call Girls Nagpur Megha Call 7001035870 Meet With Nagpur Escorts
VIP Call Girls Nagpur Megha Call 7001035870 Meet With Nagpur Escorts
 
GV'S 24 CLUB & BAR CONTACT 09602870969 CALL GIRLS IN UDAIPUR ESCORT SERVICE
GV'S 24 CLUB & BAR CONTACT 09602870969 CALL GIRLS IN UDAIPUR ESCORT SERVICEGV'S 24 CLUB & BAR CONTACT 09602870969 CALL GIRLS IN UDAIPUR ESCORT SERVICE
GV'S 24 CLUB & BAR CONTACT 09602870969 CALL GIRLS IN UDAIPUR ESCORT SERVICE
 
fmovies-Movies hold a special place in the hearts
fmovies-Movies hold a special place in the heartsfmovies-Movies hold a special place in the hearts
fmovies-Movies hold a special place in the hearts
 
Kolkata Call Girls Service +918240919228 - Kolkatanightgirls.com
Kolkata Call Girls Service +918240919228 - Kolkatanightgirls.comKolkata Call Girls Service +918240919228 - Kolkatanightgirls.com
Kolkata Call Girls Service +918240919228 - Kolkatanightgirls.com
 
VIP Call Girls Asansol Ananya 8250192130 Independent Escort Service Asansol
VIP Call Girls Asansol Ananya 8250192130 Independent Escort Service AsansolVIP Call Girls Asansol Ananya 8250192130 Independent Escort Service Asansol
VIP Call Girls Asansol Ananya 8250192130 Independent Escort Service Asansol
 

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