Advertisement
Guest User

Untitled

a guest
Jul 21st, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.61 KB | None | 0 0
  1. # tools for minimax
  2.  
  3. def _switch_rate(r):
  4.     '''Return opposing players rating corresponding to r.'''
  5.  
  6.     return r * -1 # one's loss is the other's gain
  7.  
  8. class GameState:
  9.    
  10.     """State of a two-person game, including player about to play.
  11.  
  12.       Assumptions:
  13.       Two-person, zero-sum game, with exactly three outcomes:
  14.       player one can win, lose, or draw, whereas player two
  15.       can (respectively) lose, win, or draw.
  16.       Each ply toggles player_1 <-> player_2.
  17.    """
  18.     '''Class constants.'''
  19.     WIN = 1
  20.     LOSE = -1
  21.     DRAW = 0
  22.     INF = float(9999999999999999999999999)
  23.    
  24.  
  25.     def __init__(self, start_state):
  26.         """Create a new Game in starting state.
  27.  
  28.            Arguments
  29.            start_state:  Tuple (layout, starting player).
  30.        """
  31.        
  32.         self._state = start_state
  33.  
  34.     def terminal_eval(self):
  35.         """Return current player's score at end of game.
  36.  
  37.           Assumptions:
  38.           The game is in a state reachable from the initial position by a
  39.           sequence of plies, with a current player to play, but no further
  40.           plies allowed.
  41.  
  42.           Returns:
  43.           Return whether the current player wins, loses, or ties.
  44.        """
  45.  
  46.         if self.winner(self.player()):
  47.             return self.WIN
  48.         elif self.winner(self.opponent()):
  49.             return self.LOSE
  50.         else:
  51.             return self.DRAW
  52.  
  53.     def heuristic_eval(self):
  54.         """Return estimate of current player's score at end of game.
  55.  
  56.           Assumptions:
  57.           Game is in a state reachable from initial position by sequence
  58.           of plies, current player to play, possibly further moves allowed.
  59.  
  60.           Returns:
  61.           Confidence that current player wins (0,1], loses [-1,0), or
  62.           draws (0).
  63.        """
  64.        
  65.         raise NotImplementedError('Implemented in GameState subclass')
  66.  
  67.     def minimax(self, foresight, pred_max=-1, layout=None):
  68.         """Return best move and score for current GameState.
  69.  
  70.           Arguments:
  71.           foresight: Number of plies we may look ahead.
  72.           pred_max:  Best score so far of predecessor GameState.
  73.           layout:    Dictionary containing best score and move
  74.                      for each layout
  75.          
  76.            Assumptions:
  77.            Current player has at least one legal move available.
  78.            foresight is positive.
  79.  
  80.            Returns (m, s)
  81.            s:  Highest score that current player can guarantee.
  82.            m:  Next move that allows current player to guarantee s.
  83.        """
  84.         if self.next_move() == []:
  85.             return terminal_eval()
  86.         for plys in self.next_move():
  87.             game_after_ply = self.make_move(plys)
  88.             score =  game_after_ply.heuristic_eval()
  89.             if foresight == 0:
  90.                 if  game_after_ply.next_move() == []:
  91.                     if score == -1:
  92.                         return (1, plys)
  93.                     elif score == 0:
  94.                         if 0 > pred_max:
  95.                             return (0, plys)
  96.                     else:
  97.                         return (-1, plys)
  98.                 else:
  99.                     if score < pred_max:
  100.                         return (score, plys)
  101.             else:
  102.                 foresight -= 1
  103.                 tup = self.minimax((foresight), pred_max, layout)
  104.                 layout[tup[0]] = tup[1]
  105.         keys = layout.keys()
  106.         keys_s = keys.sort()
  107.         return (keys_s[0], layout[keys_s[0]])
  108.    
  109.                        
  110.                    
  111.                    
  112.                    
  113.                    
  114.  
  115.        
  116.        
  117.     def player(self):
  118.         """Return current player --- the one with option of moving.
  119.  
  120.           Assumptions
  121.           Player returned is one of 'p1' or 'p2'.
  122.           Player returned might have no legal moves available.
  123.        """
  124.  
  125.         return self._state[1]  # state is a 2-tuple
  126.    
  127.     def opponent(self):
  128.         """Return opponent of current player."""
  129.         if self.player() == 'p1':
  130.             return 'p2'
  131.         else:
  132.             return 'p1'
  133.  
  134.     def next_move(self):
  135.         """Return a sequence of all legal moves."""
  136.         raise NotImplementedError('Implement next_move in GameState subclass')
  137.  
  138.     def winner(self, player):
  139.         """Return whether this player has won."""
  140.         raise NotImplementedError('Implement winner in GameState subclass')
  141.  
  142.     def make_move(self, move):
  143.         """Return new GameState by applying move."""
  144.         raise NotImplementedError('Implement make_move in GameState subclass')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement