示例#1
0
    def place_piece_event(self, event):

        pos_x, pos_y = event.pos
        
        x, y = self.screen_to_coord(pos_x, pos_y)
        colour = self.board.player
                    
        new_event = pygame.event.wait()

        if new_event.type == pygame.KEYDOWN:
            key   = new_event.key
            piece = None

            if key == ord("a"):
                piece = Pieces.Ant(colour)

            elif key == ord("q"):
                piece = Pieces.Queen(colour)

            elif key == ord("b"):
                piece = Pieces.Beetle(colour)

            elif key == ord("g"):
                piece = Pieces.Grasshopper(colour)

            elif key == ord("s"):
                piece = Pieces.Spider(colour)
                        
            if piece:
                Moves.place_piece(self.board, x, y, piece)
                self.render_step()
示例#2
0
    def move_piece_event(self, event):
        x, y      = event.pos
        to_cell   = self.screen_to_coord(x, y)
        from_cell = (self.selected_cell.board_x, self.selected_cell.board_y)

        Moves.play_legal_move(self.board, from_cell, to_cell)
        
        self.selected_cell = None
        self.render_step()
示例#3
0
    def optimize_monopoly_choice(session: GameSession, player: Player,
                                 move: Moves):
        """
        finds the most common resource among all other players and calculates
        if it is the best choice for the player, considering the player's hand

        :return:
        """
        p = find_sim_player(session, player)
        score = 0
        all_res_from_players = Hand()
        # all resources from all players:
        [
            all_res_from_players.insert(other_player.resource_hand())
            for other_player in session.players() if other_player != p
        ]
        res_values_all_players = \
            all_res_from_players.map_resources_by_quantity()
        res_values_curr_player = p.resource_hand().map_resources_by_quantity()

        for res_type in res_values_all_players:
            res_values_all_players[
                res_type] -= res_values_curr_player[res_type] / 2

        most_common_res = max(res_values_all_players,
                              key=res_values_all_players.get)

        if move.resource() == most_common_res:
            score += 0.5
        return score
示例#4
0
def Neural_Networke(parsedFEN, possibleMoves):
    ses = tf.Session()
    #ses.run(tf.global_variables_initializer())
    saver.restore(ses, "./tmp2/model.ckpt")
    inputlist = [parsedFEN]
    test = []
    moves = possibleMoves
    test = ses.run(logits, feed_dict={X: inputlist, Y: prrr})
    tesst = test[0]
    tesst = tesst.tolist()
    maxval = max(tesst)
    minval = min(tesst)
    for x in range(0, len(tesst)):
        y = (tesst[x] - minval) / (maxval - minval)
        tesst[x] = y
    maxval = max(tesst)
    minval = min(tesst)
    turns = Moves.getMoves()
    for x in tesst:
        ind = tesst.index(maxval)
        #print(str(tesst[ind]) + ": " + turns[ind])
        if (turns[ind] in moves):
            #print(str(tesst[ind]) + ": " + turns[ind])
            return turns[ind]
        tesst[ind] = -1
        maxval = max(tesst)
 def RecordMove(self, CurrentMove):
     self.__data['CurrentMoveIndex'] += 1
     if (len(self.__data['MoveList']) > self.__data['CurrentMoveIndex']):
         self.__data['MoveList'] = self.__data[
             'MoveList'][:self.__data['CurrentMoveIndex']]
     self.__data['MoveList'].append(CurrentMove)
     self.__data['PreviousPlayer'] = CurrentMove.player_color
     self.__data['CurrentMove'] = Moves.Moves()
示例#6
0
    def optimized_trading_choice(session: GameSession, player: Player,
                                 move: Moves):
        """prefer trading resources for resources you can't get from dice"""
        p = find_sim_player(session, player)
        res_hand = p.resource_hand()
        score = 0
        if move.get_type() == Moves.MoveType.TRADE:
            __board = session.board()
            res_types_from_dice = __board.resources_player_can_get(player)
            gets_type = move.gets().get_cards_types().pop()
            num_instances_gets_type = res_hand.cards_of_type(gets_type)

            # if what you get from trading you can't achieve from dice:
            if gets_type not in res_types_from_dice:
                # raise score:
                score += 1 / (2 * num_instances_gets_type)
        return score
