SlideShare une entreprise Scribd logo
1  sur  5
Télécharger pour lire hors ligne
look at the following module.
import sys
sys.path.append('aima-python')
from search import *
from games import *
import math
def k_in_row(k, board, move, player, delta_x_y):
'''Adapted from AIMA code in games.py
Purpose:
Function to help determine a winner in k-in-a-row
type games like TicTacToe, Connect4, Gomoku
Parameters:
k: int number in a row necessary to win
board: dictionary with (row,col) keys, 'X' or 'O' values
move: where to search from
player: str 'X' or 'O'
delta_x_y: which direction to search in
Return Value:
True if there is a line through move on board for player.
'''
(delta_x, delta_y) = delta_x_y
x, y = move
n = 0 # n is number of moves in row
while board.get((x, y)) == player:
n += 1
x, y = x + delta_x, y + delta_y
x, y = move
while board.get((x, y)) == player:
n += 1
x, y = x - delta_x, y - delta_y
n -= 1 # Because we counted move itself twice
return n >= k
def is_winner(k, h, v, board, player):
'''Adapted from AIMA code in games.py
Purpose:
Determine if given player wins in a k-in-a-row type game.
Parameters:
k: int number in a row necessary to win
h: width (horizontal) of board
v: height (vertical) of board
board: dictionary with (row,col) keys, 'X' or 'O' values
player: str 'X' or 'O'
Return Value:
True if player wins, False otherwise
'''
for row in range(1, h+1):
for col in range(1, v+1):
if (k_in_row(k, board, (row,col), player, (0,1)) or
k_in_row(k, board, (row,col), player, (1,0)) or
k_in_row(k, board, (row,col), player, (1,-1)) or
k_in_row(k, board, (row,col), player, (1,1))):
return True
return False
def connect4_eval_bad(state):
'''Example of a bad evaluation function: It gives a high
score to any state whose board has a lot of Xs in the 7th row
(that is, the bottom row)
This is a terrible plan, but at least you can see it in action,
as the agent will prefer to put its pieces on across the bottom row
if at all possible.
(Change it to row 2 or 3 if you want to see different behavior)
'''
if is_winner(4, 7, 6, state.board, 'X'):
return 1
if is_winner(4,7,6, state.board, 'O'):
return -1
ev = 0
for col in range(1,7):
if (7,col) in state.board and state.board[(7,col)] == 'X':
ev += 1
# Divide by 42 to make sure that ev is less than 1
# It is important to make sure that your evaluation is never better or worse than
# actual win/loss utility (represented by 1/-1)
return ev / 42
def connect4_eval(state):
'''Your Connect 4 evaluation function
Hopefully better than mine!
'''
return 0
def ab_cutoff_player(game, state):
return alpha_beta_cutoff_search(state, game, d=2, eval_fn=connect4_eval_bad)
class HW3:
def __init__(self):
pass
def ttt_game(self):
tt = TicTacToe()
tt.play_game(alpha_beta_player,query_player)
def c4_game(self):
c4 = ConnectFour()
c4.play_game(ab_cutoff_player,query_player)
def problem_1d():
# write your code for problem 1d here
pass
def problem_2b():
# write your code for problem 2b here
pass
def main():
hw3 = HW3()
# An example for you to follow to get you started on Games
print('Playing Tic-Tac-Toe...')
print('======================')
hw3.ttt_game()
## uncomment the following lines to play connect 4
#print('Playing Connect 4...')
#print('====================')
#hw3.c4_game()
if __name__ == '__main__':
main()
I need you to help me with the following questions and also return me the whole module filled
with problem_1d and problem_2b functions and also with a connect4_eval function that isn't
terrible. Here are the questions. please help me answer all of them.!
Problem 1. (30 points) For problem 1, you will put answers in your writeup for a - c. Also make
alterations to the given python module.
a. Run the ttt game code. You will be prompted to play tic-tac-toe against a minimax agent.
Common wisdom suggests that the best first move is the center square. The agent doesnt begin
by playing in the center square. Why do you think the agent plays where it does instead of the
center?
b. Run c4 game. You will be prompted to play connect-4 against an alpha-beta with cutoff agent
that is using a terrible evaluation function. See if you can defeat the agent in a few games. What
is your best plan to defeat it? Why?
c. In the function connect4 eval, write a new evaluation function that isnt terrible. Using this
function, write code that will play an alpha-beta agent with depth cutoff 4 using your evaluation
function against a random agent. Describe your evaluation function in your writeup and explain
why you think it should do well.
d. In the function problem 1d, run 20 games of a random agent versus your alpha-betacutoff
agent, with each agent playing 10 times as X and 10 times as O. Have the function return its
results as a tuple containing wins as X as the first item, and wins as O as the second item. So if
your agent wins every single game, it will return (10,10).
For problem 2, you will put answers in your writeup for a. Also make alterations to the given
python module.
a. Find the definition for Gomoku (5-in-a-row) in the aima code. Build an evaluation function for
gomoku. In your writeup, briefly explain what your evaluation function is doing.
b. In the function problem 2b, run 20 games of a random agent versus an alpha-betacutoff agent
using your evaluation function, with each agent playing 10 times as X and 10 times as O. Choose
a depth cutoff that will allow each game to complete in under 20 seconds. Have the function
return its results as a tuple containing wins as X as the first item, and wins as O as the second
item. So if your agent wins every single game, it will return (10,10).
Problem 3. (10 points)
a. Construct a balanced game tree with branching factor of 2 and exactly 15 nodes. Suppose that
this tree would be maximally pruned by alpha-beta pruning, based on the evaluation of its leaf
nodes. Show which nodes would be pruned.
b. Suppose you have an oracle, OM(s), that correctly predicts the opponents move in any state.
Using this, formulate the definition of a game as a (single-agent) search problem. Describe an
algorithm for finding the optimal move.
Problem 4. (10 points) An expectimax tree consists of a max node at the root with alternating
layers of chance and max nodes. At chance nodes, all outcome probabilities are nonzero, and the
sum of all probabilities from a given chance node is 1. The goal is to find the value of the root
with a bounded-depth search.
a. If leaf values are all nonnegative, is alpha-beta pruning ever possible in an expectimax tree?
Give an example, or explain why not.
b. If leaf values are all in the range [0,1], is alpha-beta pruning ever possible in an expectimax
tree?
kindly, answer for me all of them and return to me together with the full updated module after
making the alterations.

