Example #1
0
def main():

    # Get the application data
    f = open(".access_token", "r")
    keydata = json.loads(f.read())

    # Initiate the moves object
    m = Moves(keydata)

    # Initiate the com link with arduino
    c = Comm()

    loops = 0

    # Run program loop
    while True:

        state = 0

        # Load date interval
        currentDate = datetime.datetime.now().strftime("%Y%m%d")
        oldDate = (datetime.datetime.now() - datetime.timedelta(days=30)).strftime("%Y%m%d")

        data = m.getRangeSummary(oldDate, currentDate)
        processor = DataProcessor(data)

        msg = processor.getDuration()

        print msg

        c.send(msg)

        # Sleep program untill next check
        time.sleep(30)
Example #2
0
    def possibleBoards(self):
        #List Object
        boards=[""]
        for i in range(0,7):
            for j in range(0,7):
                if(self.pins[i][j]!="-" and self.pins[i][j]!="0"):

                    #Position object specifies row and col
                    start = Position(i,j)

                    #Moves object specifies start,jump and end
                    moves_obj=Moves()

                    #Read all possible moves of a particular point(x,y) from dictionary
                    possible_moves=moves_obj.getMoves(start);

                    #print "Possible Moves::",possible_moves;
                    #print "==========================================================="
                    for move_point in possible_moves:
                        #move_point[0]:start,jump and end
                        move=Move(move_point[0],move_point[1],move_point[2]);

                        #print "Individual Move::",move_loop;
                        if(self.validMove(move)):
                            boards.append(self.jump(move))

        #remove first item from list array which is empty string
        boards.remove("");

        #print "Board Values in PossibleBoards()::",boards;
        #exit("exit exit");
        return boards;
 def __init__(self, type, depthLimit=6):
     self.DEPTH_LIMIT = depthLimit
     self.type = type
     self.mg = MoveGenerator(type)
     self.lastMove = Moves()
     self.lastMoveHasCaptured = False
     self.counter = 0
     self.prunedCounter = 0
Example #4
0
 def __init__(self, type):
     #sometimes, it try to preview a draw possibility, so it goes to the maximum depth recursion
     self.LIMIT_RECURSION_SECURITY = 200  #this constant is necessery to bypass this problem
     self.type = type
     self.mg = MoveGenerator(type)
     self.alpha = -sys.maxsize - 1
     self.beta = sys.maxsize
     self.lastMove = Moves()
     self.lastMoveHasCaptured = False
     self.counter = 0
     self.prunedCounter = 0
Example #5
0
def main():

	# Get the application data
	f = open('.access_token', 'r')
	keydata = json.loads(f.read())

	# Initiate the moves object
	m = Moves(keydata)
	
	# Initiate the com link with arduino
	c = Comm()

	loops = 0

	# Run program loop
	while True:

		state = 0

		if loops is 0:
			# Load date interval
			currentDate = datetime.datetime.now().strftime('%Y%m%d')
			oldDate = (datetime.datetime.now() - datetime.timedelta(days=30)).strftime('%Y%m%d')

			data = m.getRangeSummary(oldDate, currentDate)
			processor = DataProcessor(data)

			raw = processor.newDataProcessor()

			if processor.checkMoving():
				state = 1


		# Check realtime
		realtime = datetime.datetime.strptime(requests.get('http://studier.albinhubsch.se/lucy-light').text, "%Y-%m-%d %H:%M:%S")
		now = datetime.datetime.now()

		if realtime + datetime.timedelta(minutes=10) > now:
			state = 1


		msg = str(state) + ',' + raw

		c.send(msg)

		if loops < 10:
			loops += 1
		else:
			loops = 0

		# Sleep program untill next check
		time.sleep(6)
Example #6
0
 def __init__(self, type):
     self.type = type
     self.lastMoveHasCaptured = False
     self.mg = MoveGenerator(type)
     self.lastMove = Moves()
     self.counter = 0
     self.prunedCounter = 0
Example #7
0
 def getMove(self, board=Board()):
     self.counter = 0
     self.prunedCounter = 0
     self.alpha = -sys.maxsize - 1
     self.beta = sys.maxsize
     moves = []
     if (self.lastMoveHasCaptured):
         ans = RuleEngine.possibleStates(board, self.lastMove.finalPosition)
         for move in ans[0]:
             if move.hasCaptured():
                 moves.append(move)
         self.lastMoveHasCaptured = False
     else:
         moves = self.mg.possibleActions(board)
     bestMoveIndex = []
     maxV = -sys.maxsize - 1
     for index in range(len(moves)):
         auxV = self.Min(board, [moves[index]])
         if auxV > maxV:
             maxV = auxV
             bestMoveIndex.clear()
             bestMoveIndex.append(index)
         elif auxV == maxV:
             bestMoveIndex.append(index)
     if (len(moves) > 0):
         if (len(bestMoveIndex) == 0):
             print(
                 "==========================ERROR=============================="
             )
             return False
         choose = randint(0, len(bestMoveIndex) - 1)
         self.lastMove = moves[bestMoveIndex[choose]]
         if (self.lastMove.hasCaptured()):
             self.lastMoveHasCaptured = True
         return moves[bestMoveIndex[choose]]
     else:
         if (self.lastMove.hasCaptured()):
             return Moves(Position(-1, -1))
         winner = board.winner(self.mg)
         if (winner == self.type):
             move = Moves()
             move.setWin()
             return move
         elif (winner != "."):
             move = Moves()
             move.setLost()
             return move
         print(
             "==========================ERROR=============================="
         )
         return False
Example #8
0
 def push_move(self, agent_id, game_id, turn_num, move, next_best_val,
               hand_val_before, hand_val_after):
     move = Moves.convert_to_bit(move)
     query = """INSERT INTO "Moves"
                (player_id, game_id, turn_num, next_best_val, hand_val_before, move, hand_val_after) \
                VALUES ("{0}", {1}, {2}, {3}, {4}, {5}, {6});""".format(
         agent_id, game_id, turn_num, next_best_val, hand_val_before, move,
         hand_val_after)
     self.execute_queries(query)
Example #9
0
 def __init__(self, turns=None):
     self.moves = Moves()
     self.cube = [[" " for _ in range(9)] for _ in range(12)]
     self.turns = turns
     self.cycles = 0
     for x in range(len(self.cube)):
         for y in range(len(self.cube[x])):
             if x <= 2 and y in range(3, 6):
                 self.cube[x][y] = "W"
             elif x in range(3, 6) and y <= 2:
                 self.cube[x][y] = "R"
             elif x in range(3, 6) and y in range(2, 6):
                 self.cube[x][y] = "B"
             elif x in range(3, 6) and y >= 6:
                 self.cube[x][y] = "O"
             elif x in range(6, 9) and y in range(3, 6):
                 self.cube[x][y] = "Y"
             elif x in range(9, 13) and y in range(3, 6):
                 self.cube[x][y] = "G"
     self.solved = self.cube
Example #10
0
 def push_cc(self, game_id, turn_num, bust, blackjack, exceedWinningPlayer,
             alreadyExceedingWinningPlayer, move):
     move = Moves.convert_to_bit(move)
     alreadyExceedingWinningPlayer = int(alreadyExceedingWinningPlayer)
     query = """
             INSERT INTO Card_Counter_Record
             (game_id, turn_num, bust, blackjack, exceedWinningPlayer, alreadyExceedingWinningPlayer, move)
             VALUES ({0}, {1}, {2}, {3}, {4}, {5}, {6})
             """.format(game_id, turn_num, bust, blackjack,
                        exceedWinningPlayer, alreadyExceedingWinningPlayer,
                        move)
     self.execute_queries(query)
    def get_aggression_rating_move(self, move, hit_map, stand_map):
        turn_num = move[0]
        next_best_val = move[1]
        hand_val_before = move[2]
        action = Moves.convert_to_move(move[3])
        hand_val_after = move[4]

        aggr_rating = None
        if action == Moves.HIT:
            aggr_rating = hit_map[str(hand_val_before)]
        elif action == Moves.STAND:
            aggr_rating = stand_map[str(hand_val_before)]
        return aggr_rating
Example #12
0
    def train(self, sess):
        train_iterations = self.parameters["train_steps"]

        self.sess = sess
        self.NN.Target_Network.updateTarget(sess)

        for game_num in range(train_iterations):
            print(game_num)
            all_hands = self.blackjack.get_all_hands()
            episode_buffer = []
            game_state = self.get_train_game_state(all_hands)
            action = None
            new_game_state = None
            # step in game, get reward and new state
            while self.blackjack.continue_game:
                current_agent = self.blackjack.get_current_player()
                # print(current_agent.id)
                if current_agent.id != self.NN.ID:
                    move = self.group_agents[current_agent.id].get_move(
                        all_hands)
                    self.process_action(move)
                    new_game_state = self.get_train_game_state(all_hands)
                else:  # is the nn agent's turn
                    action, new_game_state = self.process_NN_agent_action(
                        game_num, all_hands, game_state, episode_buffer,
                        self.exp_buffer)
                game_state = new_game_state  # update the game state
            # PROCESS END OF GAME
            # GET THE END OF GAME REWARD
            self.end_game()
            reward = self.gen_reward()
            # should never execute
            if action is None:
                print("NO MOVES EXECUTED")
            # decide if you want to append this
            action = Moves.convert_to_bit(action)
            episode_buffer.append(
                np.reshape(
                    np.array([
                        game_state, action, reward, new_game_state,
                        self.blackjack.continue_game
                    ]), [1, 5]))
            # Add the episode to the experience buffer
            bufferArray = np.array(episode_buffer)
            episodeBuffer = list(zip(bufferArray))
            self.exp_buffer.add(episodeBuffer)
            self.reset()
        # saves the new model after training
        self.NN.save_model()
 def get_distinct_vals(self, move):
     if isinstance(move, Moves):
         move = Moves.convert_to_bit(move)
     elif not (isinstance(move, int) and (move == 0 or move == 1)):
         return False
     get_distinct_vals = """
                         SELECT DISTINCT hand_val_before
                         FROM Moves
                         WHERE move={0};
                         """.format(move)
     distinct_vals_res = self.db_wrapper.execute_queries(get_distinct_vals,
                                                         get_result=True)
     values = [i[0] for i in distinct_vals_res]  # all distinct hand values
     values.sort()
     return values
Example #14
0
    def astar_possibleBoards(self,heuristic_val):
        #List Object
        boards=[""]
        for i in range(0,7):
            for j in range(0,7):
                if(self.pins[i][j]!="-" and self.pins[i][j]!="0"):
                    #Position object specifies row and col

                    start = Position(i,j)

                    #Moves object specifies start,jump and end
                    moves_obj=Moves()

                    #Read all possible moves of a particular point(x,y) from dictionary
                    possible_moves=moves_obj.getMoves(start);


                    #Read all possible costs related to a particular move
                    possible_costs=moves_obj.getCost(start);

                    #Read all heuristics related to a particular move
                    if(heuristic_val==1):
                        possible_heuristics=moves_obj.getHeuristic1(start);
                    else:
                        possible_heuristics=moves_obj.getHeuristic2(start);

                    #code for finding fn from hn and gn values
                    if(heuristic_val==1):
                        for i in range(0,7):
                            for j in range(0,7):
                                self.f[i][j]=self.c[i][j]+self.h1[i][j];
                    if(heuristic_val==2):
                        for i in range(0,7):
                            for j in range(0,7):
                                self.f[i][j]=self.c[i][j]+self.h2[i][j];

                        for move_point in possible_moves:
                            #move_point[0]:start,jump and end

                            move=Move(move_point[0],move_point[1],move_point[2]);

                            #print "Individual Move::",move_loop;
                            if(self.validMove(move)):
                                boards.append(self.jump(move))

        #remove first item from list array which is empty string
        boards.remove("");

        #print "Board Values in PossibleBoards()::",boards;
        #exit("exit exit");
        return boards;
Example #15
0
    def get_agent_moves(self, agent, game_id=None):
        # selects all moves
        if game_id is None:
            query = """SELECT turn_num, next_best_val, hand_val_before, move, hand_val_after
                       FROM Moves WHERE player_id='{0}'""".format(agent)
        else:
            query = """SELECT turn_num, next_best_val, hand_val_before, move, hand_val_after
                       FROM Moves WHERE player_id='{0}' AND game_id={1}""".format(
                agent, game_id)
        results = self.execute_queries(query, get_result=True)

        # convert moves from bit to move
        toReturn = []
        for result in results:
            record = list(result)
            move_as_move = Moves.convert_to_move(record[3])
            record[3] = move_as_move
            toReturn.append(record)
        return tuple(toReturn)
Example #16
0
 def process_NN_agent_action(self, game_num, all_hands, game_state,
                             episode_buffer, exp_buffer):
     explore_steps = self.parameters["explore_steps"]
     update_frequency = self.parameters["update_frequency"]
     exploring = (game_num <= explore_steps)
     action = self.NN.get_move(all_hands, exploring)
     self.process_action(action)
     new_game_state = self.get_train_game_state(all_hands)
     reward = self.gen_reward(action)
     action = Moves.convert_to_bit(action)
     # push action to buffer, for sampling later
     episode_buffer.append(
         np.reshape(
             np.array([
                 game_state, action, reward, new_game_state,
                 self.blackjack.continue_game
             ]), [1, 5]))
     if game_num % update_frequency == 0 and not exploring:
         self.NN.update_networks(exp_buffer)
     return action, new_game_state
 def get_move(self, *args):
     move_bit = randint(0, 1)
     return Moves.convert_to_move(move_bit)
Example #18
0
class IAPruning(object):
    def __init__(self, type):
        #sometimes, it try to preview a draw possibility, so it goes to the maximum depth recursion
        self.LIMIT_RECURSION_SECURITY = 200  #this constant is necessery to bypass this problem
        self.type = type
        self.mg = MoveGenerator(type)
        self.alpha = -sys.maxsize - 1
        self.beta = sys.maxsize
        self.lastMove = Moves()
        self.lastMoveHasCaptured = False
        self.counter = 0
        self.prunedCounter = 0

    def Max(self, board=Board(), moves=[], depth=0):
        v = -sys.maxsize - 1  #minint
        self.counter += 1
        if (moves[-1].hasCaptured()):  #if it has captured a piece last move
            #still playing
            cBoard = board.copyBoard()
            for move in moves:
                cBoard.executeMove(move)  #execute all last moves

            m = RuleEngine.possibleStates(cBoard, moves[-1].finalPosition)
            for move in m[0]:
                if (move.hasCaptured()):
                    moves.append(move)
                    auxV = self.Max(board, moves, depth + 1)
                    if auxV > v:
                        v = auxV
                    if auxV > self.alpha:
                        self.alpha = auxV
                    if auxV >= self.beta:  #pruning
                        self.prunedCounter += 1
                        break
                    moves.pop()
        else:
            #its the last move

            cBoard = board.copyBoard()
            for move in moves:
                cBoard.executeMove(move)  #execute all last moves

            if (board.isGameOver(self.mg)
                    or depth >= self.LIMIT_RECURSION_SECURITY):
                return self.mg.utility(board, cBoard)

            m = self.mg.possibleActions(cBoard)
            for possibleMove in m:
                auxV = self.Min(cBoard, [possibleMove], depth + 1)
                if auxV > v:
                    v = auxV
                if auxV > self.alpha:
                    self.alpha = auxV
                if auxV >= self.beta:  #pruning
                    self.prunedCounter += 1
                    break
        return v

    def Min(self, board=Board(), moves=[], depth=0):
        v = sys.maxsize  #maxint
        self.counter += 1
        if ((moves[-1]).hasCaptured()):  #if it has captured a piece last move
            #still playing
            cBoard = board.copyBoard()
            for move in moves:
                cBoard.executeMove(move)  #execute all last moves

            m = RuleEngine.possibleStates(cBoard, moves[-1].finalPosition)
            for move in m[0]:
                if (move.hasCaptured()):
                    moves.append(move)
                    auxV = self.Min(board, moves, depth + 1)
                    if auxV < v:
                        v = auxV
                    if auxV < self.beta:
                        self.beta = auxV
                    if auxV <= self.alpha:  #pruning
                        self.prunedCounter += 1
                        break
                    moves.pop()
        else:
            #its the last move

            cBoard = board.copyBoard()
            for move in moves:
                cBoard.executeMove(move)  #execute all last moves

            if (board.isGameOver(self.mg)
                    or depth >= self.LIMIT_RECURSION_SECURITY):
                return self.mg.utility(board, cBoard)

            m = self.mg.possibleOponentActions(cBoard)
            for possibleMove in m:
                auxV = self.Max(cBoard, [possibleMove], depth + 1)
                if auxV < v:
                    v = auxV
                if auxV < self.beta:
                    self.beta = auxV
                if auxV <= self.alpha:  #pruning
                    self.prunedCounter += 1
                    break
        return v

    def getMove(self, board=Board()):
        self.counter = 0
        self.prunedCounter = 0
        self.alpha = -sys.maxsize - 1
        self.beta = sys.maxsize
        moves = []
        if (self.lastMoveHasCaptured):
            ans = RuleEngine.possibleStates(board, self.lastMove.finalPosition)
            for move in ans[0]:
                if move.hasCaptured():
                    moves.append(move)
            self.lastMoveHasCaptured = False
        else:
            moves = self.mg.possibleActions(board)
        bestMoveIndex = []
        maxV = -sys.maxsize - 1
        for index in range(len(moves)):
            auxV = self.Min(board, [moves[index]])
            if auxV > maxV:
                maxV = auxV
                bestMoveIndex.clear()
                bestMoveIndex.append(index)
            elif auxV == maxV:
                bestMoveIndex.append(index)
        if (len(moves) > 0):
            if (len(bestMoveIndex) == 0):
                print(
                    "==========================ERROR=============================="
                )
                return False
            choose = randint(0, len(bestMoveIndex) - 1)
            self.lastMove = moves[bestMoveIndex[choose]]
            if (self.lastMove.hasCaptured()):
                self.lastMoveHasCaptured = True
            return moves[bestMoveIndex[choose]]
        else:
            if (self.lastMove.hasCaptured()):
                return Moves(Position(-1, -1))
            winner = board.winner(self.mg)
            if (winner == self.type):
                move = Moves()
                move.setWin()
                return move
            elif (winner != "."):
                move = Moves()
                move.setLost()
                return move
            print(
                "==========================ERROR=============================="
            )
            return False
