예제 #1
0
파일: sim.py 프로젝트: guldfisk/mtgsim
class Player(object):

    def __init__(self, library: Library, strategy: t.Type[Strategy]):
        self._library = library
        self._strategy = strategy
        self.lands = 0

        self._hand = Multiset() #type: Multiset[t.Type[Card]]

    @property
    def hand(self) -> Multiset[t.Type[Card]]:
        return self._hand

    def turn(self, game: Game) -> Player:
        self._strategy.turn(game)
        return self

    def draw(self) -> Player:
        card = self._library.draw()
        if card:
            self._hand.add(card)
        return self

    def draw_hand(self) -> Player:
        for _ in range(7):
            self.draw()
        return self
예제 #2
0
    def _generate(self) -> None:
        self.accept()

        expansions = Multiset()

        for child in self.children():
            if isinstance(child, ExpansionSelectorBox):
                expansions.add(
                    Context.db.expansions[
                        child.expansion_selector.currentText()
                    ],
                    int(child.amounter.text()),
                )

        self._generateable.pool_generated.emit(expansions)
예제 #3
0
    def as_verbose(self, meta_cube: MetaCube) -> VerboseCubePatch:
        group_updates = set()

        for group, new_weight in self.group_map_delta_operation.groups.items():
            current_weight = meta_cube.group_map.groups.get(group)
            if current_weight is None:
                group_updates.add(AddGroup(group, new_weight))
            else:
                if -new_weight == current_weight:
                    group_updates.add(RemoveGroup(
                        group,
                        new_weight,
                    ))
                else:
                    group_updates.add(
                        GroupWeightChange(
                            group,
                            current_weight,
                            current_weight + new_weight,
                        ))

        new_laps: Multiset[Lap] = Multiset({
            lap: multiplicity
            for lap, multiplicity in self._cube_delta_operation.laps
            if multiplicity > 0
        })
        removed_laps: Multiset[Lap] = Multiset({
            lap: -multiplicity
            for lap, multiplicity in self._cube_delta_operation.laps
            if multiplicity < 0
        })

        new_printings: Multiset[Printing] = Multiset({
            printing: multiplicity
            for printing, multiplicity in self._cube_delta_operation.printings
            if multiplicity > 0
        })
        removed_printings: Multiset[Printing] = Multiset({
            printing: -multiplicity
            for printing, multiplicity in self._cube_delta_operation.printings
            if multiplicity < 0
        })

        new_nodes: Multiset[ConstrainedNode] = Multiset({
            node: multiplicity
            for node, multiplicity in self._node_delta_operation.nodes.items()
            if multiplicity > 0
        })

        removed_nodes: Multiset[ConstrainedNode] = Multiset({
            node: -multiplicity
            for node, multiplicity in self._node_delta_operation.nodes.items()
            if multiplicity < 0
        })

        new_printings_cardboard_map = defaultdict(lambda: [])

        for printing in new_printings:
            new_printings_cardboard_map[printing.cardboard].append(printing)

        removed_printings_cardboard_map = defaultdict(lambda: [])

        for printing in removed_printings:
            removed_printings_cardboard_map[printing.cardboard].append(
                printing)

        for printings in itertools.chain(
                new_printings_cardboard_map.values(),
                removed_printings_cardboard_map.values(),
        ):
            printings.sort(key=lambda p: p.expansion.code)

        printing_changes: Multiset[t.Tuple[Printing, Printing]] = Multiset()

        for cardboard in new_printings_cardboard_map.keys(
        ) & removed_printings_cardboard_map.keys():
            new = new_printings_cardboard_map[cardboard]
            removed = removed_printings_cardboard_map[cardboard]
            while new and removed:
                _new = new.pop()
                _removed = removed.pop()
                printing_changes.add((_removed, _new))
                new_printings.remove(_new, 1)
                removed_printings.remove(_removed, 1)

        new_unnested_nodes = sorted(
            (node for node in new_nodes if all(
                isinstance(child, Printing) for child in node.node.children)),
            key=lambda node: len(node.node.children),
            reverse=True,
        )

        printings_moved_to_nodes = Multiset()

        for node in new_unnested_nodes:
            if node.node.children <= removed_printings:
                printings_moved_to_nodes.add((
                    node.node.children,
                    node,
                ))
                removed_printings -= node.node.children

        for _, node in printings_moved_to_nodes:
            new_nodes.remove(node, 1)

        removed_unnested_nodes = sorted(
            (node for node in removed_nodes if all(
                isinstance(child, Printing) for child in node.node.children)),
            key=lambda node: len(node.node.children),
            reverse=True,
        )

        nodes_moved_to_printings = Multiset()

        for node in removed_unnested_nodes:
            if node.node.children <= new_printings:
                nodes_moved_to_printings.add((
                    node.node.children,
                    node,
                ))
                new_printings -= node.node.children

        for _, node in nodes_moved_to_printings:
            removed_nodes.remove(node, 1)

        removed_nodes_by_node: t.Dict[PrintingNode,
                                      t.List[ConstrainedNode]] = {}

        for node in removed_nodes:
            try:
                removed_nodes_by_node[node.node].append(node)
            except KeyError:
                removed_nodes_by_node[node.node] = [node]

        nodes_to_traps: Multiset[t.Tuple[Trap, ConstrainedNode]] = Multiset()

        for lap in new_laps:
            if isinstance(lap, Trap) and lap.node in removed_nodes_by_node:
                nodes_to_traps.add(
                    (lap, removed_nodes_by_node[lap.node].pop()))
                if not removed_nodes_by_node[lap.node]:
                    del removed_nodes_by_node[lap.node]

        for trap, node in nodes_to_traps:
            new_laps.remove(trap, 1)
            removed_nodes.remove(node, 1)

        new_nodes_by_node: t.Dict[PrintingNode, t.List[ConstrainedNode]] = {}

        for node in new_nodes:
            try:
                new_nodes_by_node[node.node].append(node)
            except KeyError:
                new_nodes_by_node[node.node] = [node]

        traps_to_nodes: Multiset[t.Tuple[Trap, ConstrainedNode]] = Multiset()

        for lap in removed_laps:
            if isinstance(lap, Trap) and lap.node in new_nodes_by_node:
                traps_to_nodes.add((lap, new_nodes_by_node[lap.node].pop()))
                if not new_nodes_by_node[lap.node]:
                    del new_nodes_by_node[lap.node]

        for trap, node in traps_to_nodes:
            removed_laps.remove(trap, 1)
            new_nodes.remove(node, 1)

        altered_nodes = []

        for new_node in new_nodes:
            for removed_node in copy.copy(removed_nodes):
                if new_node.node == removed_node.node:
                    removed_nodes.remove(removed_node, 1)
                    altered_nodes.append([removed_node, new_node])
                    break

        for _, new_node in altered_nodes:
            new_nodes.remove(new_node, 1)

        return VerboseCubePatch(
            itertools.chain(
                (AddInfinite(cardboard)
                 for cardboard in self._infinites_delta_operation.added),
                (RemoveInfinite(cardboard)
                 for cardboard in self._infinites_delta_operation.removed),
                group_updates, (PrintingChange(before, after)
                                for before, after in printing_changes),
                (NewCubeable(lap) for lap in new_laps),
                (RemovedCubeable(lap)
                 for lap in removed_laps), (NewCubeable(printing)
                                            for printing in new_printings),
                (RemovedCubeable(printing) for printing in removed_printings),
                (NewNode(node)
                 for node in new_nodes), (RemovedNode(node)
                                          for node in removed_nodes),
                (PrintingsToNode(printings, node)
                 for printings, node in printings_moved_to_nodes),
                (NodeToPrintings(node, printings)
                 for printings, node in nodes_moved_to_printings),
                (NodeToTrap(trap, node) for trap, node in nodes_to_traps),
                (TrapToNode(trap, node) for trap, node in traps_to_nodes),
                (AlteredNode(before, after)
                 for before, after in altered_nodes)))
예제 #4
0
파일: view.py 프로젝트: guldfisk/deckeditor
    def _set_pick_point(self, pick_point: t.Optional[PickPoint],
                        new: bool) -> None:
        if not new:
            return

        self._update_pick_meta()
        self._booster_view.cube_image_view.cancel_drags()

        if pick_point is None:
            self._clear()
            return

        release_id = (pick_point.round.booster_specification.release.id
                      if isinstance(pick_point.round.booster_specification,
                                    CubeBoosterSpecification) else [])

        previous_picks = (
            self._draft_model.draft_client.history.preceding_picks(pick_point)
            if Context.settings.value('ghost_cards', True, bool) else None)

        ghost_cards: t.List[PhysicalCard] = [
            PhysicalCard.from_cubeable(
                cubeable, release_id=release_id, values={'ghost': True})
            for cubeable in previous_picks[0].booster.cubeables -
            pick_point.booster.cubeables
        ] if previous_picks else []

        cards = [
            PhysicalCard.from_cubeable(cubeable, release_id=release_id)
            for cubeable in pick_point.booster.cubeables
        ] + ghost_cards

        if self._draft_model.draft_client.rating_map is not None and settings.SHOW_PICKABLE_RATINGS.get_value(
        ):
            for card in cards:
                rating = self._draft_model.draft_client.rating_map.get(
                    cardboardize(card.cubeable))
                if rating is not None:
                    card.set_info_text(str(rating.rating))
                    card.values['rating'] = rating.rating

        self._booster_scene.get_cube_modification(
            add=cards,
            remove=self._booster_scene.items(),
            closed_operation=True,
        ).redo()
        self._booster_scene.get_default_sort().redo()

        for ghost_card in ghost_cards:
            ghost_card.add_highlight(GHOST_COLOR)
            ghost_card.values['ghost'] = True

        picks = Multiset()
        burns = Multiset()

        for _pick_point in previous_picks + ([pick_point]
                                             if pick_point.pick else []):
            if isinstance(_pick_point.pick, BurnPick):
                picks.add(_pick_point.pick.pick)
                if _pick_point.pick.burn is not None:
                    burns.add(_pick_point.pick.burn)
            else:
                picks.add(_pick_point.pick.cubeable)

        if pick_point == self._draft_model.draft_client.history.current:
            if self._draft_model.pick is not None:
                picks.add(self._draft_model.pick.cubeable)
            if self._draft_model.burn is not None:
                burns.add(self._draft_model.burn.cubeable)

        self._highlight_picks_burns(cards, picks, burns)
예제 #5
0
def check_deck_subset_pool(
    pool: Cube,
    deck: BaseMultiset[Printing],
    exempt_cardboards: t.AbstractSet[Cardboard] = frozenset(),
    *,
    strict: bool = True,
) -> Errors:
    """
    I am to lazy to make this work properly for cases that aren't required yet.
    This does not work properly if copies of the same printing are present in both tickets and traps.
    This also does not work properly if tickets have overlap (although it is not even really well defined how this
    should work)
    """

    if not strict:
        pool = pool.as_cardboards
        deck = FrozenMultiset(p.cardboard for p in deck)

    printings = Multiset(pool.models)
    anys: Multiset[AnyNode] = Multiset()

    for child in itertools.chain(*(trap.node.flattened
                                   for trap in pool.traps)):
        if isinstance(child, NodeAny):
            anys.add(child)
        else:
            printings.add(child)

    ticket_printings = set(itertools.chain(*pool.tickets))

    unaccounted_printings = Multiset({
        printing: multiplicity
        for printing, multiplicity in deck.items() if (
            (printing.cardboard not in exempt_cardboards) if strict else
            (printing not in exempt_cardboards))
    }) - printings

    printings_in_tickets = Multiset()
    printing_to_anys = defaultdict(list)

    flattened_anys = {
        _any: FrozenMultiset(_any.flattened_options)
        for _any in anys.distinct_elements()
    }

    for _any, options in flattened_anys.items():
        for option in options:
            for printing in option:
                printing_to_anys[printing].append(_any)

    any_potential_option_uses = defaultdict(Multiset)

    for unaccounted_printing in unaccounted_printings:
        _anys = printing_to_anys.get(unaccounted_printing)

        if not _anys:
            if unaccounted_printing in ticket_printings:
                printings_in_tickets.add(unaccounted_printing)
                continue
            return Errors([f'Pool does not contain {unaccounted_printing}'])

        for _any in _anys:
            for option in flattened_anys[_any]:
                if unaccounted_printing in option:
                    any_potential_option_uses[_any].add(option)

    uncontested_options = Multiset()
    contested_options = []
    for _any, options in any_potential_option_uses.items():
        for _ in range(anys.elements().get(_any, 0)):
            if not options:
                continue
            if len(options) == 1:
                uncontested_options.update(options.__iter__().__next__())
            else:
                contested_options.append(flattened_anys[_any])

    contested_printings = Multiset(
        printing for printing in unaccounted_printings - uncontested_options
        if not printing in printings_in_tickets)

    combination_printings = Multiset()
    if contested_options:
        solution_found = False
        for combination in itertools.product(*contested_options):
            combination_printings = Multiset(itertools.chain(*combination))
            if contested_printings <= combination_printings:
                solution_found = True
                break
    else:
        solution_found = True

    if not solution_found:
        return Errors(['No suitable combination of any choices'])

    unaccounted_printings -= combination_printings + uncontested_options

    if not unaccounted_printings:
        return Errors()

    printings_to_tickets = defaultdict(set)

    for ticket in pool.tickets:
        for printing in ticket:
            printings_to_tickets[printing].add(ticket)

    tickets_to_printings = defaultdict(list)

    for printing, multiplicity in unaccounted_printings.items():
        for ticket in printings_to_tickets[printing]:
            tickets_to_printings[ticket].append(printing)

    uncontested_tickets = []
    contested_tickets_printings = []
    contested_tickets_tickets = []

    for ticket, printings in tickets_to_printings.items():
        if len(printings) == 1:
            uncontested_tickets.append((ticket, printings[0]))
        else:
            contested_tickets_printings.append(printings)
            contested_tickets_tickets.append(ticket)

    for ticket, printing in uncontested_tickets:
        if _amount_printing_to_required_tickets(
                unaccounted_printings[printing]) > pool.tickets[ticket]:
            return Errors([f'Not enough tickets to pay for {printing}'])

    if contested_tickets_printings:
        solution_found = False
        for combination in itertools.product(*contested_tickets_printings):
            _printings_to_tickets = defaultdict(list)

            for ticket, printing in zip(contested_tickets_tickets,
                                        combination):
                _printings_to_tickets[printing].append(ticket)

            for printing, tickets in _printings_to_tickets.items():
                if _amount_printing_to_required_tickets(
                        unaccounted_printings[printing]) <= sum(
                            pool.tickets[ticket] for ticket in tickets):
                    solution_found = True
                    break

            if solution_found:
                break
    else:
        solution_found = True

    if not solution_found:
        return Errors(['No suitable combination of tickets'])

    return Errors()