def solve(self, game_map, player_info, came_from=[], depth=0):
        
        agent = MinMax()
        result = {}
        result['anything-that-unsolved'] = []
        best = -10000
        action = None
        parent = None
        if len(came_from):
            
            for j in came_from:
                state = j

                for i in self.children:
                    v = agent.forward(game_map, state['pinfo'], i, depth)

                    if v['progression']:
                        result['anything-that-unsolved'].append({'pinfo':
                                                                 v['player_info'],
                                                                 'action': i})

                    if v['additional_score'] > best:
                        best = v['additional_score']
                        action = i
                        parent = j

            result['best'] = {'points': best,
                              'parent': parent,
                              'action': action
                              }
        else:
            
            for i in self.children:
                v = agent.forward(game_map, player_info, i)
                
                if v['progression']:
                    result['anything-that-unsolved'].append({'pinfo':
                                                             v['player_info'],
                                                             'action': i})

                if v['additional_score'] > best:
                    best = v['additional_score']
                    action = i
                    
            result['best'] = {'points': best,
                              'parent': None,
                              'action': action
                              }
        return result
Beispiel #2
0
    def getAction(self):
        bestMove = ""
        with chess.polyglot.open_reader("bookfish.bin") as reader:
            for entry in reader.find_all(self.board):
                bestMove = entry.move.__str__()
                break

        #If the try succeed we can use bookfish, else we use min max with aplha beta
        try:
            move = chess.Move.from_uci(bestMove)
            method = "(Move by Bookfish)"

        except:
            move = MinMax.minimaxRoot(3, self.board, True)
            method = "(Move by Min Max and Alpha Beta pruning"

        #Player
        if (self.turnId % 2 == 0):
            action = input("Donner une action à réaliser (ex:" + str(move) +
                           ") : ")
            while (self.moveEstLegal(action) == False):
                print("L'action n'est pas autorisée, veuillez recommencer")
                action = input("Donner une action à réaliser (ex:" +
                               str(move) + ") : ")
            return chess.Move.from_uci(action)
        else:
            print(self.nameAI + " a joue " + str(move), method)
            return move
Beispiel #3
0
def test_basics( dump_vcd ):

  # Test vectors

  test_vectors = [
   # -- in -- -- out --
    [  4,  3,   3,  4 ],
    [  9,  6,   6,  9 ],
    [ 12, 16,  12, 16 ],
    [ 12, 16,  12, 16 ],
  ]

  # Instantiate and elaborate the model

  model = MinMax()
  model.vcd_file = dump_vcd
  model.elaborate()

  # Function to set the inputs on the model

  def tv_in( model, test_vector ):
    model.in0.value = test_vector[0]
    model.in1.value = test_vector[1]

  # Function to verify the outputs from the model

  def tv_out( model, test_vector ):
    if test_vector[2] != '?':
      assert model.min.value == test_vector[2]
    if test_vector[3] != '?':
      assert model.max.value == test_vector[3]

  # Create and run the test simulation

  sim = TestVectorSimulator( model, test_vectors, tv_in, tv_out )
  sim.run_test()
Beispiel #4
0
def test_basics(dump_vcd):

    # Test vectors

    test_vectors = [
        # -- in -- -- out --
        [4, 3, 3, 4],
        [9, 6, 6, 9],
        [12, 16, 12, 16],
        [12, 16, 12, 16],
    ]

    # Instantiate and elaborate the model

    model = MinMax()
    model.vcd_file = dump_vcd
    model.elaborate()

    # Function to set the inputs on the model

    def tv_in(model, test_vector):
        model.in0.value = test_vector[0]
        model.in1.value = test_vector[1]

    # Function to verify the outputs from the model

    def tv_out(model, test_vector):
        if test_vector[2] != '?':
            assert model.min.value == test_vector[2]
        if test_vector[3] != '?':
            assert model.max.value == test_vector[3]

    # Create and run the test simulation

    sim = TestVectorSimulator(model, test_vectors, tv_in, tv_out)
    sim.run_test()
