Beispiel #1
0
def chooseBestAttribute(data, attributes, target, criterion):
    # This function chooses the heuristic that must be applied in order to fulfill the
    # user's request. For each criterion there's a different call. Otherwise, it throws
    # an exception which stops the program execution.
    data = data[:]
    bestGain = 0.0
    bestAttr = None

    for attr in attributes:
        try:
            if criterion == 'gini':
                gainAttr = heur.gainGini(data, attr, target)
            elif criterion == 'entropy':
                gainAttr = heur.gainEntr(data, attr, target)
            elif criterion == 'missclass':
                gainAttr = heur.gainMisclass(data, attr, target)
            else:
                raise Exception('No criterion with such name.')
        except Exception as ex:
            print ex.args
        if (gainAttr >= bestGain and attr != target):
            bestGain = gainAttr
            bestAttr = attr

    return bestAttr
Beispiel #2
0
def coeff_train(game):
    coeff = [1, 1, 1]
    old_h = H.LinearCombinationHeuristic(coeff)
    pick = random.randint(0, 2)
    for i in range(0, 15):
        coeff[pick] += 1
        new_h = H.LinearCombinationHeuristic(coeff)
        pl1_score = 0
        pl2_score = 0
        print(coeff)
        print("--------------START GAME LOOP-----------------")
        for j in range(0, 10):
            print("----------------PLAY START-----------------")
            score = ai_vs_ai(game, new_h, old_h, 5, 5, False)
            if score == 1:
                pl1_score += 1
            elif score == 2:
                pl2_score += 2
            game.reset()

        if pl1_score > pl2_score:
            old_h = new_h
            print("PL1 wins")
        else:
            print("PL2 wins")
            new_pick = random.randint(0, 2)
            while new_pick == pick:
                new_pick = random.randint(0, 2)
            pick = new_pick
    print("--------------END GAME LOOP-------------------")
    print(coeff)
    return coeff
Beispiel #3
0
def checkInOpenList(toCompare):
    for i in range(len(open_list)):
        if np.array_equal(open_list[i].child_node.initialState,toCompare):
            if Heuristics.getHammingDist_GOAL(toCompare) < Heuristics.getHammingDist_GOAL(open_list[i].child_node.initialState):
                return i
            else:
                return -1 #ignore toComapre
    return -2 #insert as usual
Beispiel #4
0
def streak4OrDraw(board, move):

	if(Heuristics.checkForStreak(board,"red", 4) > 0 or Heuristics.checkForStreak(board,"yellow", 4) > 0):
		return True

	chip_count = 0
	for y in range(0, 6):
		for x in range (0, 7):
			if(board[x][y] != "empty"):
				chip_count += 1

	if (chip_count == 42):
		return True

	return False
Beispiel #5
0
def streak4OrDraw(board, move):

    if (Heuristics.checkForStreak(board, "red", 4) > 0
            or Heuristics.checkForStreak(board, "yellow", 4) > 0):
        return True

    chip_count = 0
    for y in range(0, 6):
        for x in range(0, 7):
            if (board[x][y] != "empty"):
                chip_count += 1

    if (chip_count == 42):
        return True

    return False
Beispiel #6
0
	def update_and_repaint(self, instance):
		if (self.game.mode == 0):
			status = self.game.updateBoard(int(instance.text))
			if ((status == "won") or (status == "draw")):
				self.repaint_board()
				return 

			self.repaint_board()

		elif (self.game.mode == 1):
			status1 = self.game.updateBoard(int(instance.text))
			if ((status1 == "won") or (status1 == "draw")):
				self.repaint_board()
				return 
			
			self.repaint_board()

			#cpu_move_num = mode_controller.human_vs_cpu(self.game)
			cpu_move_num = Heuristics.rando()
			status2 = self.game.updateBoard(cpu_move_num)
			if ((status2 == "won") or (status2 == "draw")):
				self.repaint_board()
				return 

			self.repaint_board()
Beispiel #7
0
    def update_and_repaint(self, instance):
        if (self.game.mode == 0):
            status = self.game.updateBoard(int(instance.text))
            if ((status == "won") or (status == "draw")):
                self.repaint_board()
                return

            self.repaint_board()

        elif (self.game.mode == 1):
            status1 = self.game.updateBoard(int(instance.text))
            if ((status1 == "won") or (status1 == "draw")):
                self.repaint_board()
                return

            self.repaint_board()

            #cpu_move_num = mode_controller.human_vs_cpu(self.game)
            cpu_move_num = Heuristics.rando()
            status2 = self.game.updateBoard(cpu_move_num)
            if ((status2 == "won") or (status2 == "draw")):
                self.repaint_board()
                return

            self.repaint_board()
def train():
    goal = [i + 1 for i in range(pow(size, 2) - 1)]
    goal.append(0)
    snake = get_snake(size)
    to_move = goal[snake.index(0)]
    to_remember = snake[goal.index(0)]
    goal = Node(goal, size)
    heu = Heuristics(['manhattan'], size, to_move, to_remember)
    for pattern in patterns:
        pdbs.append(train_pattern(goal, pattern, heu))
        print("DB CACHED")
Beispiel #9
0
 def trump_bidding_strategy(self, *args):
     max_score = None
     cont = None
     for symbol in CardSymbol:
         cont_num = Heuristics.approx_rounds_simple(self.player.cards,
                                                    symbol)
         score = self.game.contract_score(cont_num, cont_num)
         if max_score is None:
             max_score = score
             cont = WistContract(symbol, cont_num)
         elif score > max_score:
             max_score = score
             cont = WistContract(symbol, cont_num)
     if not self.game.trump_contract_legal(cont):
         return WistContract()
     else:
         return cont
Beispiel #10
0
def main(id_offer):
    """ Compute scores for all users given an offer

    :param: id_offer

    :return: Stringify object, sent to the client 
    """
    offer = db_loader.load_offer(id_offer)
    res = []
    if(offer):
        if(len(listUsers) > 0):
            for user in listUsers:
                res.append(mainH.computeHeurisitcs(user, offer))
            return json.dumps({'status': 200, 'message': 'OK', 'body': res})
        else:
            return json.dumps({'status':404, 'message': 'No user found in database'})
    else:
        return json.dumps({'status': 404, 'message': 'Offer not found in database'})
Beispiel #11
0
def getPath():
	global localdata
	global path
	global mapper
	global PATH
	cmap = CustomMap(img.imread(PATH))
	heuristics = Heuristics()
	search = Astar(cmap, heuristics)
	start = [localdata[0], localdata[1]]
	start = search.LocaltoGlobal(start[0],start[1])
	destination = [coordinates[0][0], coordinates[0][1]]
	destination = search.LocaltoGlobal(destination[0],destination[1])
	start = [start[0], start[1]]
	destination = [destination[0] , destination[1]]
	path = search.searchPath(start, destination)
	mapper.printpath(path)
	path = pixeltoglobal(path)
	path = dropWaypoints(path)
	addToDestinations(path)
	pixelToWaypoints()
Beispiel #12
0
def main():
    print("Sliding Puzzle Solver!\n")
    # Get size of the board from user
    size = int()
    while True:
        try:
            size = int(input("Insert the size of the board:"))
            if size < 2:
                raise ValueError
            else:
                break
        except ValueError:
            print("Insert a positive natural number > 1 !")
            continue

    game = G.Game(size)
    heuristic = H.Heuristics(game)

    inserted_value = str()
    inserted_position = []
    initial_state = None

    # Get the initial state (doesn't check the user input properly :()
    while not (inserted_value.upper() == 'Y') or (inserted_value.upper()
                                                  == 'N'):
        inserted_value = input(
            "Would you like to start from a random position (Y/N)?").upper()
        if inserted_value == 'Y':
            # Start with a random initial position
            game.shuffle()
            # Save the initial state/table
            initial_state = copy.deepcopy(game.state)
            break
        if inserted_value.upper() == 'N':
            for i in range(size**2):
                value = input(f"Insert the value number {i + 1}: ")
                try:
                    inserted_position.append(int(value))
                except ValueError:
                    print("Insert a positive natural number! Exiting ...")
                    break

            s = from_list_to_state(inserted_position, size)
            game.set_state(s)
            initial_state = copy.deepcopy(game.state)
            break

    game.set_state(initial_state)
    print("Initial state:")
    game.print()
    print()

    input("Press Enter to continue ...")
    starting_date = time.asctime(time.localtime(time.time()))
    print(f"Start searching at {starting_date}", )
    time.sleep(1)
    searching = True
    attempt = 1

    # Search routine
    while searching:
        searching = not search(game, heuristic, attempt)
        # If search return False executes the following if clause
        if searching:
            print("I'll try again from:")
            # Clean the game and set the previous initial state
            attempt += 1
            game.set_state(initial_state)
            game.explored = []
            game.state.previous_actions = []
            game.print()
            print()
            print("Start again in 2 seconds ...")
            time.sleep(2)
            # input("Press Enter to continue ...")
            searching = True
            continue