Contenu connexe

Similaire à look at the following module.import sys sys.path.append(aima-py.pdf

Please help with this. program must be written in C# .. All of the g.pdf
Please help with this. program must be written in C# .. All of the g.pdfPlease help with this. program must be written in C# .. All of the g.pdf
Please help with this. program must be written in C# .. All of the g.pdf
manjan6
 
Objectives Create a Java program using programming fundamentals (fi.docx
Objectives Create a Java program using programming fundamentals (fi.docxObjectives Create a Java program using programming fundamentals (fi.docx
Objectives Create a Java program using programming fundamentals (fi.docx
amit657720
 
Lab Assignment 17 - Working with Object ArraysIn the old days we w.pdf
Lab Assignment 17 - Working with Object ArraysIn the old days we w.pdfLab Assignment 17 - Working with Object ArraysIn the old days we w.pdf
Lab Assignment 17 - Working with Object ArraysIn the old days we w.pdf
eyewaregallery
 

Similaire à look at the following module.import sys sys.path.append(aima-py.pdf (17)

Omp 220 complete class omp220
Omp 220 complete class omp220Omp 220 complete class omp220
Omp 220 complete class omp220
 
1.2 matlab numerical data
1.2  matlab numerical data1.2  matlab numerical data
1.2 matlab numerical data
 
C++ projct
C++ projctC++ projct
C++ projct
 
Programming simple games with a raspberry pi and
Programming simple games with a raspberry pi andProgramming simple games with a raspberry pi and
Programming simple games with a raspberry pi and
 
Mcq cpup
Mcq cpupMcq cpup
Mcq cpup
 
Please help with this. program must be written in C# .. All of the g.pdf
Please help with this. program must be written in C# .. All of the g.pdfPlease help with this. program must be written in C# .. All of the g.pdf
Please help with this. program must be written in C# .. All of the g.pdf
 
Adversarial search
Adversarial searchAdversarial search
Adversarial search
 
Introduction to python programming
Introduction to python programmingIntroduction to python programming
Introduction to python programming
 
Introduction to python programming ( part-2 )
Introduction to python programming ( part-2 )Introduction to python programming ( part-2 )
Introduction to python programming ( part-2 )
 
Python programming workshop
Python programming workshopPython programming workshop
Python programming workshop
 
Programs.doc
Programs.docPrograms.doc
Programs.doc
 
AI-Programs.pdf
AI-Programs.pdfAI-Programs.pdf
AI-Programs.pdf
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with Groovy
 
Objectives Create a Java program using programming fundamentals (fi.docx
Objectives Create a Java program using programming fundamentals (fi.docxObjectives Create a Java program using programming fundamentals (fi.docx
Objectives Create a Java program using programming fundamentals (fi.docx
 
Lab Assignment 17 - Working with Object ArraysIn the old days we w.pdf
Lab Assignment 17 - Working with Object ArraysIn the old days we w.pdfLab Assignment 17 - Working with Object ArraysIn the old days we w.pdf
Lab Assignment 17 - Working with Object ArraysIn the old days we w.pdf
 
python.pptx
python.pptxpython.pptx
python.pptx
 
Unit_I_Introduction(Part_III).ppt
Unit_I_Introduction(Part_III).pptUnit_I_Introduction(Part_III).ppt
Unit_I_Introduction(Part_III).ppt
 

Plus de balrajashok

Los estudios de casos de gesti�n de proyectos se basan en el PMI 201.pdf
Los estudios de casos de gesti�n de proyectos se basan en el PMI 201.pdfLos estudios de casos de gesti�n de proyectos se basan en el PMI 201.pdf
Los estudios de casos de gesti�n de proyectos se basan en el PMI 201.pdf
balrajashok
 
Los empleados primero�. Ese es el valor cultural m�s importante y cr.pdf
Los empleados primero�. Ese es el valor cultural m�s importante y cr.pdfLos empleados primero�. Ese es el valor cultural m�s importante y cr.pdf
Los empleados primero�. Ese es el valor cultural m�s importante y cr.pdf
balrajashok
 

Plus de balrajashok (20)

Los procedimientos anal�ticos son procedimientos sustantivos que pue.pdf
Los procedimientos anal�ticos son procedimientos sustantivos que pue.pdfLos procedimientos anal�ticos son procedimientos sustantivos que pue.pdf
Los procedimientos anal�ticos son procedimientos sustantivos que pue.pdf
 
Los plurales de algunos t�rminos m�dicos pueden ser dif�ciles de con.pdf
Los plurales de algunos t�rminos m�dicos pueden ser dif�ciles de con.pdfLos plurales de algunos t�rminos m�dicos pueden ser dif�ciles de con.pdf
Los plurales de algunos t�rminos m�dicos pueden ser dif�ciles de con.pdf
 
Los miembros deben usar el marco conceptual AICPA para la independen.pdf
Los miembros deben usar el marco conceptual AICPA para la independen.pdfLos miembros deben usar el marco conceptual AICPA para la independen.pdf
Los miembros deben usar el marco conceptual AICPA para la independen.pdf
 
Los patrones caracter�sticos del ciclo econ�mico de valle, expansi�n.pdf
Los patrones caracter�sticos del ciclo econ�mico de valle, expansi�n.pdfLos patrones caracter�sticos del ciclo econ�mico de valle, expansi�n.pdf
Los patrones caracter�sticos del ciclo econ�mico de valle, expansi�n.pdf
 
Los pa�ses de bajos ingresos tienen un INB per c�pita de $1,005 o me.pdf
Los pa�ses de bajos ingresos tienen un INB per c�pita de $1,005 o me.pdfLos pa�ses de bajos ingresos tienen un INB per c�pita de $1,005 o me.pdf
Los pa�ses de bajos ingresos tienen un INB per c�pita de $1,005 o me.pdf
 
Los museos p�blicos a veces piden a los patrocinadores que donen una.pdf
Los museos p�blicos a veces piden a los patrocinadores que donen una.pdfLos museos p�blicos a veces piden a los patrocinadores que donen una.pdf
Los museos p�blicos a veces piden a los patrocinadores que donen una.pdf
 
Los loci A y B tienen una frecuencia de recombinaci�n del 5 por cien.pdf
Los loci A y B tienen una frecuencia de recombinaci�n del 5 por cien.pdfLos loci A y B tienen una frecuencia de recombinaci�n del 5 por cien.pdf
Los loci A y B tienen una frecuencia de recombinaci�n del 5 por cien.pdf
 
Los mercados sociales act�an como ______________ en l�nea aprovechan.pdf
Los mercados sociales act�an como ______________ en l�nea aprovechan.pdfLos mercados sociales act�an como ______________ en l�nea aprovechan.pdf
Los mercados sociales act�an como ______________ en l�nea aprovechan.pdf
 
Los ingresos de una entidad normalmente se miden por los valores de .pdf
Los ingresos de una entidad normalmente se miden por los valores de .pdfLos ingresos de una entidad normalmente se miden por los valores de .pdf
Los ingresos de una entidad normalmente se miden por los valores de .pdf
 
Los impuestos a la propiedad sobre las instalaciones de fabricaci�n .pdf
Los impuestos a la propiedad sobre las instalaciones de fabricaci�n .pdfLos impuestos a la propiedad sobre las instalaciones de fabricaci�n .pdf
Los impuestos a la propiedad sobre las instalaciones de fabricaci�n .pdf
 
Los hombres tienen m�s probabilidades de sufrir una enfermedad o tra.pdf
Los hombres tienen m�s probabilidades de sufrir una enfermedad o tra.pdfLos hombres tienen m�s probabilidades de sufrir una enfermedad o tra.pdf
Los hombres tienen m�s probabilidades de sufrir una enfermedad o tra.pdf
 
Los helechos, un tipo de planta, pasan por una alternancia de genera.pdf
Los helechos, un tipo de planta, pasan por una alternancia de genera.pdfLos helechos, un tipo de planta, pasan por una alternancia de genera.pdf
Los helechos, un tipo de planta, pasan por una alternancia de genera.pdf
 
Los ganglios linf�ticos funcionan como puntos de encuentro entre las.pdf
Los ganglios linf�ticos funcionan como puntos de encuentro entre las.pdfLos ganglios linf�ticos funcionan como puntos de encuentro entre las.pdf
Los ganglios linf�ticos funcionan como puntos de encuentro entre las.pdf
 
Los estudios de casos de gesti�n de proyectos se basan en el PMI 201.pdf
Los estudios de casos de gesti�n de proyectos se basan en el PMI 201.pdfLos estudios de casos de gesti�n de proyectos se basan en el PMI 201.pdf
Los estudios de casos de gesti�n de proyectos se basan en el PMI 201.pdf
 
Los estados financieros de todo el gobierno benefician a los usuar.pdf
Los estados financieros de todo el gobierno benefician a los usuar.pdfLos estados financieros de todo el gobierno benefician a los usuar.pdf
Los estados financieros de todo el gobierno benefician a los usuar.pdf
 
Los especialistas en marketing incorporan mensajes encubiertos en an.pdf
Los especialistas en marketing incorporan mensajes encubiertos en an.pdfLos especialistas en marketing incorporan mensajes encubiertos en an.pdf
Los especialistas en marketing incorporan mensajes encubiertos en an.pdf
 
Los estados financieros de Rukavina Corporation son los siguientes .pdf
Los estados financieros de Rukavina Corporation son los siguientes .pdfLos estados financieros de Rukavina Corporation son los siguientes .pdf
Los estados financieros de Rukavina Corporation son los siguientes .pdf
 
Los elementos de la agencia aparente son A confianza en la repre.pdf
Los elementos de la agencia aparente son A confianza en la repre.pdfLos elementos de la agencia aparente son A confianza en la repre.pdf
Los elementos de la agencia aparente son A confianza en la repre.pdf
 
Los empleados primero�. Ese es el valor cultural m�s importante y cr.pdf
Los empleados primero�. Ese es el valor cultural m�s importante y cr.pdfLos empleados primero�. Ese es el valor cultural m�s importante y cr.pdf
Los empleados primero�. Ese es el valor cultural m�s importante y cr.pdf
 
Los enfoques de Teaming que se usan en los grupos de LinkedIn normal.pdf
Los enfoques de Teaming que se usan en los grupos de LinkedIn normal.pdfLos enfoques de Teaming que se usan en los grupos de LinkedIn normal.pdf
Los enfoques de Teaming que se usan en los grupos de LinkedIn normal.pdf
 

Dernier

Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
Chris Hunter
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 

Dernier (20)

On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 

look at the following module.import sys sys.path.append(aima-py.pdf

  • 1. look at the following module. import sys sys.path.append('aima-python') from search import * from games import * import math def k_in_row(k, board, move, player, delta_x_y): '''Adapted from AIMA code in games.py Purpose: Function to help determine a winner in k-in-a-row type games like TicTacToe, Connect4, Gomoku Parameters: k: int number in a row necessary to win board: dictionary with (row,col) keys, 'X' or 'O' values move: where to search from player: str 'X' or 'O' delta_x_y: which direction to search in Return Value: True if there is a line through move on board for player. ''' (delta_x, delta_y) = delta_x_y x, y = move n = 0 # n is number of moves in row while board.get((x, y)) == player: n += 1 x, y = x + delta_x, y + delta_y x, y = move while board.get((x, y)) == player: n += 1 x, y = x - delta_x, y - delta_y n -= 1 # Because we counted move itself twice return n >= k def is_winner(k, h, v, board, player): '''Adapted from AIMA code in games.py Purpose:
  • 2. Determine if given player wins in a k-in-a-row type game. Parameters: k: int number in a row necessary to win h: width (horizontal) of board v: height (vertical) of board board: dictionary with (row,col) keys, 'X' or 'O' values player: str 'X' or 'O' Return Value: True if player wins, False otherwise ''' for row in range(1, h+1): for col in range(1, v+1): if (k_in_row(k, board, (row,col), player, (0,1)) or k_in_row(k, board, (row,col), player, (1,0)) or k_in_row(k, board, (row,col), player, (1,-1)) or k_in_row(k, board, (row,col), player, (1,1))): return True return False def connect4_eval_bad(state): '''Example of a bad evaluation function: It gives a high score to any state whose board has a lot of Xs in the 7th row (that is, the bottom row) This is a terrible plan, but at least you can see it in action, as the agent will prefer to put its pieces on across the bottom row if at all possible. (Change it to row 2 or 3 if you want to see different behavior) ''' if is_winner(4, 7, 6, state.board, 'X'): return 1 if is_winner(4,7,6, state.board, 'O'): return -1 ev = 0 for col in range(1,7): if (7,col) in state.board and state.board[(7,col)] == 'X': ev += 1
  • 3. # Divide by 42 to make sure that ev is less than 1 # It is important to make sure that your evaluation is never better or worse than # actual win/loss utility (represented by 1/-1) return ev / 42 def connect4_eval(state): '''Your Connect 4 evaluation function Hopefully better than mine! ''' return 0 def ab_cutoff_player(game, state): return alpha_beta_cutoff_search(state, game, d=2, eval_fn=connect4_eval_bad) class HW3: def __init__(self): pass def ttt_game(self): tt = TicTacToe() tt.play_game(alpha_beta_player,query_player) def c4_game(self): c4 = ConnectFour() c4.play_game(ab_cutoff_player,query_player) def problem_1d(): # write your code for problem 1d here pass def problem_2b(): # write your code for problem 2b here pass def main(): hw3 = HW3() # An example for you to follow to get you started on Games print('Playing Tic-Tac-Toe...') print('======================') hw3.ttt_game() ## uncomment the following lines to play connect 4 #print('Playing Connect 4...')
  • 4. #print('====================') #hw3.c4_game() if __name__ == '__main__': main() I need you to help me with the following questions and also return me the whole module filled with problem_1d and problem_2b functions and also with a connect4_eval function that isn't terrible. Here are the questions. please help me answer all of them.! Problem 1. (30 points) For problem 1, you will put answers in your writeup for a - c. Also make alterations to the given python module. a. Run the ttt game code. You will be prompted to play tic-tac-toe against a minimax agent. Common wisdom suggests that the best first move is the center square. The agent doesnt begin by playing in the center square. Why do you think the agent plays where it does instead of the center? b. Run c4 game. You will be prompted to play connect-4 against an alpha-beta with cutoff agent that is using a terrible evaluation function. See if you can defeat the agent in a few games. What is your best plan to defeat it? Why? c. In the function connect4 eval, write a new evaluation function that isnt terrible. Using this function, write code that will play an alpha-beta agent with depth cutoff 4 using your evaluation function against a random agent. Describe your evaluation function in your writeup and explain why you think it should do well. d. In the function problem 1d, run 20 games of a random agent versus your alpha-betacutoff agent, with each agent playing 10 times as X and 10 times as O. Have the function return its results as a tuple containing wins as X as the first item, and wins as O as the second item. So if your agent wins every single game, it will return (10,10). For problem 2, you will put answers in your writeup for a. Also make alterations to the given python module. a. Find the definition for Gomoku (5-in-a-row) in the aima code. Build an evaluation function for gomoku. In your writeup, briefly explain what your evaluation function is doing. b. In the function problem 2b, run 20 games of a random agent versus an alpha-betacutoff agent using your evaluation function, with each agent playing 10 times as X and 10 times as O. Choose a depth cutoff that will allow each game to complete in under 20 seconds. Have the function return its results as a tuple containing wins as X as the first item, and wins as O as the second item. So if your agent wins every single game, it will return (10,10).
  • 5. Problem 3. (10 points) a. Construct a balanced game tree with branching factor of 2 and exactly 15 nodes. Suppose that this tree would be maximally pruned by alpha-beta pruning, based on the evaluation of its leaf nodes. Show which nodes would be pruned. b. Suppose you have an oracle, OM(s), that correctly predicts the opponents move in any state. Using this, formulate the definition of a game as a (single-agent) search problem. Describe an algorithm for finding the optimal move. Problem 4. (10 points) An expectimax tree consists of a max node at the root with alternating layers of chance and max nodes. At chance nodes, all outcome probabilities are nonzero, and the sum of all probabilities from a given chance node is 1. The goal is to find the value of the root with a bounded-depth search. a. If leaf values are all nonnegative, is alpha-beta pruning ever possible in an expectimax tree? Give an example, or explain why not. b. If leaf values are all in the range [0,1], is alpha-beta pruning ever possible in an expectimax tree? kindly, answer for me all of them and return to me together with the full updated module after making the alterations.