def print_turn(board: OthelloBoard) -> None:
        """It will print current player. """

        if board.get_player_turn() == board.get_black():
            print('\nBLACK\'s Turn.')
        else:
            print('\nWHITE\'s Turn.')
    def print_scores(board: OthelloBoard) -> None:
        """ It will print scores of players. """

        print('\n******************************')
        print('************SCORES************')
        print('******************************')
        print('  BLACK = {}   &   WHITE = {} '.format(board.get_score('B'), board.get_score('W')))
        print('******************************\n')
Beispiel #3
0
 def __init__(self, path):
     self.root = Tk()
     self.mc = BasicOthelloCanvas(self.root, 8, 8, cellsize = 100)
     
     self.env = OthelloBoard(8)
     self.env.reset()
     self.mc.setBoard(self.env.board)
     
     self.controller = OthelloController(path, 2, epsilon = 10000)
     self.playing = True
 def _min_value(self, state: OthelloBoard):
     if not(state.has_legal_moves_remaining(self.symbol)) and not(state.has_legal_moves_remaining(self.oppSym)):
         return self._utility(state)
     value = float('inf')
     actions = list(state.get_legal_moves(self.oppSym))
     for a in actions:
         clone = state.cloneOBoard() #preserve initial board
         clone.play_move(a[0], a[1], self.oppSym) #generate successor
         value = min(value, self._max_value(clone))
     return value
 def _minimax_decision(self, state: OthelloBoard):
     actions = list(state.get_legal_moves(self.symbol))
     value = float("-inf")
     champ_action = actions[0]
     for a in actions:
         clone = state.cloneOBoard() #preserve initial board
         clone.play_move(a[0], a[1], self.symbol) #generate successor
         min_val = self._min_value(clone)
         if(min_val > value): #choose action with max value
             champ_action = a
     return champ_action
Beispiel #6
0
class Arena(object):
    def __init__(self, path):
        self.root = Tk()
        self.mc = BasicOthelloCanvas(self.root, 8, 8, cellsize = 100)
        
        self.env = OthelloBoard(8)
        self.env.reset()
        self.mc.setBoard(self.env.board)
        
        self.controller = OthelloController(path, 2, epsilon = 10000)
        self.playing = True

    def move(self, index1, index2, toPlay):
        observation = copy.deepcopy(self.env.board)
        
        players = [self.controller.population[index1], self.controller.population[index2]]
        
        d = {1: 0, -1: 1}
        e = {0: 1, 1: -1}
        
        # Chose a move and take it
        
        move = players[d[toPlay]].policy(observation, toPlay)
            
        observation, reward, done, info = self.env.step(move)
        
        self.mc.setBoard(observation)
    
    def play(self, load_weights1, load_weights2):
        self.controller.load([load_weights1, load_weights2])
        moving = True
        
        self.mc.focus_set()
        
        while(True):
            t1 = time.time()
            self.move(0, 1, 1)
            t2 = time.time()

            time.sleep(max(2-t2+t1, 0))
            self.mc.update()
            self.mc.update_idletasks()
            t1 = time.time()
            self.move(0, 1, -1)
            t2 = time.time()
            
            time.sleep(max(2-t2+t1, 0))
            self.mc.update()
            self.mc.update_idletasks()
            
            
    def print_board(board: OthelloBoard) -> None:
        """ It will print the current board. """

        h_line = '   ' + ' ---' * board.get_num_columns() + ' '

        col_num = '  '

        if (board.get_num_columns()/2) < 5:
            for i in range(board.get_num_columns()):
                col_num += '   ' + str(i+1)
        else:
            for i in range(8):
                col_num += '   ' + str(i+1)
            col_num += ' '
            for j in range(8, board.get_num_columns()):
                col_num += '  ' + str(j+1)

        print(col_num)
        print(h_line)

        for i in range(board.get_num_rows()):
            print('{:2d}'.format(i+1), end=' ')
            for j in range(board.get_num_columns()):
                print('| {} '.format(board.get_game_state()[i][j]), end='')
            print('|')
            print(h_line)
 def _utility(self, state: OthelloBoard):
     xscore = state.count_score(self.symbol)
     oscore = state.count_score(self.oppSym)
     if(xscore > oscore):
         return 1
     elif (xscore == oscore):
         return 0
     else:
         return -1
