Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Code
#4
I tested this code.
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.
Reply


Messages In This Thread
Code - by StoneCherry0119 - Oct-17-2022, 03:40 PM
RE: user to select an object from a randomly generated list from a dictionary - by deanhystad - Oct-19-2022, 04:47 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020