Пример #1
0
    def get_boosters(self, amount: int) -> t.Iterator[Cube]:
        cube = self.release.cube

        if not self.allow_repeat:
            required_cube_size = self.size * (1 if self.allow_intersection else amount)
            if required_cube_size > len(self.release.cube):
                if self.scale:
                    try:
                        cube = cube.scale(required_cube_size)
                    except ValueError:
                        raise GenerateBoosterException('Not enough cubeables, cannot scale empty cube')
                else:
                    raise GenerateBoosterException(
                        f'not enough cubeables, needs {required_cube_size}, only has {len(self.release.cube)}'
                    )

        cubeables = list(cube.cubeables)

        if self.allow_repeat:
            for _ in range(amount):
                yield Cube(random.choices(cubeables, k = self.size))

        elif self.allow_intersection:
            for _ in range(amount):
                yield Cube(random.sample(cubeables, self.size))

        else:
            random.shuffle(cubeables)
            for i in range(amount):
                yield Cube(cubeables[i * self.size: (i + 1) * self.size])
Пример #2
0
def filter_release_view(request: Request, pk: int) -> Response:
    try:
        query = request.query_params['query']
    except KeyError:
        return Response(status=status.HTTP_400_BAD_REQUEST)

    try:
        flattened = strtobool(request.query_params.get(
            'flattened',
            'False',
        ))
    except ValueError:
        return Response(status=status.HTTP_400_BAD_REQUEST)

    search_parser = SearchParser(db)

    try:
        pattern = search_parser.parse(query, PrintingStrategy)
    except ParseException as e:
        return Response(str(e), status=status.HTTP_400_BAD_REQUEST)

    try:
        release = models.CubeRelease.objects.get(pk=pk)
    except models.CubeRelease.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if flattened:
        cube = Cube(cubeables=release.cube.all_printings, )
    else:
        cube = release.cube

    return Response(orpserialize.CubeSerializer.serialize(
        cube.filter(pattern)))
Пример #3
0
 def get_boosters(self, amount: int) -> t.Iterator[Cube]:
     expansions = list(expansion for expansion in db.expansions.values() if expansion.expansion_type == ExpansionType.SET)
     if self.same:
         expansion = random.choice(expansions)
         return (
             Cube(expansion.generate_booster())
             for _ in
             range(amount)
         )
     for _ in range(amount):
         yield Cube(random.choice(expansions).generate_booster())
Пример #4
0
    def check(cls, updater: CubeUpdater) -> t.Optional[ReportNotification]:
        non_garbage_cube = Cube(
            (
                cubeable
                for cubeable in
                updater.cube.cubeables
                if not (
                isinstance(cubeable, Trap)
                and cubeable.intention_type == IntentionType.GARBAGE
            )
            )
        )

        new_no_garbage_cube = Cube(
            (
                cubeable
                for cubeable in
                (updater.cube + updater.patch.cube_delta_operation).cubeables
                if not (
                isinstance(cubeable, Trap)
                and cubeable.intention_type == IntentionType.GARBAGE
            )
            )
        )

        old_cardboards = FrozenMultiset(
            printing.cardboard
            for printing in
            itertools.chain(
                non_garbage_cube.all_printings,
                updater.node_collection.all_printings,
            )
        )

        new_cardboards = FrozenMultiset(
            printing.cardboard
            for printing in
            itertools.chain(
                new_no_garbage_cube.all_printings,
                (updater.node_collection + updater.patch.node_delta_operation).all_printings,
            )
        )

        return CardboardChange(
            FrozenCounter(
                new_cardboards.elements()
            ) - FrozenCounter(
                old_cardboards.elements()
            )
        )
Пример #5
0
    def perform_pick(self, pick: BurnPick) -> bool:
        if len(self._current_booster.cubeables) > 1 and pick.burn is None:
            return False

        pick_remove = Cube(
            (pick.pick, pick.burn)) if pick.burn is not None else Cube(
                (pick.pick, ))

        if not pick_remove.cubeables <= self._current_booster.cubeables.cubeables:
            return False

        self._current_booster.cubeables -= pick_remove
        self._pool += Cube((pick.pick, ))

        return True
Пример #6
0
 def get_boosters(self, amount: int) -> t.Iterator[Cube]:
     expansion = db.expansions[self.expansion_code]
     return (
         Cube(expansion.generate_booster())
         for _ in
         range(amount)
     )
