Python board.Board() Examples

The following are 8 code examples of board.Board(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module board , or try the search function .
Example #1
Source File: minimax.py    From ClassicComputerScienceProblemsInPython with Apache License 2.0 6 votes vote down vote up
def minimax(board: Board, maximizing: bool, original_player: Piece, max_depth: int = 8) -> float:
    # Base case – terminal position or maximum depth reached
    if board.is_win or board.is_draw or max_depth == 0:
        return board.evaluate(original_player)

    # Recursive case - maximize your gains or minimize the opponent's gains
    if maximizing:
        best_eval: float = float("-inf") # arbitrarily low starting point
        for move in board.legal_moves:
            result: float = minimax(board.move(move), False, original_player, max_depth - 1)
            best_eval = max(result, best_eval) # we want the move with the highest evaluation
        return best_eval
    else: # minimizing
        worst_eval: float = float("inf")
        for move in board.legal_moves:
            result = minimax(board.move(move), True, original_player, max_depth - 1)
            worst_eval = min(result, worst_eval) # we want the move with the lowest evaluation
        return worst_eval 
Example #2
Source File: minimax.py    From ClassicComputerScienceProblemsInPython with Apache License 2.0 6 votes vote down vote up
def alphabeta(board: Board, maximizing: bool, original_player: Piece, max_depth: int = 8, alpha: float = float("-inf"), beta: float = float("inf")) -> float:
    # Base case – terminal position or maximum depth reached
    if board.is_win or board.is_draw or max_depth == 0:
        return board.evaluate(original_player)

    # Recursive case - maximize your gains or minimize the opponent's gains
    if maximizing:
        for move in board.legal_moves:
            result: float = alphabeta(board.move(move), False, original_player, max_depth - 1, alpha, beta)
            alpha = max(result, alpha)
            if beta <= alpha:
                break
        return alpha
    else:  # minimizing
        for move in board.legal_moves:
            result = alphabeta(board.move(move), True, original_player, max_depth - 1, alpha, beta)
            beta = min(result, beta)
            if beta <= alpha:
                break
        return beta


# Find the best possible move in the current position
# looking up to max_depth ahead 
Example #3
Source File: tictactoe.py    From ClassicComputerScienceProblemsInPython with Apache License 2.0 5 votes vote down vote up
def move(self, location: Move) -> Board:
        temp_position: List[TTTPiece] = self.position.copy()
        temp_position[location] = self._turn
        return TTTBoard(temp_position, self._turn.opposite) 
Example #4
Source File: connectfour.py    From ClassicComputerScienceProblemsInPython with Apache License 2.0 5 votes vote down vote up
def move(self, location: Move) -> Board:
        temp_position: List[C4Board.Column] = self.position.copy()
        for c in range(C4Board.NUM_COLUMNS):
            temp_position[c] = self.position[c].copy()
        temp_position[location].push(self._turn)
        return C4Board(temp_position, self._turn.opposite) 
Example #5
Source File: minimax.py    From ClassicComputerScienceProblemsInPython with Apache License 2.0 5 votes vote down vote up
def find_best_move(board: Board, max_depth: int = 8) -> Move:
    best_eval: float = float("-inf")
    best_move: Move = Move(-1)
    for move in board.legal_moves:
        result: float = alphabeta(board.move(move), False, board.turn, max_depth)
        if result > best_eval:
            best_eval = result
            best_move = move
    return best_move 
Example #6
Source File: game.py    From Chess-AI with MIT License 5 votes vote down vote up
def __init__(self, fen=default_fen, validate=True):
        """
        Initialize the game board to the supplied FEN state (or the default
        starting state if none is supplied), and determine whether to check
        the validity of moves returned by `get_moves()`.
        """
        self.board = Board()
        self.state = State(' ', ' ', ' ', ' ', ' ')
        self.move_history = []
        self.fen_history = []
        self.validate = validate
        self.set_fen(fen=fen) 
Example #7
Source File: main.py    From DE3-ROB1-CHESS with Creative Commons Attribution 4.0 International 4 votes vote down vote up
def main(argv):
   actions = {}
   actions["train"] = main_train
   actions["show_tiles"] = main_show_tiles
   actions["dev"] = main_dev


   parser = argparse.ArgumentParser(description='A chess OCR application.')
   parser.add_argument('filenames', metavar='filename', type=str, nargs='+',
                       help='The files to process.')

   parser.add_argument('-e', dest='extract_boards', action='store_const',
                       const=True, default=False,
                       help='extract boards from images (default: use image as-is)')

   parser.add_argument('-a', dest='action', default="show_tiles",
                       choices=["train", "show_tiles", "dev"],
                       help='action to perform (default: show_tiles)')

   args = parser.parse_args()

   action = actions[args.action]



   for filename in args.filenames:
      image = cv2.imread(filename)
      print("---- %s ----" % filename)

      if args.extract_boards:
         print("Extracting Boards")
         boards = extractBoards(image, extract_width, extract_height)
      else:
         boards = [image]

      for b in boards:
         print("Extracting Grid")
         grid = extractGrid(b, 9, 9)

         print(grid)
         if grid is None:
            print("Could not find Grid")
            continue

         print("Extracting Tiles")
         tiles = extractTiles(b, grid, 100, 100)

         b = Board(tiles, 8, 8)

         print("Running action")
         action(b, args) 
Example #8
Source File: main.py    From DE3-ROB1-CHESS with Creative Commons Attribution 4.0 International 4 votes vote down vote up
def main(argv):
   actions = {}
   actions["train"] = main_train
   actions["show_tiles"] = main_show_tiles
   actions["dev"] = main_dev


   parser = argparse.ArgumentParser(description='A chess OCR application.')
   parser.add_argument('filenames', metavar='filename', type=str, nargs='+',
                       help='The files to process.')

   parser.add_argument('-e', dest='extract_boards', action='store_const',
                       const=True, default=False,
                       help='extract boards from images (default: use image as-is)')

   parser.add_argument('-a', dest='action', default="show_tiles",
                       choices=["train", "show_tiles", "dev"],
                       help='action to perform (default: show_tiles)')

   args = parser.parse_args()

   action = actions[args.action]



   for filename in args.filenames:
      image = cv2.imread(filename)
      print("---- %s ----" % filename)

      if args.extract_boards:
         print("Extracting Boards")
         boards = extractBoards(image, extract_width, extract_height)
      else:
         boards = [image]

      for b in boards:
         print("Extracting Grid")
         grid = extractGrid(b, 9, 9)

         print(grid)
         if grid is None:
            print("Could not find Grid")
            continue

         print("Extracting Tiles")
         tiles = extractTiles(b, grid, 100, 100)

         b = Board(tiles, 8, 8)

         print("Running action")
         action(b, args)