示例#7
0
    def parseMove(self, line, board):
        def col(s):
            return ord(s) - ord("a")

        def row(s):
            return ord(s) - ord("1")

        m = re.match("^\\s*([a-h])([1-8])\\s*-\\s*([a-h])([1-8])\\s*$", line)
        if m != None:
            src = (col(m.group(1)), row(m.group(2)))
            dst = (col(m.group(3)), row(m.group(4)))
            return Moves.Move(board, src, dst)

        m = re.match("^\\s*([a-h])([1-8])\\s*$", line)
        if m != None:
            src = (-1, -1)
            dst = (col(m.group(1)), row(m.group(2)))
            return Moves.Move(board, src, dst)

        return None
示例#8
0
def start_game():
    b = Board.Board()
    ui = BoardUI.BoardUI(b)
    ui.render_step()

    winner = -1

    while True:

        ui.wait_for_move()

        if Moves.has_lost(b, 0):
            winner = 1
            break

        if Moves.has_lost(b, 1):
            winner = 0
            break

    ui.render_endgame(winner)
    ui.manage_all_events()
示例#9
0
    def __run_pre_game(self) -> None:
        print('[CATAN] Pre-Game started')
        print(self.board())
        for _round in (1, 2):
            self.__pre_game_round = _round
            turn_gen = ((player for player in self.players())  # 0, 1, 2, 3
                        if _round == 1 else
                        (player for player in reversed(self.players())))  # 3, 2, 1, 0
            for curr_player in turn_gen:
                self.__curr_player_sim = curr_player
                # get player's choice of settlement
                self.__phase = GamePhase.PRE_GAME_SETTLEMENT
                self.__possible_moves_this_phase = self.__get_possible_build_settlement_moves(curr_player,
                                                                                              pre_game=True)
                build_settlement_move = curr_player.choose(self.__possible_moves_this_phase, deepcopy(self))

                # add new settlement to game
                settlement_node = build_settlement_move.at()
                self.__pre_game_settlement_node = settlement_node
                settlement = Buildable.Buildable(curr_player, settlement_node, Consts.PurchasableType.SETTLEMENT)
                curr_player.add_buildable(settlement)
                self.__board.build(settlement)

                dprint(self.board())

                # get player's choice of road
                self.__phase = GamePhase.PRE_GAME_ROAD
                adj_edges = self.board().get_adj_edges_to_node(build_settlement_move.at())
                self.__possible_moves_this_phase = [
                    Moves.BuildMove(curr_player, Consts.PurchasableType.ROAD, edge, free=True)
                    for edge in adj_edges]
                possible_road_moves = self.__possible_moves_this_phase
                build_adj_road_move = curr_player.choose(possible_road_moves, deepcopy(self))

                # add new road to game
                road_edge = build_adj_road_move.at()
                road = Buildable.Buildable(curr_player, road_edge, Consts.PurchasableType.ROAD)
                curr_player.add_buildable(road)
                self.__board.build(road)

                print(f'[PRE GAME] player {curr_player} placed settlement at {hex(settlement_node)}, '
                       f'road at {hex(road_edge)}')

                if _round == 2:  # second round, yield resources from settlement
                    starting_resources = self.__board.resource_distributions_by_node(settlement_node)
                    self.__res_deck.remove(starting_resources)
                    curr_player.receive_cards(starting_resources)
                    dprint(f'[PRE GAME] player {curr_player} received {starting_resources} '
                           f'for his 2nd settlement at {hex(settlement_node)}')

                print(self.board())
                dprint(self.status_table())
示例#10
0
 def __get_possible_knight_moves(self, player: Player.Player, robber: bool = False) -> List[Moves.UseKnightDevMove]:
     moves = []
     dev_type = Consts.DevType.KNIGHT
     if robber or player.dev_hand().contains(Hand.Hand(dev_type)):  # if has it
         # if wasnt bought this turn or had at least 1 more from before this turn
         if robber or (dev_type not in self.__dev_cards_bought_this_turn or
                       player.dev_hand().cards_of_type(dev_type).size() >
                       self.__dev_cards_bought_this_turn.cards_of_type(dev_type).size()):
             robber_hex = self.board().robber_hex()
             for hex_tile in self.board().hexes():  # get hex, cant place at same place or back at desert
                 if hex_tile is not robber_hex and hex_tile.resource() != Consts.ResourceType.DESERT:
                     opponents_on_hex = []  # finding opponents with buildables around hex
                     for node in hex_tile.nodes():  # get node around hex that is occupied
                         if self.board().nodes().get(node) is not None:
                             opp = self.board().nodes().get(node).player()
                             if opp != player and opp not in opponents_on_hex:  # if its not occupied by you...
                                 opponents_on_hex.append(opp)  # then its an opponent
                     if opponents_on_hex:
                         for opp in opponents_on_hex:
                             moves.append(
                                 Moves.UseKnightDevMove(player, hex_tile.id(), opp, robber_activated=robber))
                     else:  # no opponents, make move without opp id
                         moves.append(Moves.UseKnightDevMove(player, hex_tile.id(), None, robber_activated=robber))
     return moves
示例#11
0
    def select_piece_event(self, event):
        for cell in self.cell_list:
            
            if cell.rect.collidepoint(event.pos):
                                
                x, y = cell.board_x, cell.board_y

                piece = self.board.piece_on(x, y)

                if piece.colour == self.board.player:
                    self.selected_cell = cell
                    if self.board.queens[piece.colour]:
                        moves = Moves.moves_piece(self.board, x, y)
                        self.render_moves(moves)
                
                break
示例#12
0
    def __pre_game_settlement_sim(self, move_to_play: Moves.BuildMove) -> List[Moves.Move]:
        # add new settlement to game
        curr_player = self.__curr_player_sim
        build_settlement_move = move_to_play
        settlement_node = build_settlement_move.at()
        self.__pre_game_settlement_node = settlement_node
        settlement = Buildable.Buildable(curr_player, settlement_node, Consts.PurchasableType.SETTLEMENT)
        curr_player.add_buildable(settlement)
        self.__board.build(settlement)

        dprint(self.board())

        # get player's choice of road
        self.__phase = GamePhase.PRE_GAME_ROAD
        adj_edges = self.board().get_adj_edges_to_node(build_settlement_move.at())
        possible_road_moves = [Moves.BuildMove(curr_player, Consts.PurchasableType.ROAD, edge, free=True)
                               for edge in adj_edges]
        self.__possible_moves_this_phase = possible_road_moves
        return self.__possible_moves_this_phase
示例#13
0
 def selectMove(self, board):
     validMoves = Moves.generateMoves(board, self.color)
     while True:
         sys.stderr.write("Your move> ")
         #sys.stderr.flush()
         line = sys.stdin.readline()
         move = self.parseMove(line, board)
         if move in validMoves:
             return move
         elif move != None:  # Incomplete move - try to complete it:
             candidates = [
                 m for m in validMoves if self.moveMatches(move, m)
             ]
             if len(candidates) == 1:
                 return candidates[0]
             else:
                 sys.stderr.write("Ambiguous move\n")
         else:
             sys.stderr.write("Invalid move :-(\n")
示例#14
0
def writeToFile(fen, move):
    fen = str(fen)
    parsedfen = parseFEN.parse(fen)
    if (parseFEN.inverted):
        move = parseFEN.invertMove(move)
    allmoves = Moves.getMoves()
    parsedmove = []
    for m in allmoves:
        if (move == m):
            parsedmove.append(1)
        else:
            parsedmove.append(0)
    fenwrite = ""
    for f in parsedfen:
        fenwrite += str(f) + ","
    movewrite = ""
    for p in parsedmove:
        movewrite += str(p) + ","

    with open(pathwithoutend + ".txt", "a") as myfile:
        myfile.write(fenwrite + "|" + movewrite + "\n")
示例#15
0
    def selectMove(self, board):
        factor = 1 if self.color == White else -1

        v0 = self.brain.evaluate(board)
        #print "Valuation: %s" % v0

        validMoves = Moves.generateMoves(board, self.color)
        (bestMove, bestScore) = (None, -100 * factor)

        for move in validMoves:
            undoHandle = move.apply()
            score = self.brain.evaluate(board)
            undoHandle.undo()

            c = " "
            if score * factor > bestScore * factor:
                (bestMove, bestScore) = (move, score)
                c = "*"
            #print "  %c %s: %5.3f" % (c, move, score)

        return bestMove
示例#16
0
     game.Drawboard(gamedisplay)
     buttons.ButtonBack(gamedisplay,colors.white)
     if not game.isOver():
         buttons.nowPlayertext(gamedisplay, game.isPlayer1)
     if game.isOver():
         buttons.GameOver(gamedisplay, game.isPlayer1)
         if event.type == pygame.MOUSEBUTTONDOWN:
             x, y = pygame.mouse.get_pos()
             x, y = x / game.sizeofrect, y / game.sizeofrect
             if (x, y) == (9, 6) or (x, y) == (10, 6) or (x, y) == (11, 6):  # clicked back
                 buttons.ButtonBack(gamedisplay, colors.green)
                 pygame.display.update()
                 game.gameReset()
                 game.inGame = False
     else:
         List = moves.gameMoveHave2Eat(game.isPlayer1)
         if len(List)!=0:
             #have 2 eat
             game.isPlayer1 = moves.gameAnalizeHave2Eat(gamedisplay,game.isPlayer1,List, False)
         elif event.type == pygame.MOUSEBUTTONDOWN:
             x, y = pygame.mouse.get_pos()
             x, y = x / game.sizeofrect, y / game.sizeofrect
             if (x, y) == (9, 6) or (x, y) == (10, 6) or (x, y) == (11, 6):  #clicked back
                 buttons.ButtonBack(gamedisplay, colors.green)
                 pygame.display.update()
                 game.gameReset()
                 game.inGame = False
             elif (x>=0 and x<8 and y>=0 and y<8): #limit to board
                 game.isPlayer1 = moves.gameAnalizeMove(gamedisplay,game.isPlayer1, x, y)
 else:#main menu
     game.DrawPieces()
示例#17
0
 def __get_possible_throw_moves(player: Player.Player) -> List[Moves.ThrowMove]:
     players_cards = list(set([card for card in player.resource_hand() if card in Consts.YIELDING_RESOURCES]))
     throw_moves = [Moves.ThrowMove(player, Hand.Hand(card)) for card in players_cards]
     return throw_moves
示例#18
0
 def __get_possible_build_road_moves(self, player: Player.Player, free: bool = False) -> List[Moves.BuildMove]:
     moves = []
     if self.__has_remaining_roads(player):
         moves = [Moves.BuildMove(player, Consts.PurchasableType.ROAD, edge, free=free)
                  for edge in self.__buildable_edges(player)]
     return moves
示例#19
0
 def __get_possible_build_settlement_moves(self, player: Player.Player,
                                           pre_game: bool = False) -> List[Moves.BuildMove]:
     moves = [Moves.BuildMove(player, Consts.PurchasableType.SETTLEMENT, node, free=pre_game)
              for node in self.__buildable_nodes(player, pre_game)]
     return moves
示例#20
0
    def __get_possible_moves(self, player: Player.Player) -> List[Moves.Move]:

        # PASS TURN #
        moves = [Moves.Move(player, Moves.MoveType.PASS)]

        # BUY #
        # Buy Dev Move Legality
        if (self.__can_purchase(player, Consts.PurchasableType.DEV_CARD) and
                self.__dev_deck.size() > 0):
            moves.append(Moves.BuyDevMove(player))

        # USE #
        # Use Dev Card Legality
        if not self.__dev_used_this_turn:
            for dev_type in Consts.DevType:  # get dev card type
                if player.dev_hand().contains(Hand.Hand(dev_type)):  # if has it
                    # if wasnt bought this turn or had at least 1 more from before this turn
                    if (dev_type not in self.__dev_cards_bought_this_turn or
                            player.dev_hand().cards_of_type(dev_type).size() >
                            self.__dev_cards_bought_this_turn.cards_of_type(dev_type).size()):
                        if dev_type == Consts.DevType.MONOPOLY:
                            for resource in Consts.YIELDING_RESOURCES:
                                moves.append(Moves.UseMonopolyDevMove(player, resource))
                        elif dev_type == Consts.DevType.YEAR_OF_PLENTY:
                            for resource_comb in combinations(Consts.YIELDING_RESOURCES, Consts.YOP_NUM_RESOURCES):
                                moves.append(Moves.UseYopDevMove(player, *resource_comb))
                        elif dev_type == Consts.DevType.ROAD_BUILDING:
                            moves.append(Moves.UseRoadBuildingDevMove(player))
                        elif dev_type == Consts.DevType.KNIGHT:
                            robber_hex = self.board().robber_hex()
                            for hex_tile in self.board().hexes():
                                if hex_tile is not robber_hex and hex_tile.resource() != Consts.ResourceType.DESERT:
                                    opponents_on_hex = set()
                                    for node in hex_tile.nodes():
                                        if self.board().nodes().get(node) is not None:
                                            opp = self.board().nodes().get(node).player()
                                            if opp != player:
                                                opponents_on_hex.add(opp)
                                    if opponents_on_hex:
                                        for opp in opponents_on_hex:
                                            moves.append(Moves.UseKnightDevMove(player, hex_tile.id(), opp))
                                    else:
                                        moves.append(Moves.UseKnightDevMove(player, hex_tile.id(), None))

                        elif dev_type == Consts.DevType.VP:
                            moves.append(Moves.UseDevMove(player, dev_type))

        # BUILD #
        # Build settlement legality
        if (self.__can_purchase(player, Consts.PurchasableType.SETTLEMENT) and
                self.__has_remaining_settlements(player)):
            for node in self.__buildable_nodes(player):
                moves.append(Moves.BuildMove(player, Consts.PurchasableType.SETTLEMENT, node))

        # build city legality
        if (self.__can_purchase(player, Consts.PurchasableType.CITY) and
                self.__has_remaining_cities(player)):
            for settlement_node in player.settlement_nodes():
                moves.append(Moves.BuildMove(player, Consts.PurchasableType.CITY, settlement_node))

        # build road legality
        if (self.__can_purchase(player, Consts.PurchasableType.ROAD) and
                self.__has_remaining_roads(player)):
            for edge_id in self.__buildable_edges(player):
                moves.append(Moves.BuildMove(player, Consts.PurchasableType.ROAD, edge_id))

        # TRADE #
        # trade legality with deck
        for homogeneous_hand in self.__homogeneous_hands_of_size(player, Consts.DECK_TRADE_RATIO):
            for available_resource in self.__available_resources():
                if [card for card in homogeneous_hand][0] != available_resource:
                    moves.append(Moves.TradeMove(player, homogeneous_hand, Hand.Hand(available_resource)))

        # trade legality with general harbor
        if self.__has_general_harbor(player):
            for homogeneous_hand in self.__homogeneous_hands_of_size(player, Consts.GENERAL_HARBOR_TRADE_RATIO):
                for available_resource in self.__available_resources():
                    moves.append(Moves.TradeMove(player, homogeneous_hand, Hand.Hand(available_resource)))

        # trade legality with resource harbor
        for resource in player.harbor_resources():
            cards_out = Hand.Hand(*[resource for _ in range(Consts.RESOURCE_HARBOR_TRADE_RATIO)])
            if player.resource_hand().contains(cards_out):
                for available_resource in self.__available_resources():
                    moves.append(Moves.TradeMove(player, cards_out, Hand.Hand(available_resource)))

        return moves
示例#21
0
 def selectMove(self, board):
     validMoves = Moves.generateMoves(board, self.color)
     return random.choice(validMoves)
示例#22
0
 def ClearMoveList(self):
     self.__data['ActiveSquare'] = 0
     self.__data['MoveList'] = list()
     self.__data['PreviousPlayer'] = ''
     self.__data['CurrentMove'] = Moves.Move()
     self.__data['CurrentMoveIndex'] = -1