Beispiel #13
0
def GrowTree(dataset, attributes):
    global cnt_nonleaf_nodes,heuristic
    max_gain_attr =  None
    max_gain = 0.0
    gain = 0.0

    # print "Attributes ", attributes

    if not attributes:
        common_val = get_max_val(dataset.get("Class"))
        root = BTreeNode(str(common_val))
        root.left = None
        root.right = None

    else:

        if dataset.has_key('NA'):
            return BTreeNode(str(dataset.get('NA')))

        else:

            class_list = dataset.get("Class")
            # print class_list

            tmp_negcnt, tmp_poscnt = get_count(class_list)

            if tmp_poscnt == 0:
                print "class: all negative examples"
                # print class_list
                return BTreeNode('0')

            if tmp_negcnt == 0:
                print "class: all positive examples"
                # print class_list
                return BTreeNode('1')


            for val in attributes:

                neg_dict, pos_dict = Dataset.split_dataset(dataset, val)
                # print "Neg dict class" , neg_dict.get("Class")
                # print "Pos dict class" , pos_dict.get("Class")

                if heuristic == 0:
                    entropy_set = Heuristics.Entropy_Set(class_list)
                elif heuristic == 1:
                    variance_set = Heuristics.Variance_Impurity_Set(class_list)

                # print "Entropy set for ", val ,entropy_set

                member_list = dataset.get(val)
                if heuristic == 0:
                    entropy_member = Heuristics.Entropy_Members(dataset,neg_dict,pos_dict,member_list)
                elif heuristic == 1:
                    variance_member = Heuristics.Variance_Impurity_Members(dataset,neg_dict,pos_dict,member_list)
                # print "Entropy member for ",val,entropy_member

                if heuristic == 0:
                    gain = Heuristics.gain(entropy_set, entropy_member)
                elif heuristic == 1:
                    gain = Heuristics.gain(variance_set, variance_member)
                print "gain for ",val ,gain


                if bool([a for a in neg_dict.values() if a == []]):
                    print "Sub values empty - zero dataset"
                    common_val = get_max_val(dataset.get("Class"))
                    neg_dict = {}
                    neg_dict.update({'NA':common_val})

                elif bool([a for a in pos_dict.values() if a == []]):
                    print "Sub values empty - one dataset"
                    common_val = get_max_val(dataset.get("Class"))
                    pos_dict = {}
                    pos_dict.update({'NA':common_val})


                if gain >= max_gain:
                    max_gain = gain
                    max_gain_attr = val
                    root_zero_dataset = neg_dict
                    # print "inside max gain cal zeros ",val, neg_dict.get("Class")
                    root_one_dataset = pos_dict
                    # print "inside max gain cal ones ",val, pos_dict.get("Class")

                neg_dict = {}
                pos_dict = {}
                # print


            print "Maximum Information Gain: ",max_gain
            print "Node selected: " , max_gain_attr
            print "Zero Dataset: ", root_zero_dataset.get("Class")
            print "One Dataset: ", root_one_dataset.get("Class")

        root = BTreeNode(max_gain_attr)
        cnt_nonleaf_nodes += 1
        root.order = cnt_nonleaf_nodes
        root.subset = dataset

        if max_gain_attr in attributes:
            attributes.remove(max_gain_attr)

        if root != None:

            # if root.left:
                root.left = GrowTree(root_zero_dataset,attributes)
            # if root.right:
                root.right = GrowTree(root_one_dataset,attributes)


    return root
Beispiel #14
0
def get_latest_heuristic():
    """
    Returns the latest heuristic that was found with the genetic algorithm
    """
    return Heuristics.Main(weights=tuple(LATEST_VECTOR))
Beispiel #15
0
from Game import MancalaGame
import Heuristics as H
from time import time
import Utils
import random

PL1 = 0
PL2 = 7

HP = H.RelativePointsHeuristic()
HB = H.PebblesHeuristic()
HR = H.RightCellHeuristic()


def man_vs_ai(game, heuristic, depth):
    # make you play against an heuristic
    # PL1 is human, PL2 is AI
    game.state.print()
    move = Utils.choose_move()
    game.make_move(move, PL1)
    player = PL2
    counter = 0
    while not game.no_moves():
        counter += 1
        # game loop
        game.state.print()
        if player is PL2:
            t = time()
            # ai player
            val, move = Utils.alpha_beta(game.state,
                                         player,
Beispiel #16
0
    def start_mc(self, player_played = None):
        root = Node(self.GM)

        for i,move in enumerate(self.comp.current_cards):
            c = 0
            parent = root
            while True:
                # print(c)
                c+=1

                GMcopy = copy.deepcopy(parent.state)
                GMcopy.deck.random_shuffle()
                if c == 1:
                    comp_card = GMcopy.computer.throw_card(i + 1)
                    if player_played:
                        player_card = player_played
                    else:
                        player_card = GMcopy.player.throw_card(
                            random.choice([i + 1 for i in range(len(GMcopy.player.current_cards))]))
                else:
                    player_card = GMcopy.player.throw_card(
                        random.choice([i + 1 for i in range(len(GMcopy.player.current_cards))]))

                    comp_card = GMcopy.computer.throw_card(random.choice([i+1 for i in range(len(GMcopy.computer.current_cards))]))




                if self.turn:
                    winner = heur.check_cards(comp_card, player_card, GMcopy.main_card)
                else:
                    winner = heur.check_cards(player_card,comp_card,GMcopy.main_card)

                #computer wins
                if (winner and self.turn) or (not winner and not self.turn):
                    GMcopy.computer.add_to_loot(comp_card, player_card)
                    GMcopy.first = GMcopy.computer
                    GMcopy.second = GMcopy.player
                    self.turn = True
                else:
                    GMcopy.player.add_to_loot(comp_card, player_card)
                    GMcopy.second = GMcopy.computer
                    GMcopy.first = GMcopy.player
                    self.turn = False


                GMcopy.used_cards.append(comp_card)
                GMcopy.used_cards.append(player_card)

                if GMcopy.deck.check_if_deck_empty() is False:
                    card1, card2 = GMcopy.deck.deal_cards_on_turn()
                    GMcopy.computer.pick_up_card(card1)
                    GMcopy.player.pick_up_card(card2)

                child = Node(GMcopy, parent)
                parent.add_child(child)
                if c == 17:
                    print(1)
                if GMcopy.second.check_hand():
                    self.backpropagate(child)
                    break
                parent = child



        pass
Beispiel #17
0
            for cell in obj_list[r]:
                board[i + cell[0]][j + cell[1]] = 2 + obs
                cells += 1
            obs += 1
            break

    print("Number of objects : " + str(obs))
    print("Number of cells : " + str(cells))

    return board, obs


# Main
start_time = time.time()

heuristic = H.PianoMoverHeur()

# Instance generation
board, obj = get_starting_board(RATIO)
print(board)
print("\n")
game = G.PianoMoverGame(board, obj)

state0 = game.getState()
dicOfStates[state0] = heuristic.euclidean(state0)
solution = search(game, state0)

print("Start \n")

cost = 0
def GrowTree(dataset, attributes, level):

    print "Constructing Decision Tree" , level
    max_gain, max_gain_attr, level = 0, None, 0

    print "Attributes ", attributes

    if not attributes:
        common_val = get_max_val(dataset.get("Class"))
        root = BTreeNode(str(common_val))
        root.left = None
        root.right = None

    else:

        if dataset.has_key('NA'):
            return BTreeNode(str(dataset.get('NA')))

        else:

            class_list = dataset.get("Class")

            tmp_negcnt, tmp_poscnt = get_count(class_list)

            if tmp_poscnt == 0:
                print "class: all negative examples"
                return BTreeNode('0')

            if tmp_negcnt == 0:
                print "class: all positive examples"
                return BTreeNode('1')


            for val in attributes:

                neg_dict, pos_dict = Dataset.split_dataset(dataset, val)

                variance_set = Heuristics.Variance_Impurity_Set(class_list)

                print "Variance Impurity set for ", val ,variance_set

                member_list = dataset.get(val)
                variance_member = Heuristics.Variance_Impurity_Members(dataset,neg_dict,pos_dict,member_list)
                print "Variance Impurity member for ",val,variance_member

                var_gain = Heuristics.gain(variance_set, variance_member)
                print "Variance Impurity gain for ",val ,var_gain

                print "Bool value - zeros" , bool([a for a in neg_dict.values() if a == []])
                print "Bool value - ones" , bool([a for a in pos_dict.values() if a == []])

                if bool([a for a in neg_dict.values() if a == []]):
                    print "Sub values empty - zero dataset"
                    common_val = get_max_val(dataset.get("Class"))
                    neg_dict = {}
                    neg_dict.update({'NA':common_val})

                elif bool([a for a in pos_dict.values() if a == []]):
                    print "Sub values empty - one dataset"
                    common_val = get_max_val(dataset.get("Class"))
                    pos_dict = {}
                    pos_dict.update({'NA':common_val})


                if var_gain > max_gain:
                    max_gain = var_gain
                    max_gain_attr = val
                    root_zero_dataset = neg_dict
                    root_one_dataset = pos_dict

                else:
                    max_gain = var_gain
                    max_gain_attr = val
                    root_zero_dataset = neg_dict
                    root_one_dataset = pos_dict



            print "Maximum Information Gain: ",max_gain
            print "Node selected" , max_gain_attr
            print "Zero Dataset", root_zero_dataset
            print "One Dataset", root_one_dataset

        root = BTreeNode(max_gain_attr)

        if max_gain_attr in attributes:
            attributes.remove(max_gain_attr)

        if root != None:
            root.left = GrowTree(root_zero_dataset,attributes,level)
            root.right = GrowTree(root_one_dataset,attributes,level)


    level+= 1


    return root
Beispiel #19
0
        padre = padre.parent
    return reversed(lStates)


def search(game, state0):
    sHorizon = set([])
    sExplored = set([])
    sHorizon.add(state0)
    while (len(sHorizon) > 0):
        view = pick(sHorizon)
        if not (view is None):
            if game.solution(view):
                return backpath(view)
            sExplored.add(view)
            sHorizon = sHorizon | (game.neighbors(view) - sExplored)
    return None


# Main
heuristic = H.MissCannHeuristic()
game = G.MissCannGame(mr=5,
                      cr=5,
                      ml=0,
                      cl=0,
                      ship=True,
                      shipMax=2,
                      heuristic=heuristic)
state0 = game.getState()
dicOfStates[state0] = heuristic.H(state0)
solution = search(game, state0)
Beispiel #20
0
    [0, 12, 3, 0, 0],
    [0, 13, 0, 0, 0],
    [14, 0, 1, 0, 0],
]
# a 4x4 board with 1 as the smallest number, and 16 as the highest
hidatoBoard2 = [[0, 0, 0, 10], [14, 16, 0, 11], [0, 4, 8, 1], [5, 0, 0, 0]]
# a 5x5 board with 1 as the smallest number, and 25 as the highest
hidatoBoard3 = [
    [0, 0, 0, 0, 0],
    [0, 0, 12, 1, 2],
    [16, 0, 0, 10, 25],
    [0, 0, 0, 0, 24],
    [0, 0, 0, 21, 22],
]