Example #19
0
mcfFileName = sys.argv[1]
featModelFileName = sys.argv[2]
mcdFileName = sys.argv[3]
dicosFileName = sys.argv[4]
dataFileName = sys.argv[5]
wordsLimit = int(sys.argv[6])
verbose = False

print('reading mcd from file :', mcdFileName)
mcd = Mcd(mcdFileName)

print('reading dicos from file :', dicosFileName)
dicos = Dicos(fileName=dicosFileName)

# dicos.populateFromMcfFile(mcfFileName, mcd, verbose=False)
# print('saving dicos in file :', dicosFileName)
# dicos.printToFile(dicosFileName)

moves = Moves(dicos)

print('reading feature model from file :', featModelFileName)
featModel = FeatModel(featModelFileName, dicos)

inputSize = featModel.getInputSize()
outputSize = moves.getNb()
print('input size = ', inputSize, 'outputSize =', outputSize)

print('preparing training data')
prepareData(mcd, mcfFileName, featModel, moves, dataFileName, wordsLimit)
Example #20
0
def generate_move():
    choice = int(random.uniform(1, 5))
    return Moves(choice)
Example #21
0
 def getMove(self, board=Board()):
     moves = []
     playables = self.mg.playablePieces(board)
     if (len(playables) == 0):
         move = Moves()
         move.setLost()
         return move
     if (self.type == board.winner(self.mg)):
         move = Moves()
         move.setWin()
         return move
     if (self.lastMoveHasCaptured):
         move = []
         ans = RuleEngine.possibleStates(board, self.lastMove.finalPosition)
         for move in ans[0]:
             if move.hasCaptured():
                 moves.append(move)
         if (len(moves) == 0):
             print("Você não tem mais jogadas disponíveis!")
             self.lastMoveHasCaptured = False
             return Moves(Position(-1, -1))
     if (self.lastMoveHasCaptured):
         print("Saindo de " + self.lastMove.finalPosition.toString())
         startPos = self.lastMove.finalPosition
     else:
         print("Qual peça você quer mover? <linha> <coluna>")
         rightInput = False
         while (not rightInput):
             start = input().split()
             while (len(start) != 2):
                 print("Entrada inválida!")
                 start = input().split()
             try:
                 startPos = Position(int(start[0]), int(start[1]))
                 if (board.getPiece(startPos).lower() != self.type):
                     print("Você deve escolher uma peça sua para mover!")
                 else:
                     for pos in playables:
                         if (startPos.column == pos.column
                                 and startPos.row == pos.row):
                             rightInput = True
                             break
                     if (not rightInput):
                         print("Essa peça não pode ser movida!")
             except:
                 print("Entrada inválida!")
     #by this part, you already has an valid startPosition
     print("Para onde você quer ir? <linha> <coluna>")
     rightInput = False
     while (not rightInput):
         target = input().split()
         while (len(target) != 2):
             print("Dê uma entrada válida: ")
             target = input().split()
         try:
             targetPos = Position(int(target[0]), int(target[1]))
             if (len(moves) == 0):
                 ans = RuleEngine.possibleStates(board, startPos)
                 moves = ans[0]
             if (len(moves) == 0):  #if you dont have any move to do
                 move = Moves()
                 move.setLost()
                 return move
             for m in moves:
                 if (m.finalPosition.column == targetPos.column
                         and m.finalPosition.row == targetPos.row):
                     move = m
                     rightInput = True
             if (not rightInput):
                 print("Jogada inválida!")
         except:
             print("Entrada inválida!")
     print(move.toString())
     self.lastMoveHasCaptured = move.hasCaptured()
     self.lastMove = move
     return move