Beispiel #5
0
def IAvsIA():
    board = chess.Board()
    display(SVG(chess.svg.board(board=board)))
    print("")
    while not (board.is_game_over()):
        moves = board.legal_moves

        #It look if the best_move function has a move to push
        #If not, we use alpha-beta method
        if best_move(board) == "Nothing":

            move = MinMax.minimaxRoot(3, board, True)
            line.append(move)
            board.push(move)
            display(SVG(chess.svg.board(board=board, lastmove=move)))
            print("")
            #If there is a move from polyglot, we push it
        elif best_move(board) in moves:
            moveToPush = best_move(board)
            line.append(moveToPush)
            board.push(moveToPush)
            display(SVG(chess.svg.board(board=board, lastmove=moveToPush)))
            print("")

        #We look after every move if the game is over in order to end it
        if board.is_game_over():
            print("The game is over")
            print(board.result())
            game.headers["Result"] = board.result()

    ###Game saving ###
    game.add_line(line)
    new_pgn = open("D:/Polytech/FI 3/Proj/gitTheo2.0/savedGames.pgn",
                   "a",
                   encoding="utf-8")
    exporter = chess.pgn.FileExporter(new_pgn)
    game.accept(exporter)

    new_pgn.close()
Beispiel #6
0
    def getAction(self):
        bestMove = ""
        with chess.polyglot.open_reader("bookfish.bin") as reader:
            for entry in reader.find_all(self.board):
                bestMove = entry.move.__str__()
                break

        #If the try succeed we can use bookfish, else we use min max with aplha beta
        try:
            move = chess.Move.from_uci(bestMove)
            method = "(Move by Bookfish)"

        except:
            move = MinMax.minimaxRoot(3, self.board, True)
            method = "Move by Min Max and Alpha Beta pruning"

        #Player
        if (self.turnId % 2 == 0):
            print(self.nameAI1 + " a joue " + str(move), method)
            return move
        else:
            print(self.nameAI2 + " a joue " + str(move), method)
            return move
    def new_bot_logic(self):

        agent = MinMax()
        moves = [i for i in Commands]
        tree = BFTree(moves)
        # new new bot login
        c = copy.deepcopy(self.player_info)
        result = tree.solve(self.map
                            , c) # <-- soup
        r = 1
        while len(result['anything-that-unsolved']):
            temp = result['anything-that-unsolved']
            result = tree.append_result(result
                                        , BFTree(moves).solve(self.map, None, result['anything-that-unsolved']), r)
            r += 1
            result['anything-that-unsolved'] = [i for i in result['anything-that-unsolved'] if not i in temp]

        #print(result["best"]["action"])
                
        #print("{}|{}".format(result, i))          
        #self.command = Commands.NOTHING.value
        self.command = result["best"]["action"]
        return self.command