class OthelloSession(object):
    def __init__(self, path):
        self.path = path
        self.root = Tk()
        self.env = OthelloBoard(8)
        self.env.reset()

        self.mc = BasicOthelloCanvas(self.root, 8, 8, cellsize=100)
        self.mc.setBoard(self.env.board)

        self.controller = OthelloController(path, 1, epsilon=10000)

    def play(self, load_num):
        self.controller.load([load_num])
        self.controller.population[0].depth = 3

        def makeMove(event):
            x, y = self.mc.cell_coords(event.x, event.y)

            if (self.env.ValidMove(x, y, 1)):
                observation, reward, done, info = self.env.step([x, y])

                if (done):
                    print("Done!!!")
                else:
                    self.mc.setBoard(observation)
                    self.mc.update()

                    move = self.controller.population[0].policy(
                        observation, -1)

                    observation, reward, done, info = self.env.step(move)

                    self.mc.setBoard(self.env.board)
                    self.mc.after(5000, self.mc.update)
            else:
                print("That Move cannot be made, make another one.")

        def passMove(event):
            observation, reward, done, info = self.env.step([-1, -1])

            if (done):
                print("Done!!!")
            else:
                move = self.controller.population[0].policy(observation, -1)

                observation, reward, done, info = self.env.step(move)

                self.mc.setBoard(observation)

        self.mc.bind("<Button-1>", makeMove)
        self.mc.bind("<Button-2>", passMove)
        self.mc.update()

        self.root.mainloop()
    def move_row(board: OthelloBoard) -> int:
        """ It will take an object of class Othello and promote the user for the
        the row number of his/her move and return it. """

        while True:

            try:

                user_input = (int(input('Please specify the ROW number.\nPlease enter an integer between 1 to {} for number of the row: '.format(board.get_num_rows())))) - 1

                #if game_state.valid_row(user_input):
                if 0 <= user_input < board.get_num_rows():
                    return user_input

                else:

                    raise InvalidInputException()

            except:

                print('\nInvalid Input!!!')
                print('Please try it again.\n')
Beispiel #11
0
    def alphabeta(self, board, depth, alpha, beta, color, index):
        if(depth == 0):
            return self.policy(board, color, index), None

        moves = []
        if(color == 1):
            moves = board.move_generator()
        else:
            board.reverse()
            moves = board.move_generator()
            board.reverse()
        
        if len(moves) == 0:
            newboard = OthelloBoard(8)
            newboard.reset()
            newboard.board = deepcopy(board.board)
            score, m = self.alphabeta(newboard, depth-1, alpha, beta, -color, index)
                
            return score, m

        if(color == 1):
            return_move = None

            for move in moves:
                newboard = OthelloBoard(8)
                newboard.reset()
                newboard.board = deepcopy(board.board)
                newboard.MakeMove(move[0], move[1],color)

                score, m = self.alphabeta(newboard, depth-1, alpha, beta, -1, index)
                
                if(score > alpha):
                    alpha = score
                    return_move = move
                
                if(beta <= alpha):
                    break
            return alpha, return_move
        elif(color == -1):
            return_move = None

            for move in moves:
                newboard = OthelloBoard(8)
                newboard.reset()
                newboard.board = deepcopy(board.board)
                newboard.MakeMove(move[0], move[1],color)

                score, m = self.alphabeta(newboard, depth - 1, alpha, beta, 1, index)

                if(score < beta):
                    beta = score
                    return_move = move

                if(beta <= alpha):
                    break
            return beta, return_move
        else:
            print("Error in AlphaBeta, Color is not 1 or -1")
            print("Color is: " + color)
            raise(Exception("Color Error in Alpha Beta"))