Example #22
0
model_file =     sys.argv[2]
dicos_file =     sys.argv[3]
feat_model =     sys.argv[4]
mcd_file =       sys.argv[5]
wordsLimit = int(sys.argv[6])

    
sys.stderr.write('reading mcd from file :')
sys.stderr.write(mcd_file)
sys.stderr.write('\n')
mcd = Mcd(mcd_file)

sys.stderr.write('loading dicos\n')
dicos = Dicos(fileName=dicos_file)

moves = Moves(dicos)

sys.stderr.write('reading feature model from file :')
sys.stderr.write(feat_model)
sys.stderr.write('\n')
featModel = FeatModel(feat_model, dicos)

sys.stderr.write('loading model :')
sys.stderr.write(model_file)
sys.stderr.write('\n')
model = load_model(model_file)

inputSize = featModel.getInputSize()
outputSize = moves.getNb()

c = Config(mcf_file, mcd, dicos)
Example #23
0
class Cube:
    def __init__(self, turns=None):
        self.moves = Moves()
        self.cube = [[" " for _ in range(9)] for _ in range(12)]
        self.turns = turns
        self.cycles = 0
        for x in range(len(self.cube)):
            for y in range(len(self.cube[x])):
                if x <= 2 and y in range(3, 6):
                    self.cube[x][y] = "W"
                elif x in range(3, 6) and y <= 2:
                    self.cube[x][y] = "R"
                elif x in range(3, 6) and y in range(2, 6):
                    self.cube[x][y] = "B"
                elif x in range(3, 6) and y >= 6:
                    self.cube[x][y] = "O"
                elif x in range(6, 9) and y in range(3, 6):
                    self.cube[x][y] = "Y"
                elif x in range(9, 13) and y in range(3, 6):
                    self.cube[x][y] = "G"
        self.solved = self.cube

    def __str__(self):
        return '\n'.join([' '.join(str(y) for y in row)
                          for row in self.cube]) + "\n"

    def move(self):

        self.turn()
        self.cycles += 1
        while self.cube != Cube.solved():
            print("Cycle: ", self.cycles)
            self.turn()
            self.cycles += 1
            if self.cycles == 6:
                print(self.__str__())
                break

    @staticmethod
    def solved():
        solved_cube = [[" " for _ in range(9)] for _ in range(12)]
        for x in range(len(solved_cube)):
            for y in range(len(solved_cube[x])):
                if x <= 2 and y in range(3, 6):
                    solved_cube[x][y] = "W"
                elif x in range(3, 6) and y <= 2:
                    solved_cube[x][y] = "R"
                elif x in range(3, 6) and y in range(2, 6):
                    solved_cube[x][y] = "B"
                elif x in range(3, 6) and y >= 6:
                    solved_cube[x][y] = "O"
                elif x in range(6, 9) and y in range(3, 6):
                    solved_cube[x][y] = "Y"
                elif x in range(9, 13) and y in range(3, 6):
                    solved_cube[x][y] = "G"

        return solved_cube

    def turn(self):
        top = ["U", "u", "White", "white", "Top", "top", "T", "t"]
        left = ["L", "l", "Left", "left"]
        right = ["R", "r", "Right", "right"]
        front = ["F", "f", "Front", "front"]
        back = ["B", "b", "Back", "back"]
        down = ["D", "d", "Down", "down"]
        for turn in self.turns:
            # top turns
            if turn in top:
                self.top()
            elif turn in [move + "\'" for move in top]:
                self.top(ccw=True)
            elif turn in [move + "2" for move in top]:
                self.top()
                self.top()

            # left turns
            elif turn in left:
                self.left()
            elif turn in [move + "\'" for move in left]:
                self.left(ccw=True)
            elif turn in [move + "2" for move in left]:
                self.left()
                self.left()

            # right turns
            elif turn in right:
                self.right()
            elif turn in [move + "\'" for move in right]:
                self.right(ccw=True)
            elif turn in [move + "2" for move in right]:
                self.right()
                self.right()

            # front turns
            elif turn in front:
                self.front()
            elif turn in [move + "\'" for move in front]:
                self.front(ccw=True)
            elif turn in [move + "2" for move in front]:
                self.front()
                self.front()

            # back turns
            elif turn in back:
                self.back()
            elif turn in [move + "\'" for move in back]:
                self.back(ccw=True)
            elif turn in [move + "2" for move in back]:
                self.back()
                self.back()

            # back turns
            elif turn in down:
                self.down()
            elif turn in [move + "\'" for move in down]:
                self.back(ccw=True)
            elif turn in [move + "2" for move in down]:
                self.down()
                self.down()

    def top(self, ccw=False):
        self.cube = self.moves.top(self.cube, ccw)

    def left(self, ccw=False):
        self.cube = self.moves.left(self.cube, ccw)

    def right(self, ccw=False):
        self.cube = self.moves.right(self.cube, ccw)

    def front(self, ccw=False):
        pass

    def back(self, ccw=False):
        pass

    def down(self, ccw=False):
        pass
    def possibleStates(boardClass=Board(), initialState=Position(0, 0)):
        ''' 
        This method will return all possible states for a piece on a list of Positions.
        Params: 
                board -> the current state of the board
                initialState -> position of actual state of the piece
        '''
        possibleMoves = []
        type = boardClass.getPiece(initialState)
        board = boardClass.getBoard()
        hasEverCapture = False

        if (type == "."):
            return possibleMoves, False
        if (
                type.isupper()
        ):  #its a double piece and it can move multiply spaces descrease and increaseingly
            #considering top-left
            j = (7 - initialState.row
                 ) if (7 - initialState.row
                       ) < initialState.column else initialState.column
            i = 1
            captureAnyPiece = False
            while (i <= j):
                #in case it found one piece from same colour
                if (board[initialState.row + i][initialState.column -
                                                i].lower() == type.lower()):
                    break
                #in case it found an empty space
                elif (board[initialState.row + i][initialState.column - i]
                      == "." and not captureAnyPiece):
                    possibleMoves.append(
                        Moves(
                            initialState,
                            Position(initialState.row + i,
                                     initialState.column - i), 0, False))

                #the only rest case, it found an piece to capture and tests if it can jump over
                elif (i < j and
                      (board[initialState.row + i][initialState.column -
                                                   i].lower() != type.lower()
                       or captureAnyPiece)):
                    if (board[initialState.row + i + 1][initialState.column -
                                                        i - 1] == "."):
                        possibleMoves.append(
                            Moves(
                                initialState,
                                Position(initialState.row + i + 1,
                                         initialState.column - i - 1), 1,
                                False))
                        hasEverCapture = True
                        captureAnyPiece = True
                    else:
                        break
                elif (captureAnyPiece
                      and board[initialState.row + i][initialState.column - i]
                      != "."):
                    break
                i += 1

            #considering top-right
            j = (7 - initialState.row
                 ) if (7 - initialState.row) < 7 - initialState.column else (
                     7 - initialState.column)
            i = 1
            captureAnyPiece = False
            while (i <= j):
                #in case it found one piece from same colour
                if (board[initialState.row + i][initialState.column +
                                                i].lower() == type.lower()):
                    break
                #in case it found an empty space
                elif (board[initialState.row + i][initialState.column + i]
                      == "." and not captureAnyPiece):
                    possibleMoves.append(
                        Moves(
                            initialState,
                            Position(initialState.row + i,
                                     initialState.column + i), 0, False))

                #the only rest case, it found an piece to capture and tests if it can jump over
                elif (i < j and
                      (board[initialState.row + i][initialState.column +
                                                   i].lower() != type.lower()
                       or captureAnyPiece)):
                    if (board[initialState.row + i + 1][initialState.column +
                                                        i + 1] == "."):
                        possibleMoves.append(
                            Moves(
                                initialState,
                                Position(initialState.row + i + 1,
                                         initialState.column + i + 1), 1,
                                False))
                        hasEverCapture = True
                        captureAnyPiece = True
                    else:
                        break
                elif (captureAnyPiece
                      and board[initialState.row + i][initialState.column + i]
                      != "."):
                    break
                i += 1

            #considering bottom-left
            j = (initialState.row
                 ) if (initialState.row) < initialState.column else (
                     initialState.column)
            i = 1
            captureAnyPiece = False
            while (i <= j):
                #in case it found one piece from same colour
                if (board[initialState.row - i][initialState.column -
                                                i].lower() == type.lower()):
                    break
                #in case it found an empty space
                elif (board[initialState.row - i][initialState.column - i]
                      == "." and not captureAnyPiece):
                    possibleMoves.append(
                        Moves(
                            initialState,
                            Position(initialState.row - i,
                                     initialState.column - i), 0, False))

                #the only rest case, it found an piece to capture and tests if it can jump over
                elif (i < j and
                      (board[initialState.row - i][initialState.column -
                                                   i].lower() != type.lower()
                       or captureAnyPiece)):
                    if (board[initialState.row - i - 1][initialState.column -
                                                        i - 1] == "."):
                        possibleMoves.append(
                            Moves(
                                initialState,
                                Position(initialState.row - i - 1,
                                         initialState.column - i - 1), 1,
                                False))
                        hasEverCapture = True
                        captureAnyPiece = True
                    else:
                        break
                elif (captureAnyPiece
                      and board[initialState.row - i][initialState.column - i]
                      != "."):
                    break
                i += 1

            #considering bottom-right
            j = (initialState.row
                 ) if (initialState.row) < 7 - initialState.column else (
                     7 - initialState.column)
            i = 1
            captureAnyPiece = False
            while (i <= j):
                #in case it found one piece from same colour
                if (board[initialState.row - i][initialState.column +
                                                i].lower() == type.lower()):
                    break
                #in case it found an empty space
                elif (board[initialState.row - i][initialState.column + i]
                      == "." and not captureAnyPiece):
                    possibleMoves.append(
                        Moves(
                            initialState,
                            Position(initialState.row - i,
                                     initialState.column + i), 0, False))

                #the only rest case, it found an piece to capture and tests if it can jump over
                elif (i < j and
                      (board[initialState.row - i][initialState.column +
                                                   i].lower() != type.lower()
                       or captureAnyPiece)):
                    if (board[initialState.row - i - 1][initialState.column +
                                                        i + 1] == "."):
                        possibleMoves.append(
                            Moves(
                                initialState,
                                Position(initialState.row - i - 1,
                                         initialState.column + i + 1), 1,
                                False))
                        hasEverCapture = True
                        captureAnyPiece = True
                    else:
                        break
                elif (captureAnyPiece
                      and board[initialState.row - i][initialState.column + i]
                      != "."):
                    break
                i += 1

        else:  #it is a single piece

            if (type.lower() == "b"):  #shoud be evaluate mostly increasingly

                if (initialState.row < 6):  #it still can capture other piece
                    #considering a capture
                    if (initialState.column < 6 and
                            board[initialState.row + 1][initialState.column +
                                                        1].lower() == "w"
                            and board[initialState.row +
                                      2][initialState.column + 2] == "."):
                        if (initialState.row +
                                2 == 7):  #it will also become double
                            possibleMoves.append(
                                Moves(
                                    initialState,
                                    Position(initialState.row + 2,
                                             initialState.column + 2), 1,
                                    True))
                        else:
                            possibleMoves.append(
                                Moves(
                                    initialState,
                                    Position(initialState.row + 2,
                                             initialState.column + 2), 1,
                                    False))
                        hasEverCapture = True

                    if (initialState.column > 1 and
                            board[initialState.row + 1][initialState.column -
                                                        1].lower() == "w"
                            and board[initialState.row +
                                      2][initialState.column - 2] == "."):
                        if (initialState.row +
                                2 == 7):  #it will also become double
                            possibleMoves.append(
                                Moves(
                                    initialState,
                                    Position(initialState.row + 2,
                                             initialState.column - 2), 1,
                                    True))
                        else:
                            possibleMoves.append(
                                Moves(
                                    initialState,
                                    Position(initialState.row + 2,
                                             initialState.column - 2), 1,
                                    False))
                        hasEverCapture = True

                    #considering only a simple diagonal move (without capture)
                    if (initialState.column < 7
                            and board[initialState.row +
                                      1][initialState.column + 1] == "."):
                        possibleMoves.append(
                            Moves(
                                initialState,
                                Position(initialState.row + 1,
                                         initialState.column + 1), 0, False))
                    if (initialState.column > 0
                            and board[initialState.row +
                                      1][initialState.column - 1] == "."):
                        possibleMoves.append(
                            Moves(
                                initialState,
                                Position(initialState.row + 1,
                                         initialState.column - 1), 0, False))

                else:  #now it can only become double
                    if (initialState.column < 7
                            and board[initialState.row +
                                      1][initialState.column + 1] == "."):
                        possibleMoves.append(
                            Moves(
                                initialState,
                                Position(initialState.row + 1,
                                         initialState.column + 1), 0, True))
                    if (initialState.column > 0
                            and board[initialState.row +
                                      1][initialState.column - 1] == "."):
                        possibleMoves.append(
                            Moves(
                                initialState,
                                Position(initialState.row + 1,
                                         initialState.column - 1), 0, True))

                if (initialState.row >
                        1):  #considering it can capture backward
                    if (initialState.column < 6 and
                            board[initialState.row - 1][initialState.column +
                                                        1].lower() == "w"
                            and board[initialState.row -
                                      2][initialState.column + 2] == "."):
                        possibleMoves.append(
                            Moves(
                                initialState,
                                Position(initialState.row - 2,
                                         initialState.column + 2), 1, False))
                        hasEverCapture = True
                    if (initialState.column > 1 and
                            board[initialState.row - 1][initialState.column -
                                                        1].lower() == "w"
                            and board[initialState.row -
                                      2][initialState.column - 2] == "."):
                        possibleMoves.append(
                            Moves(
                                initialState,
                                Position(initialState.row - 2,
                                         initialState.column - 2), 1, False))
                        hasEverCapture = True

            else:  #shoud be evaluate mostly decreasingly
                if (initialState.row > 1):  #it still can capture other piece
                    if (initialState.column < 6 and
                            board[initialState.row - 1][initialState.column +
                                                        1].lower() == "b"
                            and board[initialState.row -
                                      2][initialState.column + 2] == "."):
                        if (initialState.row -
                                2 == 0):  #it will also become double
                            possibleMoves.append(
                                Moves(
                                    initialState,
                                    Position(initialState.row - 2,
                                             initialState.column + 2), 1,
                                    True))
                        else:
                            possibleMoves.append(
                                Moves(
                                    initialState,
                                    Position(initialState.row - 2,
                                             initialState.column + 2), 1,
                                    False))
                        hasEverCapture = True

                    if (initialState.column > 1 and
                            board[initialState.row - 1][initialState.column -
                                                        1].lower() == "b"
                            and board[initialState.row -
                                      2][initialState.column - 2] == "."):
                        if (initialState.row -
                                2 == 0):  #it will also become double
                            possibleMoves.append(
                                Moves(
                                    initialState,
                                    Position(initialState.row - 2,
                                             initialState.column - 2), 1,
                                    True))
                        else:
                            possibleMoves.append(
                                Moves(
                                    initialState,
                                    Position(initialState.row - 2,
                                             initialState.column - 2), 1,
                                    False))
                        hasEverCapture = True

                    #considering only a simple diagonal move (without capture)
                    if (initialState.column < 7
                            and board[initialState.row -
                                      1][initialState.column + 1] == "."):
                        possibleMoves.append(
                            Moves(
                                initialState,
                                Position(initialState.row - 1,
                                         initialState.column + 1), 0, False))
                    if (initialState.column > 0
                            and board[initialState.row -
                                      1][initialState.column - 1] == "."):
                        possibleMoves.append(
                            Moves(
                                initialState,
                                Position(initialState.row - 1,
                                         initialState.column - 1), 0, False))

                else:  #now it can only become double
                    if (initialState.column < 7
                            and board[initialState.row +
                                      1][initialState.column + 1] == "."):
                        possibleMoves.append(
                            Moves(
                                initialState,
                                Position(initialState.row - 1,
                                         initialState.column + 1), 0, True))
                    if (initialState.column > 0
                            and board[initialState.row +
                                      1][initialState.column - 1] == "."):
                        possibleMoves.append(
                            Moves(
                                initialState,
                                Position(initialState.row - 1,
                                         initialState.column - 1), 0, True))

                if (initialState.row <
                        6):  #considering it can capture backward
                    if (initialState.column < 6 and
                            board[initialState.row + 1][initialState.column +
                                                        1].lower() == "b"
                            and board[initialState.row +
                                      2][initialState.column + 2] == "."):
                        possibleMoves.append(
                            Moves(
                                initialState,
                                Position(initialState.row + 2,
                                         initialState.column + 2), 1, False))
                        hasEverCapture = True
                    if (initialState.column > 1 and
                            board[initialState.row + 1][initialState.column -
                                                        1].lower() == "b"
                            and board[initialState.row +
                                      2][initialState.column - 2] == "."):
                        possibleMoves.append(
                            Moves(
                                initialState,
                                Position(initialState.row + 2,
                                         initialState.column - 2), 1, False))
                        hasEverCapture = True

        if (hasEverCapture
            ):  #if you can capture any piece, you must capture some piece
            for possibleMove in possibleMoves:
                if (not possibleMove.hasCaptured()):
                    possibleMoves.remove(possibleMove)

        return possibleMoves, hasEverCapture
class IAHeuristic(object):
    def __init__(self, type, depthLimit=6):
        self.DEPTH_LIMIT = depthLimit
        self.type = type
        self.mg = MoveGenerator(type)
        self.lastMove = Moves()
        self.lastMoveHasCaptured = False
        self.counter = 0
        self.prunedCounter = 0

    def Max(self, board=Board(), moves=[], depth=0):
        v = -sys.maxsize - 1  #minint
        self.counter += 1

        cBoard = board.copyBoard()
        for move in moves:
            cBoard.executeMove(move)  #execute all last moves

        if (depth >= self.DEPTH_LIMIT or cBoard.gameover):
            return self.mg.heuristic(cBoard, moves[-1])

        if (moves[-1].hasCaptured()):  #if it has captured a piece last move
            #still playing

            m = RuleEngine.possibleStates(cBoard, moves[-1].finalPosition)
            for move in m[0]:
                if (move.hasCaptured()):
                    moves.append(move)
                    auxV = self.Max(board, moves, depth + 1)
                    if auxV > v:
                        v = auxV
                    moves.pop()
        else:
            #its the last move

            m = self.mg.possibleActions(cBoard)
            for possibleMove in m:
                auxV = self.Min(cBoard, [possibleMove], depth + 1)
                if auxV > v:
                    v = auxV
        return v

    def Min(self, board=Board(), moves=[], depth=0):
        v = sys.maxsize  #maxint
        self.counter += 1

        cBoard = board.copyBoard()
        for move in moves:
            cBoard.executeMove(move)  #execute all last moves

        if (depth >= self.DEPTH_LIMIT or cBoard.gameover):
            return self.mg.heuristic(cBoard, moves[-1])

        if ((moves[-1]).hasCaptured()):  #if it has captured a piece last move
            #still playing

            m = RuleEngine.possibleStates(cBoard, moves[-1].finalPosition)
            for move in m[0]:
                if (move.hasCaptured()):
                    moves.append(move)
                    auxV = self.Min(board, moves, depth + 1)
                    if auxV < v:
                        v = auxV
                    moves.pop()
        else:
            #its the last move

            m = self.mg.possibleOponentActions(cBoard)
            for possibleMove in m:
                auxV = self.Max(cBoard, [possibleMove], depth + 1)
                if auxV < v:
                    v = auxV
        return v

    def getMove(self, board=Board()):
        self.counter = 0
        moves = []
        if (self.lastMoveHasCaptured):
            ans = RuleEngine.possibleStates(board, self.lastMove.finalPosition)
            for move in ans[0]:
                if move.hasCaptured():
                    moves.append(move)
            self.lastMoveHasCaptured = False
        else:
            moves = self.mg.possibleActions(board)
        bestMoveIndex = []
        maxV = -sys.maxsize - 1
        for index in range(len(moves)):
            auxV = self.Min(board, [moves[index]])
            if auxV > maxV:
                maxV = auxV
                bestMoveIndex.clear()
                bestMoveIndex.append(index)
            elif auxV == maxV:
                bestMoveIndex.append(index)
        if (len(moves) > 0):
            if (len(bestMoveIndex) == 0):
                print(
                    "==========================ERROR=============================="
                )
                return False
            choose = randint(0, len(bestMoveIndex) - 1)
            self.lastMove = moves[bestMoveIndex[choose]]
            if (self.lastMove.hasCaptured()):
                self.lastMoveHasCaptured = True
            return moves[bestMoveIndex[choose]]
        else:
            if (self.lastMove.hasCaptured()):
                return Moves(Position(-1, -1))
            winner = board.winner(self.mg)
            if (winner == self.type):
                move = Moves()
                move.setWin()
                return move
            elif (winner != "."):
                move = Moves()
                move.setLost()
                return move
            print(
                "==========================ERROR=============================="
            )
            return False