Пример #7
0
 def deserialize(cls, value: serialization_model,
                 inflator: Inflator) -> MetaCube:
     return cls(
         Cube.deserialize(value['cube'], inflator),
         NodeCollection.deserialize(value['nodes'], inflator),
         GroupMap.deserialize(value['groups'], inflator),
         Infinites.deserialize(value['infinites'], inflator),
     )
Пример #8
0
    def difference_report(self) -> CubeDelta:

        cubes = self._cube_loader.all_cubes()

        current_cube, _ = next(cubes, Cube())
        previous_cube, _ = next(cubes, Cube())

        delta = CubeDelta(previous_cube, current_cube)

        self.proxy_cube(cube=delta.new_cubeables,
                        file_name=os.path.join(self.OUT_DIR, 'new_laps.pdf'))

        self.proxy_cube(cube=delta.removed_cubeables,
                        file_name=os.path.join(self.OUT_DIR,
                                               'removed_laps.pdf'))

        return delta
Пример #9
0
    def perform_pick(self, pick: SinglePickPick) -> bool:
        if pick.cubeable not in self._current_booster.cubeables:
            return False

        _pick = Cube((pick.cubeable, ))
        self._current_booster.cubeables -= _pick
        self._pool += _pick

        return True
Пример #10
0
 def create(cls,
            cube: Cube,
            versioned_cube: VersionedCube,
            infinites: Infinites,
            intended_size: int = 360) -> CubeRelease:
     return cls.objects.create(
         cube=cube,
         checksum=cube.persistent_hash(),
         name=NameGenerator().get_name(
             int(
                 hashlib.sha1(
                     cube.persistent_hash().encode('ASCII')).hexdigest(),
                 16,
             )),
         versioned_cube=versioned_cube,
         intended_size=intended_size,
         infinites=infinites,
     )
Пример #11
0
    def _construct_cube(self, tsv: t.List[t.List[str]]) -> Cube:
        traps = []
        printings = []
        tickets = []
        purples = []

        exceptions = []  #type: t.List[t.Tuple[str, Exception]]

        def _parse_all_cells(
            cells: t.Iterable[str],
            arguments: t.Iterable[str],
            parser: t.Callable[[str, str], T],
        ) -> t.Iterable[T]:

            for _cell, arg in itertools.zip_longest(cells,
                                                    arguments,
                                                    fillvalue=''):
                if _cell:
                    try:
                        yield parser(_cell, arg)
                    except CubeParseException as e:
                        exceptions.append((_cell, e))

        for column, args in itertools.zip_longest(
                tsv, tsv[1:], fillvalue=['' for _ in range(len(tsv[-1]))]):

            if column[0] == 'TRAPS':
                traps.extend(
                    list(
                        _parse_all_cells(column[2:], args[2:],
                                         self._parse_trap_cell)))

            if column[0] == 'GARBAGE_TRAPS':
                traps.extend(
                    list(
                        _parse_all_cells(column[2:], (),
                                         self._parse_trap_cell)))

            elif column[0] in ('W', 'U', 'B', 'R', 'G', 'HYBRID', 'GOLD',
                               'COLORLESS', 'LAND'):
                printings.extend(
                    _parse_all_cells(column[2:], args[2:],
                                     self._parse_printing))

            elif column[0] == 'TICKETS':
                tickets = list(
                    _parse_all_cells(column[2:], args[2:], self._parse_ticket))

            elif column[0] == 'PURPLES':
                purples = list(
                    _parse_all_cells(column[2:], args[2:], self._parse_purple))

        if exceptions:
            raise CubeParseException(exceptions)

        return Cube(itertools.chain(printings, traps, tickets, purples))
Пример #12
0
    def _copy(self):
        cards = self._scene.selectedItems()

        if not cards:
            return

        stream = QtCore.QByteArray(
            PickleStrategy.serialize(Cube(card.cubeable for card in cards)))

        mime = QtCore.QMimeData()

        mime.setData('cards', stream)

        Context.clipboard.setMimeData(mime)
Пример #13
0
    def get(self, request: Request, *args, **kwargs) -> Response:
        try:
            native = strtobool(self.request.query_params.get(
                'native', 'False'))
        except ValueError:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        return Response(
            status=status.HTTP_200_OK,
            data=(RawStrategy
                  if native else orpserialize.CubeSerializer).serialize(
                      Cube(
                          random.sample(
                              list(self.get_object().deck.maindeck),
                              7,
                          ))))
Пример #14
0
 def perform_create(self, serializer):
     with transaction.atomic():
         versioned_cube = serializer.save(author=self.request.user)
         release = models.CubeRelease.create(
             cube=Cube(),
             versioned_cube=versioned_cube,
             infinites=Infinites((db.cardboards[c] for c in (
                 'Plains',
                 'Island',
                 'Swamp',
                 'Mountain',
                 'Forest',
             ))),
         )
         models.ConstrainedNodes.objects.create(
             constrained_nodes=NodeCollection(()),
             group_map=GroupMap({}),
             release=release,
         )
