Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import copy
- import random
- from exceptions import AgentException
- class MinMaxAgent:
- def __init__(self, my_token='o'):
- self.my_token = my_token
- def decide(self, connect4):
- if connect4.who_moves != self.my_token:
- raise AgentException('not my round')
- score, best_drop = self.minimax(connect4, 5, connect4.who_moves)
- if best_drop is None:
- return random.choice(connect4.possible_drops())
- return best_drop
- def minimax(self, connect4, depth, who_moves):
- if depth == 0:
- return 0, None
- if who_moves != connect4.who_moves:
- raise AgentException('not my round')
- score = -999
- best_drop = None
- for possible_drop in connect4.possible_drops():
- plansza_testowa = copy.deepcopy(connect4)
- plansza_testowa.drop_token(possible_drop)
- if plansza_testowa.game_over:
- if plansza_testowa.wins == who_moves:
- return 1, possible_drop
- new_score, new_best_drop = self.minimax(plansza_testowa, depth - 1, 'o' if who_moves == 'x' else 'x')
- new_score *= -1
- if new_score > score:
- score = new_score
- best_drop = possible_drop
- return score, best_drop
- import copy
- import random
- from exceptions import AgentException
- class AlphaBetaAgent:
- def __init__(self, my_token='o'):
- self.my_token = my_token
- def decide(self, connect4):
- if connect4.who_moves != self.my_token:
- raise AgentException('not my round')
- score, best_drop = self.alphabeta(connect4, 5, connect4.who_moves, -999, 999)
- if best_drop is None:
- return random.choice(connect4.possible_drops())
- return best_drop
- def alphabeta(self, connect4, depth, who_moves, alpha, beta):
- if depth == 0:
- return 0, None
- if who_moves != connect4.who_moves:
- raise AgentException('not my round')
- score = -999
- best_drop = None
- for possible_drop in connect4.possible_drops():
- plansza_testowa = copy.deepcopy(connect4)
- plansza_testowa.drop_token(possible_drop)
- if plansza_testowa.game_over:
- if plansza_testowa.wins == who_moves:
- return 1, possible_drop
- new_score, new_best_drop = self.alphabeta(plansza_testowa, depth - 1, 'o' if who_moves == 'x' else 'x', -beta, -alpha)
- new_score *= -1
- if new_score > score:
- score = new_score
- best_drop = possible_drop
- alpha = max(alpha, score)
- if alpha >= beta:
- break
- return score, best_drop
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement