Oct-19-2022, 04:47 PM
I tested this code.
I made a dataclass for the pokemon cards. The dataclass does nice things like providing a function for making a pretty string when you print a card, providing comparison methods so you can sort cards, or compare cards. Currently it compares cards using their ID, you might find a better attribute.
from dataclasses import dataclass import requests, random MAX_POKEMON = 905 POKEMON_LINK = "https://pokeapi.co/api/v2/pokemon/" @dataclass(order=True) class Pokemon: """Info about a Pokemon. dataclass provides __str__, == and sorting """ id: int name: str height: int weight: int def __init__(self, id, name, height, weight, **kwargs): self.id = id self.name = name.title() self.height = height self.weight = weight def new_deck(count, end=MAX_POKEMON, start=1): """Make a random deck of "count" pokemon cards.""" # random.sample() guarantees no duplicates. To allow duplicates, use random.choices() ids = random.sample(range(start, end+1), k=count) return [Pokemon(**requests.get(f"{POKEMON_LINK}/{id}/").json()) for id in ids] def deal(count, deck): """Deal count cards from deck. Return list of cards.""" return [deck.pop() for _ in range(count)] def print_cards(cards, title=None): """Print a list of cards""" if title: print(title) print(*cards, "", sep="\n") def get_card(name, deck): """Find card by name. Return matching card or None.""" name = name.title() for card in deck: if card.name == name: return card return None # Create a deck of cards and deal a hand deck = new_deck(10) hand = sorted(deal(5, deck)) # Try printing some cards print_cards(hand, "Hand") print_cards(sorted(deck), "Deck") # Try picking a card by name print("Picking \"Daffy Duck\"", get_card("Daffy Duck", deck)) print(f"Picking \"{deck[2].name}\"", get_card(deck[2].name, deck))It makes more sense for a deck of cards to be a list than a dictionary. Selecting a card by name can be done with a loop and doesn't take too long for something as a deck of cards.
I made a dataclass for the pokemon cards. The dataclass does nice things like providing a function for making a pretty string when you print a card, providing comparison methods so you can sort cards, or compare cards. Currently it compares cards using their ID, you might find a better attribute.