Beispiel #8
0
class methods:
    def __init__(self, fps, clockObject, surface, font, bars, windowsize):
        self.fps = fps
        self.clock = clockObject
        self.surface = surface
        self.font = font
        self.bars = bars
        self.windowsize = windowsize

    def get_array(self, length, mode=0):
        arr = list(range(length))

        if not mode:
            random.shuffle(arr)
        elif mode == 2:
            arr = arr[::-1]
        elif mode == 3:
            for i in range(length - 1):
                if random.randint(0, 10) < 8:
                    tmp = random.randint(4, 15)
                    try:
                        arr[i], arr[i + tmp] = arr[i + tmp], arr[i]
                    except:
                        pass

        return arr

    def setup(self, length, mode=0):
        self.array = self.get_array(length, mode)

        self.display = Display(self.windowsize[0] / length, self.windowsize,
                               self.surface, self.font)
        self.accesses = 0
        self.comparisons = 0

        setattr(self.display, "bars", self.bars)

    bubble = lambda self: Bubble(self.array, self.display, self.clock, self.fps
                                 ).main()
    quicksort = lambda self: Quicksort(self.array, self.display, self.clock,
                                       self.fps).main()
    selection = lambda self: Selection(self.array, self.display, self.clock,
                                       self.fps).main()
    cocktail = lambda self: Cocktail(self.array, self.display, self.clock, self
                                     .fps).main()
    bogo = lambda self: Bogo(self.array, self.display, self.clock, self.fps
                             ).main()
    oddeven = lambda self: Oddeven(self.array, self.display, self.clock, self.
                                   fps).main()
    shell = lambda self: Shell(self.array, self.display, self.clock, self.fps
                               ).main()
    comb = lambda self: Comb(self.array, self.display, self.clock, self.fps
                             ).main()
    insertion = lambda self: Insertion(self.array, self.display, self.clock,
                                       self.fps).main()
    mergetd = lambda self: MergeTD(self.array, self.display, self.clock, self.
                                   fps).main()
    radixlsd = lambda self: RadixLSD(self.array, self.display, self.clock, self
                                     .fps).main()
    counting = lambda self: Counting(self.array, self.display, self.clock, self
                                     .fps).main()
    cycle = lambda self: Cycle(self.array, self.display, self.clock, self.fps
                               ).main()
    heap = lambda self: Heap(self.array, self.display, self.clock, self.fps
                             ).main()
    circle = lambda self: Circle(self.array, self.display, self.clock, self.fps
                                 ).main()
    gnome = lambda self: Gnome(self.array, self.display, self.clock, self.fps
                               ).main()
    binaryinsertion = lambda self: BinaryInsertion(
        self.array, self.display, self.clock, self.fps).main()
    pancake = lambda self: Pancake(self.array, self.display, self.clock, self.
                                   fps).main()
    permutation = lambda self: Permutation(self.array, self.display, self.
                                           clock, self.fps).main()
    strand = lambda self: Strand(self.array, self.display, self.clock, self.fps
                                 ).main()
    bucket = lambda self: Bucket(self.array, self.display, self.clock, self.fps
                                 ).main()
    minmax = lambda self: MinMax(self.array, self.display, self.clock, self.fps
                                 ).main()
    mergebu = lambda self: MergeBU(self.array, self.display, self.clock, self.
                                   fps).main()
    bitonic = lambda self: Bitonic(self.array, self.display, self.clock, self.
                                   fps).main()
    stooge = lambda self: Stooge(self.array, self.display, self.clock, self.fps
                                 ).main()
    smooth = lambda self: Smooth(self.array, self.display, self.clock, self.fps
                                 ).main()
    quick3 = lambda self: Quick3(self.array, self.display, self.clock, self.fps
                                 ).main()
Beispiel #9
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 #10
0
from board import board
from move import move
from MinMax import MinMax

playboard = board()

player = int(raw_input("Player colour? (1=White, 2=Black)"))
print "Player is %s; computer is %s"%("Black" if player == 2 else "White", 
                                      "White" if player == 2 else "Black")

level = int(raw_input("Computer level? (1-?)"))

computer = MinMax(level, 1 if player == 2 else 2)
                                      
turn_token = 1
while 1:
    playboard.display()
    print "Score: %d"%playboard.score()
    if turn_token == player:
        move_object = None
        while move_object == None:
            move_string = raw_input("%s move? (ROW, COLUMN or ROW, COLUMN, TAKE_ROW, TAKE_COLUMN) "%
                                    ("White" if (turn_token == 1) else "Black"))
            move_object = move(turn_token, string = move_string)
    else:
        move_object = computer.move(playboard)
    turn_token = 2 if (turn_token == 1) else 1
    playboard.move(move_object)
Beispiel #11
0
 def __init__(self, playerID, difficulty):
     self.ID = playerID
     self.diff = difficulty
     self.MM = MinMax(self.ID, self)