heuristic = H.HidatoHeuristic()

start_time1 = time.time()

# example number 1
print("This is the first example given board:")
print('\n'.join(
    [''.join(['{:4}'.format(item) for item in row]) for row in hidatoBoard1]))

game1 = G.HidatoGame(hidatoBoard1, 1, 4, 2, heuristic=heuristic)
state0 = game1.getState()
dictOfStates[state0] = heuristic.H(state0)
solution1 = breadth_first_search(game1, state0)

print("This is the winning state board:")
print('\n'.join([
Beispiel #21
0
    def build(self,card_down = None):
        root = MinMaxNode(None, self.first_cards, self.second_cards, True)
        last_level_nodes = []
        if card_down:
            self.first_cards.append(card_down)

        #prva karta - prvi krog
        for card in self.first_cards:

            first_cards_left = self.first_cards[:]
            second_cards_left = self.second_cards[:]

            first_cards_left.pop(first_cards_left.index(card))
            n = MinMaxNode(card, first_cards_left, second_cards_left, True, root)
            root.children.append(n)
            #druga karta - prvi krog
            for card_1 in self.second_cards:
                second_cards_left_1 = second_cards_left[:]
                second_cards_left_1.pop(second_cards_left_1.index(card_1))
                # vrednost prvega kroga
                val1 = get_value(card, card_1)
                turn_winner = heur.check_cards(card,card_1,self.main_card)

                if(turn_winner):
                    turn_1_winner_cards = first_cards_left
                    turn_1_loser_cards = second_cards_left_1

                else:
                    turn_1_winner_cards = second_cards_left_1
                    turn_1_loser_cards = first_cards_left

                # shrani kdo je zmagal v zgodovini in koliko točk je dobil računalnik
                if (not card_down and not turn_winner) or (card_down and turn_winner):
                    computer_level_winner = [True]
                    computer_values = [val1]
                else:
                    computer_level_winner = [False]
                    computer_values = [-val1]
                if computer_level_winner[0]:
                    n_1 = MinMaxNode(card_1, turn_1_winner_cards, turn_1_loser_cards, computer_level_winner[0], n)
                else:
                    n_1 = MinMaxNode(card_1, turn_1_loser_cards, turn_1_winner_cards, computer_level_winner[0], n)
                n.children.append(n_1)

                for card_2 in turn_1_winner_cards:
                    turn_1_winner_cards_2 = turn_1_winner_cards[:]
                    turn_1_winner_cards_2.pop(turn_1_winner_cards_2.index(card_2))

                    #preveri če je komp zmagal ali ne
                    if (computer_level_winner[0]):
                        n_2 = MinMaxNode(card_2, turn_1_winner_cards_2, turn_1_loser_cards, computer_level_winner[0], n_1)
                    else:
                        n_2 = MinMaxNode(card_2, turn_1_loser_cards, turn_1_winner_cards_2, computer_level_winner[0], n_1)
                    n_1.children.append(n_2)


                    for card_3 in turn_1_loser_cards:
                        turn_1_loser_cards_3 = turn_1_loser_cards[:]
                        turn_1_loser_cards_3.pop(turn_1_loser_cards_3.index(card_3))
                        computer_level_winner_2 = computer_level_winner[::]
                        computer_values_2 = computer_values[::]
                        # Shrani če je v drugem krogu zmagal računalnik in koliko točk je dobil
                        val2 = get_value(card_2, card_3)
                        turn_winner_1 = heur.check_cards(card_2, card_3, self.main_card)

                        if (not computer_level_winner[0] and not turn_winner_1) or (computer_level_winner[0] and turn_winner_1):
                            computer_level_winner_2.append(True)
                            computer_values_2.append(int(val2))
                        else:
                            computer_level_winner_2.append(False)
                            computer_values_2.append(-int(val2))


                        if(computer_level_winner_2[1]):
                            n_3 = MinMaxNode(card_3, turn_1_winner_cards_2, turn_1_loser_cards_3, turn_winner_1, n_2)
                            turn_winner_2 = heur.check_cards(turn_1_winner_cards_2[0], turn_1_loser_cards_3[0],
                                                             self.main_card)
                        else:
                            n_3 = MinMaxNode(card_3, turn_1_loser_cards_3, turn_1_winner_cards_2, turn_winner_1,n_2)
                            turn_winner_2 = heur.check_cards(turn_1_loser_cards_3[0], turn_1_winner_cards_2[0],
                                                             self.main_card)

                        n_2.children.append(n_3)

                        val3 = int(get_value(turn_1_loser_cards_3[0], turn_1_winner_cards_2[0]))

                        if (not computer_level_winner_2[1] and not turn_winner_2) or (
                                computer_level_winner_2[1] and turn_winner_2):
                            computer_level_winner_2.append(True)
                            computer_values_2.append(val3)
                        else:
                            computer_level_winner_2.append(False)
                            computer_values_2.append(-val3)


                        n_3.value = int(sum(computer_values_2))
                        last_level_nodes.append(n_3)
        if card_down:
            self.doMiniMax(last_level_nodes, True, 4)
        else:
            self.doMiniMax(last_level_nodes, False, 4)
        self.tree = root
        if self.turn:
            self.enemy_move(self.turn)
            self.first_cards.pop(len(self.first_cards)-1)
        print("")
Beispiel #22
0
 def approx_rounds(self, idx):
     cards = self.game.players[idx].cards
     trump_symbol = self.game.trump_symbol
     return Heuristics.approx_rounds_simple(cards, trump_symbol)
Beispiel #23
0
import argparse

DEFAULT_NUM_PLAYERS = 4
RANDOM_AGENT = 'random'
ONE_MOVE_AGENT = 'onemove'
HUMAN_AGENT = 'human'
PROBABILITY_AGENT = 'prob'
MONTECARLO_AGENT = 'monte'
GENETIC_AGENT = 'genetic'
GENETIC_WEIGHTS = (0.77197979, 0.8782323, 0.07241402, 0.82772027, 0.45152069,
                   0.17718227, 0.37266962, 0.15663299, 0.19536229)
AGENTS = {
    RANDOM_AGENT:
    Agent.RandomAgent(),
    ONE_MOVE_AGENT:
    Agent.OneMoveHeuristicAgent(Heuristics.AmossComb1()),
    HUMAN_AGENT:
    Agent.HumanAgent(),
    PROBABILITY_AGENT:
    Agent.ProbabilityAgent(),
    MONTECARLO_AGENT:
    Agent.MonteCarloAgent(Heuristics.Everything()),
    GENETIC_AGENT:
    Agent.MonteCarloAgent(Heuristics.Everything(weights=GENETIC_WEIGHTS))
}
DEFAULT_AGENTS = [RANDOM_AGENT]
PLAYER_NAMES = ['Roy', 'Boaz', 'Oriane', 'Amoss']


def get_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser()
Beispiel #24
0
def game():
    board = [
        [' ', 'w', ' ', 'w', ' ', 'w', ' ', 'w'],
        ['w', ' ', 'w', ' ', 'w', ' ', 'w', ' '],
        [' ', 'w', ' ', 'w', ' ', 'w', ' ', 'w'],  # machine frontier
        [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
        [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
        ['k', ' ', 'k', ' ', 'k', ' ', 'k', ' '],  # human frontier
        [' ', 'k', ' ', 'k', ' ', 'k', ' ', 'k'],
        ['k', ' ', 'k', ' ', 'k', ' ', 'k', ' ']
    ]

    LEVEL = 3
    heuristic = H.CheckerHeuristic()
    rep = G.CheckerRepresentation(board)
    rep.setCurrentPlayer('w')
    curState = G.CheckerState(heuristic, rep)
    f = open("log", "w")
    f.close()

    while True:
        turn = 'w'  # machine
        curState.setCurrentPlayer(turn)
        states = curState.neighbors(
            turn
        )  # find possible moves from here (1 level deeper). these are first level TRIANGLES DOWN
        for s in states:
            print str(s)
        mx = -9999
        ix = None  # best state
        for s in states:  # in this loop I want to choose the best move
            start = time.time()
            h = heuristic.H(s, LEVEL, 'k',
                            mx)  # for each move, calculate heuristic value
            end = time.time()
            print "Time needed for heuristic: ", str((end - start))
            if h > mx:  # find best heuristic value (MAX one) and remember the corresponding state
                mx = h
                ix = s

        # generate a move in function of ix
        curState = ix
        print "MATRIX AFTER MACHINE MOVE:"
        print str(curState)
        f = open("log", "a")
        f.write(str(curState))
        f.close()

        # if machine has just moved a peg to the last line of human frontier (row 7) => add it to free set
        for i in range(0, 8):
            if curState.getRepresentation().getPiece(7, i) == 'w':
                curState.addToFree(7, i)

        # check if final break WHITE wins!
        if curState.solution() == 'machine':
            print "You lose"
            return

        turn = 'k'  # human
        curState.setCurrentPlayer(turn)
        movePossible = False
        while movePossible == False:
            s = input('Position of move start. [row.column]: ')
            s = str(s)
            r = int(s.split('.')[0])
            c = int(s.split('.')[1])
            s = input('Position of move end. [row.column]: ')
            s = str(s)
            re = int(s.split(".")[0])
            ce = int(s.split(".")[1])
            # is it feasible?
            movePossible = curState.isAdmissible(r, c, re, ce)
            if not movePossible:
                print "Move not admissible"

        curState = curState.makeMove(r, c, re, ce)
        print "RESULTING MATRIX:"
        print str(curState)
        f = open("log", "a")
        f.write(str(curState))
        f.close()
        # check if final break BLACK wins!
        if curState.solution() == 'human':
            print "You win"
            return

        time.sleep(3)
Beispiel #25
0
    return -2  #insert as usual


start_time = time.time()

fileNum = 0
for initialConfig in readInputFile.getPuzzles('puzzles.txt', (2, 4)):
    goalNum = 1
    init_state = np.array(initialConfig)

    #GBS initial phase
    #H1: Hamming Distance - GOAL1
    puzzleIni = XPuzzle.XPuzzle(init_state)
    open_list = [
        Node(puzzleIni, None,
             Heuristics.getHammingDist_GOAL(init_state, goalNum), None, 0)
    ]
    closed_list = []

    #end time is set after 60 seconds
    t_end = time.time() + 60
    count = 0
    IsASol = False
    while time.time() < t_end:
        if len(open_list) == 0:  #check if open_list is empty
            print("No solution")
            break

        #pop the least cost element in the open_list and push it to hte closed_list
        closed_list.append(open_list.pop(0))
        nodeToGenerateChildren = closed_list[len(closed_list) - 1]
Beispiel #26
0
 def contract_bidding_strategy(self, *args):
     cont = Heuristics.approx_rounds_simple(self.player.cards,
                                            self.game.trump_symbol)
     if cont not in self.game.legal_contracts():
         cont = cont + 1
     return cont
Beispiel #27
0
 def __init__(self, in_ini, in_env):
     self.frontier = [in_ini]
     self.env = in_env
     self.visited = []
     self.heu_calc = heu.AltHeuristic(self.env)
Beispiel #28
0

if __name__ == "__main__":
	draws = 0
	red_wins = 0
	red_losses = 0

	num_games_to_play = 20

	connect4_game = connect4.Connect4()
	first_turns = True 
	while (num_games_to_play > 0): 

		print "cpu1 thinking"
		if (first_turns): # introduce random variation 
			cpu1_move_num = Heuristics.rando()
		else:	
			cpu1_move_num = cpu1(connect4_game)
		

		status = connect4_game.updateBoard(cpu1_move_num)
		if (status == "red won"):
			red_wins += 1
			num_games_to_play -= 1
			first_turns = True
			connect4_game = connect4.Connect4()
			continue 

		if (status == "yellow won"):
			red_losses += 1
			num_games_to_play -= 1
Beispiel #29
0
    def random_game(self, GM, move, turn, leftOver = False):
        # print(len(GM.player.current_cards), len(GM))
        main_card = GM.main_card
        deck = GM.deck
        # print(len(deck.deck))
        if leftOver:
            card1_playing = GM.player.card_down
            card2_playing = move
            # print(len(GM.player.current_cards), "zacetek1")
            # print(len(GM.computer.current_cards), "zacetek2")
            if heur.check_cards(card1_playing, card2_playing, main_card):
                GM.player.add_to_loot(card1_playing, card2_playing)
                turn = 2
                if deck.check_if_deck_empty() is False:
                    card1, card2 = deck.deal_cards_on_turn()
                    GM.player.pick_up_card(card1)
                    GM.computer.pick_up_card(card2)
            else:
                GM.computer.add_to_loot(card1_playing, card2_playing)
                turn = 1
                if deck.check_if_deck_empty() is False:
                    card1, card2 = deck.deal_cards_on_turn()
                    GM.computer.pick_up_card(card1)
                    GM.player.pick_up_card(card2)
            # random = randint(1, len(GM.computer.current_cards))
        if turn == 1:
            first = GM.computer
            second = GM.player
        else:
            second = GM.computer
            first = GM.player
        # if len(first.current_cards) == 0 or len(second.current_cards) == 0:

        first_turn = True
        while True:
            card1_playing = None
            card2_playing = None
            if first_turn:
                first_turn = False
                if turn == 1:
                    card1_playing = move
                    player2_pick = randint(1, len(second.current_cards))
                    card2_playing = second.throw_card(int(player2_pick))
                    # print(card1_playing, card2_playing)
                elif turn == 2:
                    card2_playing = move
                    player1_pick = randint(1, len(first.current_cards))
                    card1_playing = first.throw_card(int(player1_pick))
            else:
                # print(len(first.current_cards), len(second.current_cards))
                player1_pick = randint(1, len(first.current_cards))
                card1_playing = first.throw_card(int(player1_pick))
                # print(card1_playing)
                player2_pick = randint(1, len(second.current_cards))
                # print(player2_pick, len())
                card2_playing = second.throw_card(int(player2_pick))
                # print(card2_playing)

            if heur.check_cards(card1_playing, card2_playing, main_card):
                first.add_to_loot(card1_playing, card2_playing)
            else:
                second.add_to_loot(card1_playing, card2_playing)
                tmp = first
                first = second
                second = tmp

            if deck.check_if_deck_empty() is False:
                card1, card2 = deck.deal_cards_on_turn()
                first.pick_up_card(card1)
                second.pick_up_card(card2)
            if first.check_hand() or second.check_hand():
                # print("pride")
                # print(deck.check_if_deck_empty())
                # print(len(first.current_cards),"prvi")
                # print(len(second.current_cards), "drugi")
                break

        if first.score > second.score:
            if first.name == 'Computer':
                return 1
            return -1
            # print(first.name+" has won the game because he collected more points!")
        elif first.score < second.score:
            if second.name == 'Computer':
                return 1
            return -1
            # print(second.name + " has won the game because he collected more points!")
        else:
            return 0
Beispiel #30
0
def vec_to_agent(vector):
    """
    Returns a new agent based on the given vector
    """
    heur = Heuristics.Main(weights=tuple(vector))
    return Agent.OneMoveHeuristicAgent(heuristic=heur)
    def neighbors(self, state, rep_alfa, rep_beta):
        heuristic = H.RubikCubeHeuristics()
        out = set([])
        # GENERO PASSI SUCCESSIVI RAGGIUNGIBILI

        #    ROTAZIONE ORARIA PANNELLO LATERALE SINISTRO
        rep_beta = RubikCubeRepresentation([
            state.representation.retro[6], state.representation.alto[1],
            state.representation.alto[2], state.representation.retro[3],
            state.representation.alto[4], state.representation.alto[5],
            state.representation.retro[0], state.representation.alto[7],
            state.representation.alto[8]
        ], [
            state.representation.fronte[0], state.representation.basso[1],
            state.representation.basso[2], state.representation.fronte[3],
            state.representation.basso[4], state.representation.basso[5],
            state.representation.fronte[6], state.representation.basso[7],
            state.representation.basso[8]
        ], [
            state.representation.sinistra[6], state.representation.sinistra[3],
            state.representation.sinistra[0], state.representation.sinistra[7],
            state.representation.sinistra[4], state.representation.sinistra[1],
            state.representation.sinistra[8], state.representation.sinistra[5],
            state.representation.sinistra[2]
        ], state.representation.destra, [
            state.representation.alto[0], state.representation.fronte[1],
            state.representation.fronte[2], state.representation.alto[3],
            state.representation.fronte[4], state.representation.fronte[5],
            state.representation.alto[6], state.representation.fronte[7],
            state.representation.fronte[8]
        ], [
            state.representation.basso[6], state.representation.retro[1],
            state.representation.retro[2], state.representation.basso[3],
            state.representation.retro[4], state.representation.retro[5],
            state.representation.basso[0], state.representation.retro[7],
            state.representation.retro[8]
        ])
        n = RubikCubeState(
            state, rep_beta.alto, rep_beta.basso, rep_beta.sinistra,
            rep_beta.destra, rep_beta.fronte, rep_beta.retro,
            heuristic.H(rep_beta)
        )  #euristica lavora su una rappresentazione di stato non sullo stato direttamente
        out.add(n)

        #   ROTAZIONE ANTIORARIA PANNELLO LATERALE SINISTRO
        rep_beta = RubikCubeRepresentation([
            state.representation.fronte[0], state.representation.alto[1],
            state.representation.alto[2], state.representation.fronte[3],
            state.representation.alto[4], state.representation.alto[5],
            state.representation.fronte[6], state.representation.alto[7],
            state.representation.alto[8]
        ], [
            state.representation.retro[6], state.representation.basso[1],
            state.representation.basso[2], state.representation.retro[3],
            state.representation.basso[4], state.representation.basso[5],
            state.representation.retro[0], state.representation.basso[7],
            state.representation.basso[8]
        ], [
            state.representation.sinistra[2], state.representation.sinistra[5],
            state.representation.sinistra[8], state.representation.sinistra[1],
            state.representation.sinistra[4], state.representation.sinistra[7],
            state.representation.sinistra[0], state.representation.sinistra[3],
            state.representation.sinistra[6]
        ], state.representation.destra, [
            state.representation.basso[0], state.representation.fronte[1],
            state.representation.fronte[2], state.representation.basso[3],
            state.representation.fronte[4], state.representation.fronte[5],
            state.representation.basso[6], state.representation.fronte[7],
            state.representation.fronte[8]
        ], [
            state.representation.alto[6], state.representation.retro[1],
            state.representation.retro[2], state.representation.alto[3],
            state.representation.retro[4], state.representation.retro[5],
            state.representation.alto[0], state.representation.retro[7],
            state.representation.retro[8]
        ])
        n = RubikCubeState(
            state, rep_beta.alto, rep_beta.basso, rep_beta.sinistra,
            rep_beta.destra, rep_beta.fronte, rep_beta.retro,
            heuristic.H(rep_beta)
        )  #euristica lavora su una rappresentazione di stato non sullo stato direttamente
        out.add(n)

        #   ROTAZIONE ORARIA PANNELLO LATERALE DESTRO (alto,basso, sinistra, destra, fronte, retro)
        rep_beta = RubikCubeRepresentation([
            state.representation.alto[0], state.representation.alto[1],
            state.representation.fronte[2], state.representation.alto[3],
            state.representation.alto[4], state.representation.fronte[5],
            state.representation.alto[6], state.representation.alto[7],
            state.representation.alto[8]
        ], [
            state.representation.basso[0], state.representation.basso[1],
            state.representation.retro[8], state.representation.basso[3],
            state.representation.basso[4], state.representation.retro[5],
            state.representation.basso[6], state.representation.basso[7],
            state.representation.retro[2]
        ], state.representation.sinistra, [
            state.representation.destra[6], state.representation.destra[3],
            state.representation.destra[0], state.representation.destra[7],
            state.representation.destra[4], state.representation.destra[1],
            state.representation.destra[8], state.representation.destra[5],
            state.representation.destra[2]
        ], [
            state.representation.fronte[0], state.representation.fronte[1],
            state.representation.basso[2], state.representation.fronte[3],
            state.representation.fronte[4], state.representation.basso[5],
            state.representation.fronte[6], state.representation.fronte[7],
            state.representation.basso[8]
        ], [
            state.representation.retro[0], state.representation.retro[1],
            state.representation.alto[8], state.representation.retro[3],
            state.representation.retro[4], state.representation.alto[5],
            state.representation.retro[6], state.representation.retro[7],
            state.representation.alto[2]
        ])
        n = RubikCubeState(
            state, rep_beta.alto, rep_beta.basso, rep_beta.sinistra,
            rep_beta.destra, rep_beta.fronte, rep_beta.retro,
            heuristic.H(rep_beta)
        )  #euristica lavora su una rappresentazione di stato non sullo stato direttamente
        out.add(n)

        #   ROTAZIONE ANTIORARIA PANELLO LATERALE DESTRO
        rep_beta = RubikCubeRepresentation([
            state.representation.alto[0], state.representation.alto[1],
            state.representation.retro[8], state.representation.alto[3],
            state.representation.alto[4], state.representation.retro[5],
            state.representation.alto[6], state.representation.alto[7],
            state.representation.retro[2]
        ], [
            state.representation.basso[0], state.representation.basso[1],
            state.representation.fronte[2], state.representation.basso[3],
            state.representation.basso[4], state.representation.fronte[5],
            state.representation.basso[6], state.representation.basso[7],
            state.representation.fronte[8]
        ], state.representation.sinistra, [
            state.representation.destra[2], state.representation.destra[5],
            state.representation.destra[8], state.representation.destra[1],
            state.representation.destra[4], state.representation.destra[7],
            state.representation.destra[0], state.representation.destra[3],
            state.representation.destra[6]
        ], [
            state.representation.fronte[0], state.representation.fronte[1],
            state.representation.alto[2], state.representation.fronte[3],
            state.representation.fronte[4], state.representation.alto[5],
            state.representation.fronte[6], state.representation.fronte[7],
            state.representation.alto[8]
        ], [
            state.representation.retro[0], state.representation.retro[1],
            state.representation.basso[8], state.representation.retro[3],
            state.representation.retro[4], state.representation.basso[5],
            state.representation.retro[6], state.representation.retro[7],
            state.representation.basso[2]
        ])
        n = RubikCubeState(
            state, rep_beta.alto, rep_beta.basso, rep_beta.sinistra,
            rep_beta.destra, rep_beta.fronte, rep_beta.retro,
            heuristic.H(rep_beta)
        )  #euristica lavora su una rappresentazione di stato non sullo stato direttamente
        out.add(n)

        #   ROTAZIONE ORARIA PANNELLO SUPERIORE
        rep_beta = RubikCubeRepresentation([
            state.representation.alto[6], state.representation.alto[3],
            state.representation.alto[0], state.representation.alto[7],
            state.representation.alto[4], state.representation.alto[1],
            state.representation.alto[8], state.representation.alto[5],
            state.representation.alto[2]
        ], state.representation.basso, [
            state.representation.fronte[0], state.representation.fronte[1],
            state.representation.fronte[2], state.representation.sinistra[3],
            state.representation.sinistra[4], state.representation.sinistra[5],
            state.representation.sinistra[6], state.representation.sinistra[7],
            state.representation.sinistra[8]
        ], [
            state.representation.retro[8], state.representation.retro[7],
            state.representation.retro[6], state.representation.destra[3],
            state.representation.destra[4], state.representation.destra[5],
            state.representation.destra[6], state.representation.destra[7],
            state.representation.destra[8]
        ], [
            state.representation.destra[0], state.representation.destra[1],
            state.representation.destra[2], state.representation.fronte[3],
            state.representation.fronte[4], state.representation.fronte[5],
            state.representation.fronte[6], state.representation.fronte[7],
            state.representation.fronte[8]
        ], [
            state.representation.retro[0], state.representation.retro[1],
            state.representation.retro[2], state.representation.retro[3],
            state.representation.retro[4], state.representation.retro[5],
            state.representation.sinistra[2], state.representation.sinistra[1],
            state.representation.sinistra[0]
        ])
        n = RubikCubeState(
            state, rep_beta.alto, rep_beta.basso, rep_beta.sinistra,
            rep_beta.destra, rep_beta.fronte, rep_beta.retro,
            heuristic.H(rep_beta)
        )  #euristica lavora su una rappresentazione di stato non sullo stato direttamente
        out.add(n)

        #   ROTAZIONE ANTIORARIA PANNELLO SUPERIORE
        rep_beta = RubikCubeRepresentation([
            state.representation.alto[2], state.representation.alto[5],
            state.representation.alto[8], state.representation.alto[1],
            state.representation.alto[4], state.representation.alto[7],
            state.representation.alto[0], state.representation.alto[3],
            state.representation.alto[6]
        ], state.representation.basso, [
            state.representation.retro[8], state.representation.retro[7],
            state.representation.retro[6], state.representation.sinistra[3],
            state.representation.sinistra[4], state.representation.sinistra[5],
            state.representation.sinistra[6], state.representation.sinistra[7],
            state.representation.sinistra[8]
        ], [
            state.representation.fronte[0], state.representation.fronte[1],
            state.representation.fronte[2], state.representation.destra[3],
            state.representation.destra[4], state.representation.destra[5],
            state.representation.destra[6], state.representation.destra[7],
            state.representation.destra[8]
        ], [
            state.representation.sinistra[0], state.representation.sinistra[1],
            state.representation.sinistra[2], state.representation.fronte[3],
            state.representation.fronte[4], state.representation.fronte[5],
            state.representation.fronte[6], state.representation.fronte[7],
            state.representation.fronte[8]
        ], [
            state.representation.retro[0], state.representation.retro[1],
            state.representation.retro[2], state.representation.retro[3],
            state.representation.retro[4], state.representation.retro[5],
            state.representation.destra[2], state.representation.destra[1],
            state.representation.destra[0]
        ])
        n = RubikCubeState(
            state, rep_beta.alto, rep_beta.basso, rep_beta.sinistra,
            rep_beta.destra, rep_beta.fronte, rep_beta.retro,
            heuristic.H(rep_beta)
        )  #euristica lavora su una rappresentazione di stato non sullo stato direttamente
        out.add(n)

        #   ROTAZIONE ORARIA PANNELLO INFERIORE
        rep_beta = RubikCubeRepresentation(state.representation.alto, [
            state.representation.basso[6], state.representation.basso[3],
            state.representation.basso[0], state.representation.basso[7],
            state.representation.basso[4], state.representation.basso[1],
            state.representation.basso[8], state.representation.basso[5],
            state.representation.basso[2]
        ], [
            state.representation.sinistra[0], state.representation.sinistra[1],
            state.representation.sinistra[2], state.representation.sinistra[3],
            state.representation.sinistra[4], state.representation.sinistra[5],
            state.representation.fronte[6], state.representation.fronte[7],
            state.representation.fronte[8]
        ], [
            state.representation.destra[0], state.representation.destra[1],
            state.representation.destra[2], state.representation.destra[3],
            state.representation.destra[4], state.representation.destra[5],
            state.representation.retro[2], state.representation.retro[1],
            state.representation.retro[0]
        ], [
            state.representation.fronte[0], state.representation.fronte[1],
            state.representation.fronte[2], state.representation.fronte[3],
            state.representation.fronte[4], state.representation.fronte[5],
            state.representation.destra[6], state.representation.destra[7],
            state.representation.destra[8]
        ], [
            state.representation.sinistra[8], state.representation.sinistra[7],
            state.representation.sinistra[6], state.representation.retro[3],
            state.representation.retro[4], state.representation.retro[5],
            state.representation.retro[6], state.representation.retro[7],
            state.representation.retro[8]
        ])
        n = RubikCubeState(
            state, rep_beta.alto, rep_beta.basso, rep_beta.sinistra,
            rep_beta.destra, rep_beta.fronte, rep_beta.retro,
            heuristic.H(rep_beta)
        )  #euristica lavora su una rappresentazione di stato non sullo stato direttamente
        out.add(n)

        #   ROTAZIONE ANTIORARIA PANNELLO INFERIORE
        rep_beta = RubikCubeRepresentation(state.representation.alto, [
            state.representation.basso[2], state.representation.basso[5],
            state.representation.basso[8], state.representation.basso[1],
            state.representation.basso[4], state.representation.basso[7],
            state.representation.basso[0], state.representation.basso[3],
            state.representation.basso[6]
        ], [
            state.representation.retro[0], state.representation.sinistra[1],
            state.representation.sinistra[2], state.representation.retro[3],
            state.representation.sinistra[4], state.representation.sinistra[5],
            state.representation.retro[6], state.representation.sinistra[7],
            state.representation.sinistra[8]
        ], [
            state.representation.fronte[0], state.representation.destra[1],
            state.representation.destra[2], state.representation.fronte[3],
            state.representation.destra[4], state.representation.destra[5],
            state.representation.fronte[6], state.representation.destra[7],
            state.representation.destra[8]
        ], [
            state.representation.sinistra[0], state.representation.fronte[1],
            state.representation.fronte[2], state.representation.sinistra[3],
            state.representation.fronte[4], state.representation.fronte[5],
            state.representation.sinistra[6], state.representation.fronte[7],
            state.representation.fronte[8]
        ], [
            state.representation.destra[6], state.representation.retro[1],
            state.representation.retro[2], state.representation.destra[3],
            state.representation.retro[4], state.representation.retro[5],
            state.representation.destra[3], state.representation.retro[7],
            state.representation.retro[8]
        ])
        n = RubikCubeState(
            state, rep_beta.alto, rep_beta.basso, rep_beta.sinistra,
            rep_beta.destra, rep_beta.fronte, rep_beta.retro,
            heuristic.H(rep_beta)
        )  #euristica lavora su una rappresentazione di stato non sullo stato direttamente
        out.add(n)

        #   ROTAZIONE ORARIA PANNELLO FRONTALE
        rep_beta = RubikCubeRepresentation([
            state.representation.alto[0], state.representation.alto[1],
            state.representation.alto[2], state.representation.alto[3],
            state.representation.alto[4], state.representation.alto[5],
            state.representation.sinistra[8], state.representation.sinistra[5],
            state.representation.sinistra[2]
        ], [
            state.representation.destra[6], state.representation.destra[3],
            state.representation.destra[0], state.representation.basso[3],
            state.representation.basso[4], state.representation.basso[5],
            state.representation.basso[6], state.representation.basso[7],
            state.representation.basso[8]
        ], [
            state.representation.sinistra[0], state.representation.sinistra[1],
            state.representation.basso[0], state.representation.sinistra[3],
            state.representation.sinistra[4], state.representation.basso[1],
            state.representation.sinistra[6], state.representation.sinistra[7],
            state.representation.basso[2]
        ], [
            state.representation.alto[6], state.representation.destra[1],
            state.representation.destra[2], state.representation.alto[7],
            state.representation.destra[4], state.representation.destra[5],
            state.representation.alto[8], state.representation.destra[7],
            state.representation.destra[8]
        ], [
            state.representation.fronte[6], state.representation.fronte[3],
            state.representation.fronte[0], state.representation.fronte[7],
            state.representation.fronte[4], state.representation.fronte[1],
            state.representation.fronte[8], state.representation.fronte[5],
            state.representation.fronte[2]
        ], state.representation.retro)
        n = RubikCubeState(
            state, rep_beta.alto, rep_beta.basso, rep_beta.sinistra,
            rep_beta.destra, rep_beta.fronte, rep_beta.retro,
            heuristic.H(rep_beta)
        )  #euristica lavora su una rappresentazione di stato non sullo stato direttamente
        out.add(n)

        #   ROTAZIONE ANTIORARIA PANNELLO FRONTALE
        rep_beta = RubikCubeRepresentation([
            state.representation.alto[0], state.representation.alto[1],
            state.representation.alto[2], state.representation.alto[3],
            state.representation.alto[4], state.representation.alto[5],
            state.representation.destra[0], state.representation.destra[3],
            state.representation.destra[6]
        ], [
            state.representation.sinistra[2], state.representation.sinistra[5],
            state.representation.sinistra[8], state.representation.basso[3],
            state.representation.basso[4], state.representation.basso[5],
            state.representation.basso[6], state.representation.basso[7],
            state.representation.basso[8]
        ], [
            state.representation.sinistra[0], state.representation.sinistra[1],
            state.representation.alto[8], state.representation.sinistra[3],
            state.representation.sinistra[4], state.representation.alto[7],
            state.representation.sinistra[6], state.representation.sinistra[7],
            state.representation.alto[6]
        ], [
            state.representation.basso[2], state.representation.destra[1],
            state.representation.destra[2], state.representation.basso[1],
            state.representation.destra[4], state.representation.destra[5],
            state.representation.basso[0], state.representation.destra[7],
            state.representation.destra[8]
        ], [
            state.representation.fronte[2], state.representation.fronte[5],
            state.representation.fronte[8], state.representation.fronte[1],
            state.representation.fronte[4], state.representation.fronte[7],
            state.representation.fronte[0], state.representation.fronte[3],
            state.representation.fronte[6]
        ], state.representation.retro)
        n = RubikCubeState(
            state, rep_beta.alto, rep_beta.basso, rep_beta.sinistra,
            rep_beta.destra, rep_beta.fronte, rep_beta.retro,
            heuristic.H(rep_beta)
        )  #euristica lavora su una rappresentazione di stato non sullo stato direttamente
        out.add(n)

        #   ROTAZIONE ORARIA PANNELLO POSTERIORE
        rep_beta = RubikCubeRepresentation([
            state.representation.destra[2], state.representation.destra[5],
            state.representation.destra[8], state.representation.alto[3],
            state.representation.alto[4], state.representation.alto[5],
            state.representation.alto[6], state.representation.alto[7],
            state.representation.alto[8]
        ], [
            state.representation.basso[0], state.representation.basso[1],
            state.representation.basso[2], state.representation.basso[3],
            state.representation.basso[4], state.representation.basso[5],
            state.representation.sinistra[0], state.representation.sinistra[3],
            state.representation.sinistra[6]
        ], [
            state.representation.alto[2], state.representation.sinistra[1],
            state.representation.sinistra[2], state.representation.alto[1],
            state.representation.sinistra[4], state.representation.sinistra[5],
            state.representation.alto[2], state.representation.sinistra[7],
            state.representation.sinistra[8]
        ], [
            state.representation.destra[0], state.representation.destra[1],
            state.representation.basso[6], state.representation.destra[3],
            state.representation.destra[4], state.representation.basso[7],
            state.representation.destra[6], state.representation.destra[7],
            state.representation.basso[8]
        ], state.representation.fronte, [
            state.representation.retro[2], state.representation.retro[5],
            state.representation.retro[8], state.representation.retro[1],
            state.representation.retro[4], state.representation.retro[7],
            state.representation.retro[0], state.representation.retro[3],
            state.representation.retro[6]
        ])
        n = RubikCubeState(
            state, rep_beta.alto, rep_beta.basso, rep_beta.sinistra,
            rep_beta.destra, rep_beta.fronte, rep_beta.retro,
            heuristic.H(rep_beta)
        )  #euristica lavora su una rappresentazione di stato non sullo stato direttamente
        out.add(n)

        #   ROTAZIONE ANTIORARIA PANNELLO POSTERIORE
        rep_beta = RubikCubeRepresentation([
            state.representation.sinistra[6], state.representation.sinistra[3],
            state.representation.sinistra[0], state.representation.alto[3],
            state.representation.alto[4], state.representation.alto[5],
            state.representation.alto[6], state.representation.alto[7],
            state.representation.alto[8]
        ], [
            state.representation.basso[0], state.representation.basso[1],
            state.representation.basso[2], state.representation.basso[3],
            state.representation.basso[4], state.representation.basso[5],
            state.representation.destra[2], state.representation.destra[5],
            state.representation.destra[8]
        ], [
            state.representation.basso[6], state.representation.sinistra[1],
            state.representation.sinistra[2], state.representation.basso[7],
            state.representation.sinistra[4], state.representation.sinistra[5],
            state.representation.basso[8], state.representation.sinistra[7],
            state.representation.sinistra[8]
        ], [
            state.representation.destra[0], state.representation.destra[1],
            state.representation.alto[0], state.representation.destra[3],
            state.representation.destra[4], state.representation.alto[1],
            state.representation.destra[6], state.representation.destra[7],
            state.representation.alto[2]
        ], state.representation.fronte, [
            state.representation.retro[6], state.representation.retro[3],
            state.representation.retro[0], state.representation.retro[7],
            state.representation.retro[4], state.representation.retro[1],
            state.representation.retro[8], state.representation.retro[5],
            state.representation.retro[2]
        ])
        n = RubikCubeState(
            state, rep_beta.alto, rep_beta.basso, rep_beta.sinistra,
            rep_beta.destra, rep_beta.fronte, rep_beta.retro,
            heuristic.H(rep_beta)
        )  #euristica lavora su una rappresentazione di stato non sullo stato direttamente
        out.add(n)

        return out
Beispiel #32
0
def main():

    logging.basicConfig(level='INFO')
    level = input("Insert level (odd number): ")

    # the play will be saved in this file
    file_name = "_plays/othello_{}.txt".format(
        datetime.now().strftime('%Y-%m-%d_%H-%M-%S'))
    out = open(file_name, "w")

    heuristic = heur.OthelloHeuristic()
    othello = game.OthelloGame(heuristic)

    # k start first
    turn = 'k'

    logging.info("starting player: {}, initial board:\n {}\n\n".format(
        turn, np.array(cp.copy(game.initial_board))))

    ix = othello.state

    start = time.time()

    while True:

        states = othello.neighbors(turn, ix)
        mx = -9999
        # store previous board
        previous = ix

        # cycle through the neighbors
        for s in states:
            # if the state is the previous one make it less valuable (so you will not get stuck)
            if s == previous:
                h = -1000
            else:
                # compute the heuristic value of the state s
                h = heuristic.Hl(othello, s, level, turn)

            logging.info(
                "possible move for player {}; state = \n {} \n heuristic = {}\n"
                .format(turn, s.representation.board, h))
            if h > mx:
                mx = h
                ix = s

        # at the end ix will contain the best state of the neighbor, log the state and write it in the out file
        logging.info("MOVE: player {} = \n {}\n\n".format(
            turn, ix.representation.board))
        out.write("MOVE: player {} = \n {}\n\n".format(
            turn, ix.representation.board))

        # check whether the state is final
        winner = ix.is_final()

        # if there is a winner print it and quit
        if winner is not None:
            elapsed_time = time.time() - start
            logging.info("The winner is player: {}".format(winner))
            logging.info("Elapsed time: {}".format(elapsed_time))

            out.write("The winner is player: {}\n".format(winner))
            out.write("Elapsed time: {}".format(elapsed_time))
            out.close()
            break

        turn = heur.OthelloHeuristic.get_enemy_color(turn)
Beispiel #33
0
    def game(self):
        self.deal_cards()
        self.main_card = self.deck.get_first_card()
        self.first, self.second = self.random_starter(self.player,
                                                      self.computer)
        mm = None
        while True:
            mc = MC.MonteCarlo(self, self.first.isComputer)

            if self.first.isComputer:
                if self.deck.check_if_deck_empty():
                    if mm is None:
                        comp = self.first.current_cards
                        player = self.second.current_cards
                        mm = MM(player, comp, self.main_card)
                        card_rand = mm.find_best().card
                    else:
                        if len(self.first.current_cards) != 1:
                            card_rand = mm.find_best().card
                        else:
                            card_rand = self.first.current_cards[0]

                else:
                    card_rand = mc.MC_random(self.iteration)

                index = -1
                for n, card in enumerate(self.first.current_cards):
                    if card.color == card_rand.color:
                        if card.power == card_rand.power:
                            index = n

                card1_playing = self.first.throw_card(int(index + 1))
                self.first.card_down = card1_playing
                print("")
                print(self.first.name + " played: " + str(card1_playing))
                print("")

                player2_pick = input("It's " + self.second.name +
                                     " turn to play,\n(Main card is " +
                                     str(self.main_card) +
                                     ") select number between 1 and " +
                                     str(len(self.second.current_cards)) +
                                     ",\n" + str(self.second.current_cards) +
                                     "\nwhich card in deck you want to play: ")
                while int(player2_pick) < 1 or int(player2_pick) > len(
                        self.second.current_cards):
                    print("")
                    player2_pick = input(
                        "You have to select number between 1 and " +
                        str(len(self.second.current_cards)) + ",\n" +
                        str(self.second.current_cards) +
                        " \nwhich card in deck you want to play: ")
                card2_playing = self.second.throw_card(int(player2_pick))
                if mm is not None and self.deck.check_if_deck_empty() and len(
                        self.second.current_cards) != 1:
                    mm.enemy_move(card2_playing)
                print("")
                print(self.second.name + " played: " + str(card2_playing))
                print("")
                self.second.card_down = card2_playing
            else:

                player1_pick = input(
                    "It's " + self.first.name +
                    " turn to play,\n(Main card is " + str(self.main_card) +
                    ") select number between 1 and " +
                    str(len(self.second.current_cards)) + ",\n" +
                    str(self.first.current_cards) +
                    " \nwhich card in deck you want to play: ")
                while int(player1_pick) < 1 or int(player1_pick) > len(
                        self.first.current_cards):
                    print("")
                    player1_pick = input(
                        "You have to select number between 1 and " +
                        str(len(self.second.current_cards)) + ",\n" +
                        str(self.first.current_cards) +
                        " \nwhich card in deck you want to play: ")

                card1_playing = self.first.throw_card(int(player1_pick))
                self.first.card_down = card1_playing
                print("")
                print(self.first.name + " played: " + str(card1_playing))
                print("")

                if self.deck.check_if_deck_empty():
                    if mm is None:
                        comp = self.second.current_cards
                        player = self.first.current_cards
                        mm = MM(player, comp, self.main_card, card1_playing)
                    else:
                        if len(self.first.current_cards) != 0:
                            mm.enemy_move(card1_playing)

                    if len(self.second.current_cards) != 1:
                        card_rand = mm.find_best().card
                    else:
                        card_rand = self.second.current_cards[0]
                else:
                    card_rand = mc.MC_random(self.iteration)
                index = -1
                for n, card in enumerate(self.second.current_cards):
                    if card.color == card_rand.color:
                        if card.power == card_rand.power:
                            index = n

                card2_playing = self.second.throw_card(int(index + 1))
                self.second.card_down = card2_playing

                print("")
                print(self.second.name + " played: " + str(card2_playing))
                print("")

            if heur.check_cards(card1_playing, card2_playing, self.main_card):
                print(self.first.name + " win the turn.")
                self.first.add_to_loot(card1_playing, card2_playing)
                print(self.first.count_score() + "\n\n")
            else:
                print(self.second.name + " win the turn.")
                self.second.add_to_loot(card1_playing, card2_playing)
                print(self.second.count_score() + "\n\n")
                tmp = self.first
                self.first = self.second
                self.second = tmp

            self.used_cards.append(card1_playing)
            self.used_cards.append(card2_playing)

            if self.deck.check_if_deck_empty() is False:
                card1, card2 = self.deck.deal_cards_on_turn()
                self.first.pick_up_card(card1)
                self.second.pick_up_card(card2)

            if self.second.check_hand():
                break

        print("\n\n")
        print(self.first.name + " has collected " + self.first.count_score() +
              " points.")
        print(self.second.name + " has collected " +
              self.second.count_score() + " points.")
        print("\n")

        if self.first.score > self.second.score:
            print(self.first.name +
                  " has won the game because he collected more points!")
        elif self.first.score < self.second.score:
            print(self.second.name +
                  " has won the game because he collected more points!")
        else:
            print("Game has finished with tied score!")
Beispiel #34
0
def main():

    # It gives the user the option to choose the (odd) level up to where he will come to explore the minMax
    level = input("Choose the depth you want to get to explore the tree : ")
    # From the rules of Othello the starting player is always black
    # Remember: k--> black, w--> white, '-'--> empty cell
    turn = 'k'

    print("All the moves of the play are saved in the file.\n")

    # Each play is saved on a file
    file_name = input("Choose a name for the file: ")
    file_path = "output/{}.txt".format(file_name)
    print("Please, wait...\n")
    out = open(file_path, "w")
    start = t.time()

    out.write("Starting player is: {}\n".format(turn))
    out.write("Level: {}\n\n\n".format(level))

    heuristic = he.OthelloHeuristic()
    othello = g.OthelloGame(heuristic)

    # Initial state of the game
    ix = othello.state
    out.write("\nInitial configuration: \n {}\n\n".format(
        ix.representation.board))

    #Start the game
    while True:
        # Save the states that it's possible to reach from the current state knowing the current turn
        states = othello.neighbors(turn, ix)
        # Initial value gives to find a better heuristic value (it is valid only in the first iteration, in next
        # iterations will be save the best heuristic value compute)
        mx = -9999
        # Save the last state in ix on prev because we must denied to stay always in the same state at least it is the
        # only possible move
        prev = ix

        # Start to explore the states
        for s in states:
            # for each state in states
            # if the state is the previous one make it less valuable (so you will not choose always the same state at
            # least it is the only possible move)
            if s == prev:
                # set h to -500 (arbitrary low)
                h = -500
            # if the state is not equal to the previus one
            else:
                # compute the heuristic on the state s
                h = heuristic.MinMax(othello, s, level, turn)

            # if the returned value from the heuristic method is grather than mx
            if h > mx:
                # save the new value in mx
                mx = h
                # save the state associate to the best heuristic value found
                ix = s

        # Write the move's player on the file
        out.write("\nplayer {}, move:\n {}\n\n".format(
            turn, ix.representation.board))
        print("player {}, move:\n {}\n\n".format(turn,
                                                 ix.representation.board))

        # Return the winner of the game
        winner = ix.is_final()

        # If ther's a winner
        if winner is not None:
            print("The game is finished! The winnwr is: {}".format(winner))
            # write the winner in the file
            out.write("The winner is player: {}\n".format(winner))
            end = t.time() - start
            # close file
            out.write("The time spent is: {}".format(end))
            out.close()

            print("The time spent is: {}".format(end))
            break
        # otherwise give the control to the other player
        turn = he.OthelloHeuristic.get_enemy_color(turn)