Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Code
#1
Python code
snippsat write Oct-17-2022, 03:23 PM:
Added code tag in your post,look at BBCode on how to use.
Reply
#2
Sorry, but that was a lot of coding that you're going to throw away.

You need a deck of Pokemon cards. You have a good start at that with your random_pokemon() function.
def new_deck(count):
    """Make a random deck of "count" pokemon cards."""
    deck = {}
    # random.sample() guarantees no duplicates.  To allow duplicates, use random.choices()
    for i in random.sample(range(1, MAX_POKEMON, k=count):
        response = requests.get(f"https://pokeapi.co/api/v2/pokemon/{i}/).json
        card = {key:response[key] for key in ("name", "id", "height", "weight")}
        deck[card["name"] = card
    return deck
Now that you have a shuffled deck of pokemon cards, it is easy to deal cards.
def deal(count, deck):
    return [deck.pop() for _ in range(count)]
When a card is delt, you pop() it from the deck so that nobody else can have that card.

Now that we have a deck of cards, selecting a card by name is easy:
def select_pokemon(deck):
    """Select a pokemon by name.  If card in deck, return card, else return None"""
    # Should I print available pokemon, or is this a blind guess like "go fish"?
    name = input("Enter pokemon name: ")
    for pokemon in deck:
        if name.lower() == pokemon["name"].lower():
            return pokemon
    return None
Reply
#3
Thats great, thank you, I really appreciate it as I am just learning to code. How do I get the code to print out available pokemon to choose from? I've tried using the print function but which variable to specify has me confused. The user input doesnt appear to flag up either when run.
Reply
#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


Forum Jump:

User Panel Messages

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