Beispiel #12
0
class TTTMinMax(Player):
    def __init__(self, playerID, difficulty):
        self.ID = playerID
        self.diff = difficulty
        self.MM = MinMax(self.ID, self)

    def readyPlayer(self):
        pass

    def queryAction(self, state):
        print("Beginning MinMax.")
        best = self.MM.MinMaxGo(None, state, self.diff)
        #        print("Best: ", best)
        print("Best: ", best[0])
        return best[0]

    # Heuristic used to evaluate a state.
    def evaluate(self, state):
        #        print("Evaluating state.")
        result = state.gameover()
        #        print("Result: " + str(state.gameover()))

        if result == -1:  # Game not over
            # Count number of possible 3s in a row to get
            score = 0

            # Go through rows
            for i in range(0, 3):
                ours, theirs, neither = 0, 0, 0
                #                print("row " + str(i))
                for j in range(0, 3):
                    if state.board[i][j] == 0:
                        neither += 1
                    elif state.board[i][j] == self.ID:
                        ours += 1
                    else:
                        theirs += 1
                # possible results
#                print(str(ours) + " " + str(theirs) + " " + str(neither))
                score += self.singleScore(ours, theirs, neither)
#            print("Score after rows: " + str(score))

# Go through columns
            for i in range(0, 3):
                ours, theirs, neither = 0, 0, 0
                #                print("column " + str(i))
                for j in range(0, 3):
                    if state.board[j][i] == 0:
                        neither += 1
                    elif state.board[j][i] == self.ID:
                        ours += 1
                    else:
                        theirs += 1
                # possible results
#                print(str(ours) + " " + str(theirs) + " " + str(neither))
                score += self.singleScore(ours, theirs, neither)
#            print("Score after cols: " + str(score))

#            print("First diagonal")
            ours, theirs, neither = 0, 0, 0
            # Diagonal UL to DR
            for i in range(0, 3):
                if state.board[i][i] == 0:
                    neither += 1
                elif state.board[i][i] == self.ID:
                    ours += 1
                else:
                    theirs += 1
            # possible results
#            print(str(ours) + " " + str(theirs) + " " + str(neither))
            score += self.singleScore(ours, theirs, neither)

            #            print("Second diagonal")
            ours, theirs, neither = 0, 0, 0
            # Diagonal UR to DL
            for i in range(0, 3):
                if state.board[i][2 - i] == 0:
                    neither += 1
                elif state.board[i][2 - i] == self.ID:
                    ours += 1
                else:
                    theirs += 1
            # possible results
            score += self.singleScore(ours, theirs, neither)

            #            print("Score after diags (Final): " + str(score))
            return score
        elif result == 0:  # Tie
            return 0
        elif result == self.ID:
            return 500
        else:
            return -500

    def singleScore(self, ours, theirs, neither):
        score = 0
        if ours == 1 and neither == 2:
            score += 1
        elif ours == 2 and neither == 1:
            score += 2
        elif theirs == 1 and neither == 2:
            score -= 1
        elif theirs == 2 and neither == 1:
            score -= 2
        return score

    def equals(self, arg):
        if (arg.ID == self.ID):
            return True
        return False
Beispiel #13
0
def MANvsIA():

    board = chess.Board()
    display(SVG(chess.svg.board(board=board)))

    while not (board.is_game_over()):
        moves = board.legal_moves
        #The MAN start everytime
        man_move = chess.Move.from_uci(input("your move : "))
        if man_move in moves:
            board.push(man_move)
            line.append(man_move)
            display(SVG(chess.svg.board(board=board, lastmove=man_move)))
        else:
            while man_move not in moves:
                print("Illegal move, please try an other one")
                print("Here is the list of legal move")
                for move in board.legal_moves:
                    print(move)
                man_move = chess.Move.from_uci(input("your move : "))
            board.push(man_move)
            line.append(man_move)
            display(SVG(chess.svg.board(board=board, lastmove=man_move)))

    #We look after every move if the game is over in order to end it
        if board.is_game_over():
            print("The game is over")
            print(board.result())
            game.headers["Result"] = board.result()
            print("")

        #Now it's IA turns

        moves = board.legal_moves

        #It look if the best_move function has a move to push
        #If not, we use alpha-beta method
        if best_move(board) == "Nothing":

            move = MinMax.minimaxRoot(3, board, True)
            line.append(move)
            board.push(move)
            display(SVG(chess.svg.board(board=board, lastmove=move)))
            print("")
            #If there is a move from polyglot, we push it
        elif best_move(board) in moves:
            moveToPush = best_move(board)
            line.append(moveToPush)
            board.push(moveToPush)
            display(SVG(chess.svg.board(board=board, lastmove=moveToPush)))
            print("")

        #We look after every move if the game is over in order to end it
        if board.is_game_over():
            print("The game is over")
            print(board.result())
            game.headers["Result"] = board.result()
            print("")

    ###Game saving ###
    game.add_line(line)
    new_pgn = open("D:/Polytech/FI 3/Proj/gitTheo2.0/savedGames.pgn",
                   "a",
                   encoding="utf-8")
    exporter = chess.pgn.FileExporter(new_pgn)
    game.accept(exporter)

    new_pgn.close()