Пример #15
0
    def __init__(self, drafter: Drafter, draft: Draft, draft_seat: DraftSeat):
        super().__init__()
        self._drafter = drafter
        self._draft = draft
        self._draft_seat = draft_seat

        self._pool = Cube()

        self._messages: t.List[t.Mapping[str, t.Any]] = []
        self._pick_counter = 0

        self._booster_queue = Queue()
        self._pick_queue = Queue()
        self._out_queue = Queue()

        self._current_booster: t.Optional[DraftBooster] = None

        self._terminating = threading.Event()

        self._booster_pusher = threading.Thread(target=self._draft_loop)

        self._connect_lock = threading.Lock()
        self._consumer: t.Optional[WebsocketConsumer] = None
Пример #16
0
 def get_boosters(self, amount: int) -> t.Iterator[Cube]:
     booster_map = BoosterKey(
         (RARE_MYTHIC_SLOT,)
         + (UNCOMMON_SLOT,) * 3
         + (COMMON_SLOT,) * 11
     ).get_booster_map(
         [
             printing
             for printing in
             db.printings.values()
             if printing.cardboard.latest_printing.expansion.expansion_type != ExpansionType.FUNNY
         ] if self.respect_printings else [
             cardboard.latest_printing
             for cardboard in
             db.cardboards.values()
             if cardboard.latest_printing.expansion.expansion_type != ExpansionType.FUNNY
         ]
     )
     return (
         Cube(booster_map.generate_booster())
         for _ in
         range(amount)
     )
Пример #17
0
def sample_pack(request: Request, pk: int, size: int) -> Response:
    try:
        release = models.CubeRelease.objects.get(pk=pk)
    except models.CubePatch.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    r = random.Random()
    seed = request.GET.get('seed') or ''.join(
        random.choice(string.ascii_letters) for _ in range(16))
    r.seed(seed)

    try:
        return Response({
            'pack':
            orpserialize.CubeSerializer.serialize(
                Cube(
                    r.sample(
                        sorted(release.cube.cubeables,
                               key=lambda p: str(p.id)), size))),
            'seed':
            seed,
        })
    except ValueError:
        return Response('Pack to large', status=status.HTTP_400_BAD_REQUEST)
Пример #18
0
 def get(self, request, *args, **kwargs):
     seat: models.DraftSeat = self.get_object()
     picks = list(seat.picks.all().order_by('global_pick_number')[:int(kwargs['pick']) + 1])
     return Response(
         {
             'seat': serializers.DraftSeatSerializer(seat, context = {'request': request}).data,
             'pool': CubeSerializer.serialize(
                 Cube(
                     itertools.chain(
                         *(
                             pick.pick.added_cubeables
                             for pick in
                             picks[:-1]
                         )
                     )
                 )
             ),
             'pick': serializers.DraftPickSerializer(
                 picks[-1],
                 context = {'request': request},
             ).data if picks else None,
             'pick_count': seat.picks.all().count(),
         }
     )
Пример #19
0
 def cube(self) -> Cube:
     return Cube(item.cubeable for item in self.items()
                 if isinstance(item, SceneCard))
Пример #20
0
 def deserialize(cls, value: serialization_model,
                 inflator: Inflator) -> FantasySet:
     return cls({
         k: Cube.deserialize(v, inflator)
         for k, v in value['rarity_map'].items()
     })
Пример #21
0
 def get_finale_cube(self, new_garbage: t.Optional[TrapCollection]) -> Cube:
     if new_garbage is None:
         return self.new_cube
     else:
         return self.new_cube - Cube(
             self.new_cube.garbage_traps) + Cube(new_garbage)
Пример #22
0
 def from_primitive_deck(cls, deck: OrpDeck) -> Deck:
     return cls(
         Cube(deck.maindeck),
         Cube(deck.sideboard),
     )
Пример #23
0
 def deserialize(cls, value: serialization_model,
                 inflator: Inflator) -> Deck:
     return cls(
         maindeck=Cube.deserialize(value['maindeck'], inflator),
         sideboard=Cube.deserialize(value['sideboard'], inflator),
     )
Пример #24
0
 def __init__(self, non_existent_removed_cubeables: FrozenMultiset[Cubeable]):
     self._non_existent_removed_cubeables = Cube(non_existent_removed_cubeables)