Beispiel #14
0
def test():
    'currently no error checking for valid user moves'

    mm = MinMax()
    board = mm.init_board()

    player = True
    while not mm.game_over(board):
        if player:  # black - AI
            print mm.generate_black_moves(board)
            mm.minmax(board, 2, False)  # don't know why False
            move = mm.BEST_MOVE
            board = mm.move_black(board, *move)
            mm.print_board(board)
            player = False
        else:
            print mm.generate_white_moves(board)
            i = int(raw_input("Enter piece i: "))
            j = int(raw_input("Enter piece j: "))
            i_new = int(raw_input("Enter new i: "))
            j_new = int(raw_input("Enter new j: "))
            board = mm.move_white(board, (i, j), (i_new, j_new))
            mm.print_board(board)
            player = True
Beispiel #15
0
    def elaborate_logic(s):

        #---------------------------------------------------------------------
        # Stage A->B pipeline registers
        #---------------------------------------------------------------------

        s.reg_AB = [Reg(16) for x in range(4)]
        s.connect(s.reg_AB[0].in_, s.in_[0])
        s.connect(s.reg_AB[1].in_, s.in_[1])
        s.connect(s.reg_AB[2].in_, s.in_[2])
        s.connect(s.reg_AB[3].in_, s.in_[3])

        #---------------------------------------------------------------------
        # Stage B combinational logic
        #---------------------------------------------------------------------

        s.cmp_B0 = m = MinMax()
        s.connect_dict({
            m.in0: s.reg_AB[0].out,
            m.in1: s.reg_AB[1].out,
        })

        s.cmp_B1 = m = MinMax()
        s.connect_dict({
            m.in0: s.reg_AB[2].out,
            m.in1: s.reg_AB[3].out,
        })

        #---------------------------------------------------------------------
        # Stage B->C pipeline registers
        #---------------------------------------------------------------------

        s.reg_BC = [Reg(16) for x in range(4)]
        s.connect(s.reg_BC[0].in_, s.cmp_B0.min)
        s.connect(s.reg_BC[1].in_, s.cmp_B0.max)
        s.connect(s.reg_BC[2].in_, s.cmp_B1.min)
        s.connect(s.reg_BC[3].in_, s.cmp_B1.max)

        #---------------------------------------------------------------------
        # Stage C combinational logic
        #---------------------------------------------------------------------

        s.cmp_C0 = m = MinMax()
        s.connect_dict({
            m.in0: s.reg_BC[0].out,
            m.in1: s.reg_BC[2].out,
        })

        s.cmp_C1 = m = MinMax()
        s.connect_dict({
            m.in0: s.reg_BC[1].out,
            m.in1: s.reg_BC[3].out,
        })

        s.cmp_C2 = m = MinMax()
        s.connect_dict({
            m.in0: s.cmp_C0.max,
            m.in1: s.cmp_C1.min,
        })

        # Connect to output ports

        s.connect(s.cmp_C0.min, s.out[0])
        s.connect(s.cmp_C2.min, s.out[1])
        s.connect(s.cmp_C2.max, s.out[2])
        s.connect(s.cmp_C1.max, s.out[3])