def search(self, search_term: str) -> List[SearchResult]:
        """
        Search the pokemontcg.io API for cards with the given search term.

        :param search_term: The search to give to the API
        :returns: A list of search results given from the search
        """
        # Users will often enter 'hydreigon ex' when they really mean
        # 'hydreigon-ex'. This annoying, but simply inserting the dash does not
        # work as it makes Ruby/Sapphire era ex cards unaccessible. Instead,
        # search for both
        cards = []
        if search_term.lower().endswith(' ex'):
            cards.extend(Card.where(name=search_term.lower()))
            cards.extend(
                Card.where(name=search_term.lower().replace(' ex', '-ex')))
        # GX cards do not have the same issue, so we can simply insert the dash
        # as expected
        elif search_term.lower().endswith(' gx'):
            cards.extend(
                Card.where(name=search_term.lower().replace(' gx', '-gx')))
        # Hardcode the card 'N' to search for the specific card, not all cards
        # with the letter n within their name
        elif search_term.lower() == "n":
            cards = Card.where(name="\"N\"")
        # Otherwise, search for the given text
        else:
            cards = Card.where(name=search_term)

        return sorted([
            PokemonTCGIOV1Provider._card_to_searchresult(card)
            for card in cards
        ],
                      key=lambda result: result.release)
예제 #2
0
def parse_card(name, card_set):
	# If the card set includes a specific number, we can just use that to
	# get the card
	card = None
	if "-" in card_set:
		card = Card.find(card_set)
		if card == None:
			return "No results for card `%s`" % card_set
	else:
		# Search for the given card
		cards = Card.where(name = name, setCode=card_set)

		if len(cards) == 0:
			return ("No results found for '%s' in set `%s`" %
				(name, card_set))

		if len(cards) > 1:
			return (
"""
Too many results. Try specifying the card number too. For example
`!show %s %s-%s`
""" % (name, card_set, cards[0].number)
			)

		card = cards[0]
	return card
예제 #3
0
def parse_card(name, card_set):
    # If the card set includes a specific number, we can just use that to
    # get the card
    card = None
    if "-" in card_set:
        card_part = card_set.split("-")
        for set_code, setid in sets.items():
            if set_code in card_set:
                card_set = card_set.replace(card_part[0], setid.lower())
        card = Card.find(card_set)
        if card is None:
            return "No results for card `%s`" % card_set
    else:
        # Check if a Set Abbreviation was used instead
        nums = set('0123456789')
        for set_code, setid in sets.items():
            card_set = card_set.replace(set_code, setid)
        
        # Verify Set Abbreviation was replaced
        if any((n in nums) for n in card_set):
            # Search for the given card
            cards = Card.where(q=f'name:{name} set.id:{card_set}')

            if len(cards) == 0:
                return "No results found for '%s' in set `%s`" % (name, card_set)

            if len(cards) > 1:
                return ("Too many results. Try specifying the card number too. "
                        "For example `[p]show %s %s-%s`" % (name, card_set, cards[0].number))

            card = cards[0]
        else:
            return ("Set Abbreviation wasn't found. Double check and try again.")
   
    return card    
예제 #4
0
def search(name):
    if name == "":
        return ("", 0)

    # Users will often enter 'hydreigon ex' when they really mean
    # 'hydreigon-ex'. This annoying, but simply inserting the dash does not
    # work as it makes Ruby/Sapphire era ex cards unaccessible. Instead,
    # search for both
    cards = []
    if name.lower().endswith(" ex"):
        cards.extend(Card.where(name=name.lower()))
        cards.extend(Card.where(name=name.lower().replace(" ex", "-ex")))
    # GX cards do not have the same issue, so we can simply insert the dash
    # as expected
    elif name.lower().endswith(" gx"):
        cards.extend(Card.where(name=name.lower().replace(" gx", "-gx")))
    # Delta card text replacement
    elif name.lower().endswith(" delta"):
        cards.extend(Card.where(name=name.lower().replace(" delta", " δ")))
    # Otherwise, search for the given text
    else:
        cards = Card.where(name=name)

    # Give an error if there are no matches
    if len(cards) == 0:
        return ("No matches for search '%s'" % name, 0)

    # If there is exactly one match, save time for the user and give the
    # !show output instead
    if len(cards) == 1:
        return (show(cards[0].name, cards[0].set_code), 1)

    # If there are matches, build a string with the name, set and set code
    # of every match
    cards_with_sets = []
    for card in cards:
        card_set = Set.find(card.set_code)

        # Re-arrange the release data so it is ISO
        date_split = card_set.release_date.split("/")
        card_set.release_date = "%s-%s-%s" % (date_split[2], date_split[0],
                                              date_split[1])

        cards_with_sets.append((card, card_set))

    # Sort the list of cards by set release date
    cards_with_sets.sort(key=lambda card: card[1].release_date)

    # Create the returned string
    return_str = "Matches for search '%s'\n" % name
    for card in cards_with_sets:
        return_str += ("%s - %s %s/%s (`%s-%s`)\n" %
                       (card[0].name, card[1].name, card[0].number,
                        card[1].total_cards, card[1].code, card[0].number))

    return (return_str, len(cards_with_sets))
예제 #5
0
def search(name):
    if name == "":
        return ("", 0)

    # Users will often enter 'hydreigon ex' when they really mean
    # 'hydreigon-ex'. This annoying, but simply inserting the dash does not
    # work as it makes Ruby/Sapphire era ex cards unaccessible. Instead,
    # search for both
    cards = []
    if name.lower().endswith(" ex"):
        cards.extend(Card.where(q=f'name:"{name.lower()}"'))
        cards.extend(
            Card.where(q=f'name:"{name.lower().replace(" ex", "-ex")}"'))
    # GX cards do not have the same issue, so we can simply insert the dash
    # as expected
    elif name.lower().endswith(" gx"):
        cards.extend(
            Card.where(q=f'name:"{name.lower().replace(" gx", "-gx")}"'))
    # Delta card text replacement
    elif name.lower().endswith(" delta"):
        cards.extend(
            Card.where(q=f'name:"{name.lower().replace(" delta", " δ")}"'))
    # Handling "N"
    elif name.lower() == "n":
        return_str = "Matches for search 'N'\n"
        return_str += "N - Noble Victories 92/101 (`bw3-92`)\n"
        return_str += "N - Noble Victories 101/101 (`bw3-101`)\n"
        return_str += "N - Dark Explorers 96/108 (`bw5-96`)\n"
        return_str += "N - BW Black Star Promos BW100 (`bwp-BW100`)\n"
        return_str += "N - Fates Collide 105/124 (`xy10-105`)\n"
        return_str += "N - Fates Collide 105a/124 (`xy10-105a`)\n"

        return (return_str, 6)
    # Otherwise, search for the given text
    else:
        cards = Card.where(q=f'name:"{name}"', orderBy="set.releaseDate")

    # Give an error if there are no matches
    if len(cards) == 0:
        return ("No matches for search '%s'" % name, 0)

    # If there is exactly one match, save time for the user and give the
    # !show output instead
    if len(cards) == 1:
        return (show(cards[0].name, cards[0].id), 1)

    # Create the returned string
    return_str = "Matches for search '%s'\n" % name
    for card in cards:
        return_str += ("%s - %s %s/%s (`%s-%s`)\n" %
                       (card.name, card.set.name, card.number,
                        card.set.printedTotal, card.set.id, card.number))

    return (return_str, len(cards))
    def test_find_returns_card(self):
        with vcr.use_cassette('fixtures/gardevoir.yaml'):
            card = Card.find('xy7-54')

            self.assertEqual('Gardevoir', card.name)
            self.assertEqual('xy7-54', card.id)
            self.assertEqual(282, card.national_pokedex_number)
            self.assertEqual('https://images.pokemontcg.io/xy7/54.png', card.image_url)
            self.assertEqual('Stage 2', card.subtype)
            self.assertEqual('Pokémon', card.supertype)
            self.assertEqual('Bright Heal', card.ability['name'])
            self.assertEqual('Once during your turn (before your attack), you may heal 20 damage from each of your Pokémon.',card.ability['text'])
            self.assertEqual('130', card.hp)
            self.assertEqual(['Colorless', 'Colorless'], card.retreat_cost)
            self.assertEqual(2, card.converted_retreat_cost)
            self.assertEqual('54', card.number)
            self.assertEqual('TOKIYA', card.artist)
            self.assertEqual('Rare Holo', card.rarity)
            self.assertEqual('XY', card.series)
            self.assertEqual('Ancient Origins', card.set)
            self.assertEqual('xy7', card.set_code)
            self.assertEqual(['Fairy'], card.types)
            self.assertTrue(len(card.attacks) == 1)
            self.assertTrue(len(card.weaknesses) == 1)
            self.assertTrue(len(card.resistances) == 1)
예제 #7
0
 def getCard(self, cardSet, cardNum):
     """
     :param cardSet: Name of the set the card is in
     :param cardNum: number of the card in the set
     :return: Card object with all card attributes
     """
     return Card.find(id=f"{self.setDict[cardSet].lower()}-{str(cardNum)}")
    def test_find_returns_card(self):
        with vcr.use_cassette('fixtures/gardevoir.yaml'):
            card = Card.find('xy7-54')

            self.assertEqual('Gardevoir', card.name)
            self.assertEqual('xy7-54', card.id)
            self.assertEqual(282, card.national_pokedex_number)
            self.assertEqual('https://s3.amazonaws.com/pokemontcg/xy7/54.png',
                             card.image_url)
            self.assertEqual('Stage 2', card.subtype)
            self.assertEqual('Pokémon', card.supertype)
            self.assertEqual('Bright Heal', card.ability['name'])
            self.assertEqual(
                'Once during your turn (before your attack), you may heal 20 damage from each of your Pokémon.',
                card.ability['text'])
            self.assertEqual('130', card.hp)
            self.assertEqual(['Colorless', 'Colorless'], card.retreat_cost)
            self.assertEqual('54', card.number)
            self.assertEqual('TOKIYA', card.artist)
            self.assertEqual('Rare Holo', card.rarity)
            self.assertEqual('XY', card.series)
            self.assertEqual('Ancient Origins', card.set)
            self.assertEqual('xy7', card.set_code)
            self.assertEqual(['Fairy'], card.types)
            self.assertTrue(len(card.attacks) == 1)
            self.assertTrue(len(card.weaknesses) == 1)
            self.assertTrue(len(card.resistances) == 1)
예제 #9
0
def get_cards(format):
    get_sets()
    sets = req_format(format)

    check_path()
    h = open('archive/cards/hashed_cards.txt', "r")
    check = h.read().splitlines()
    h.close()

    for set in sets:
        print(set['name'])
        count = 1

        for card in range(set['size']):
            try:
                req = str(set['req_id'] + '-' + str(count))
                raw_card = str(Card.find(req))

                card = strip_card(raw_card, count, set['id'])
                
                if(card['hash'] in check):
                    print('found redundant card | skipping set')
                    break

                save_card(card)
                print(set['id'], count,"| saved to", card['supertype'],"|", card['hash'], "|", card['name'])
                

                count +=1
            except:
                print("req error | probaly a promo set")
                time.sleep(2)
                break

        print()
예제 #10
0
 def test_find_returns_card(self):
     with vcr.use_cassette('fixtures/gardevoir.yaml'):
         card = Card.find('xy7-54')
         self.assertEqual('xy7-54', card.id)
         self.assertEqual('Gardevoir', card.name)
         self.assertEqual('Pokémon', card.supertype)
         self.assertEqual(['Stage 2'], card.subtypes)
         self.assertEqual('130', card.hp)
         self.assertEqual(['Fairy'], card.types)
         self.assertEqual('Kirlia', card.evolvesFrom)
         self.assertTrue(len(card.abilities) == 1)
         self.assertTrue(len(card.attacks) == 1)
         self.assertTrue(len(card.weaknesses) == 1)
         self.assertTrue(len(card.resistances) == 1)
         self.assertEqual(['Colorless', 'Colorless'], card.retreatCost)
         self.assertEqual(2, card.convertedRetreatCost)
         self.assertEqual('xy7', card.set.id)
         self.assertEqual('54', card.number)
         self.assertEqual('TOKIYA', card.artist)
         self.assertEqual('Rare Holo', card.rarity)
         self.assertEqual(
             'It has the power to predict the future. Its power peaks when it is protecting its Trainer.',
             card.flavorText)
         self.assertEqual([282], card.nationalPokedexNumbers)
         self.assertEqual('https://prices.pokemontcg.io/tcgplayer/xy7-54',
                          card.tcgplayer.url)
    def test_all_with_params_return_cards(self):
        with vcr.use_cassette('fixtures/mega_pokemon.yaml'):
            cards = Card.where(supertype='pokemon') \
                        .where(subtype='mega') \
                        .all()

            self.assertTrue(len(cards) >= 70)
예제 #12
0
def get_cards_from_sets(sets):
    cards = []
    for set in sets:
        print(set.name)
        set_cards = Card.where(set=set.name)
        for card in set_cards:
            cards.append(card)
    return remove_duplicate_card_names(cards)
예제 #13
0
def showPokemonData():
    #get the number typed into the entry box
    pokemonNumber = randint(0, 99)

    #use the function above to get the pokemon data
    pokemon = Card.where(page=1).array()[pokemonNumber]

    #get the data from the dictionary and add it to the labels
    lblNameValue.configure(text=pokemon.get('name'))
    lblHPValue.configure(text=pokemon.get('hp'))
    lblAttackValue.configure(text=pokemon.get('attacks')[0]['damage']
                             if pokemon.get('attacks') else '?')
    lblDefenceValue.configure(text=pokemon.get("resistances")[0]['type'])
예제 #14
0
def getOptions():
    global options
    global chosenSets
    global probs
    recalc=0
    while(recalc<20):
        cset = np.random.choice(chosenSets,1)
        ctype = np.random.choice([p[0] for p in probs],p=[p[1] for p in probs])
        try:
            options = np.random.choice(Card.where(set=cset[0], supertype=ctype),NOPTIONS,replace=False)
            recalc+=100
        except ValueError:
            recalc+=1
    return [card.image_url_hi_res for card in options]
예제 #15
0
def getCardByName(cardName, cardSet, cardID, literal, superType):
    if not cardSet:
        card = Card.where(name=cardName).all()
    else:
        card = Card.where(name=cardName).where(set=cardSet).all()
    if literal:
        result = []
        for i in card:
            if re.findall('^' + cardName + '$', i.name):
                result.append(i)
        card = result
    if superType:
        result = []
        for i in card:
            if i.supertype[0] == superType[0]:
                result.append(i)
        card = result
    if cardID:
        result = []
        for i in card:
            if re.findall(str(cardID) + '$', i.id):
                result.append(i)
        card = result
    return card
예제 #16
0
def getCard():
    name = request.args.get('name')
    cards = []
    try:
        cards = Card.where(name=name)
    except:
        return

    pokelista = []
    for card in cards:
        pokelista.append({
            'name': card.name,
            'imageUrl': card.image_url,
            'id': card.id
        })
    return (jsonify(pokelista), 200)
예제 #17
0
파일: main.py 프로젝트: zturchan/prizecam
def fetch_alternate_version_of_card(card):
    # Subtype filter needed for cases like special darkness energy
    versions_of_card = Card.where(name=card.name, subtype=card.subtype)

    for version in versions_of_card:
        try:
            print(version.id)
            version_photo = getphoto(version.image_url, version.id)
            break
        except AttributeError:
            # Happens due to a bug in pillow 5.4.1 where some cards with EXIF data cause pillow to barf
            # In that case, try and find an alternate card image
            # This mostly occurs on certain secret rares, esp from Ultra Prism
            pass
    if (version_photo):
        return version_photo
    return get_back_photo()
예제 #18
0
def main():
    print("Downloading all cards... Please be patient")

    fields_remain_same = [
        'id', 'name', 'national_pokedex_number', 'image_url',
        'image_url_hi_res', 'subtype', 'supertype', 'hp', 'number', 'artist',
        'rarity', 'series', 'set', 'set_code', 'converted_retreat_cost',
        'evolves_from'
    ]

    set_fields = [
        'total_cards', 'standard_legal', 'expanded_legal', 'release_date'
    ]

    cards = Card.all()
    sets = Set.all()

    create_workbook(cards, fields_remain_same, sets, set_fields)
예제 #19
0
def insert_cards(set_name):
    cards = Card.where(q='set.name:{}'.format(set_name))
    sets = Set.all()

    sets_to_save = []
    for set in sets:
        sets_to_save.append(PokemonCardSet(id=set.id, name=set.name))

    overlap, inserted = _dedupe_and_insert(PokemonCardSet, sets_to_save)

    cards_to_save = []
    for card in cards:
        cards_to_save.append(
            PokemonCard(id=card.id,
                        name=card.name,
                        set=PokemonCardSet.objects.get(id=card.set.id)))

    overlap, inserted = _dedupe_and_insert(PokemonCard, cards_to_save)

    return overlap, inserted
def search(name):
	# Search for the given text
	cards = Card.where(name = name).all()

	if name == "":
		return

	# Give an error if there are no matches
	if len(cards) == 0:
		return "No matches for search '%s'" % name

	# If there is exactly one match, save time for the user and give the
	# !show output instead
	if len(cards) == 1:
		return show(cards[0].name, cards[0].set_code)

	# If there are matches, build a string with the name, set and set code
	# of every match
	cards_with_sets = []
	for card in cards:
		card_set = Set.find(card.set_code)

		# Re-arrange the release data so it is ISO
		date_split = card_set.release_date.split("/")
		card_set.release_date = ("%s-%s-%s" %
			(date_split[2], date_split[0], date_split[1]))

		cards_with_sets.append((card, card_set))

	# Sort the list of cards by set release date
	cards_with_sets.sort(key = lambda card : card[1].release_date)

	# Create the returned string
	return_str = "Matches for search '%s'\n" % name
	for card in cards_with_sets:
		return_str += ("%s - %s %s/%s (`%s-%s`)\n" %
			(card[0].name, card[1].name, card[0].number,
			 card[1].total_cards, card[1].code, card[0].number))
	return return_str
예제 #21
0
 def test_all_with_page_returns_cards(self):
     with vcr.use_cassette('fixtures/all_first_page.yaml'):
         cards = Card.where(page=1)
         self.assertEqual(250, len(cards))
예제 #22
0
#!/usr/bin/env python3

import requests
import traceback

from pokemontcgsdk import Card
# from pokemontcgsdk import Set
# from pokemontcgsdk import Type
# from pokemontcgsdk import Supertype
# from pokemontcgsdk import Subtype

# requests.packages.urllib3.disable_warnings()

log = open("log.txt", "w")
session = requests.Session()
session.verify = False

try:
    cards = Card.where(page=5, pageSize=100)
    print(card)

except Exception:
    traceback.print_exc(file=log)


예제 #23
0
def new_set(set_):
    new_set_ = Set.where(name=set_)
    cards = Card.where(set=set_)
    for card in cards:
        input_card(card)
예제 #24
0
from pokemontcgsdk import Card

#Getting pokes from specific set
cards = Card.where(set="FireRed & LeafGreen")

#Array to handle pokes objects
pokemons_list = []

#Class to get each pokemon from api
class Pokemon():
    def __init__(self, name, number, image_url, supertype, subtype, rarity):
        self.name = name
        self.number = number
        self.image_url = image_url
        self.supertype = supertype
        self.subtype = subtype
        self.rarity = rarity


    def return_by_name(self, name):
        if self.name == name:
            return self

#Creating json
for card in cards:
    poke = Pokemon(card.name, card.number, card.image_url, card.supertype, card.subtype, card.rarity)
    pokemons_list.append(poke)
예제 #25
0
 def test_all_with_params_return_cards(self):
     with vcr.use_cassette('fixtures/mega_pokemon.yaml'):
         cards = Card.where(supertype='pokemon', subtype='mega')
         self.assertTrue(len(cards) >= 70)
예제 #26
0
        fire_energy,
        grass_energy,
        lightning_energy,
        metal_energy,
        psychic_energy,
        water_energy,
    )

    c = conn.cursor()
    if energy_cost_attackID:
        c.execute(
            "DELETE FROM EnergyCost WHERE cardID=? AND costType=? AND attackID=?",
            (card_id, energy_cost_type, energy_cost_attackID))
    else:
        c.execute(
            "DELETE FROM EnergyCost WHERE cardID=? AND costType=? AND attackID IS NULL",
            (card_id, energy_cost_type))
    c.execute("INSERT INTO EnergyCost VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
              energy_index)
    print("Inserted EnergyCost: {} {} {} {}".format(card_id, energy_cost_type,
                                                    energy_cost_attackID,
                                                    energy_cost_converted))


cards = Card.where(set='generations').where(supertype='pokemon').all()
conn = create_connection("ptcg.db")
for card in cards:
    insert_card(card)
conn.commit()
conn.close()
예제 #27
0
 def test_all_with_page_returns_cards(self):
     with vcr.use_cassette('fixtures/all_first_page.yaml'):
         cards = Card.where(page=1)
         self.assertEqual(100, len(cards))
예제 #28
0
 def test_all_with_page_and_page_size_returns_card(self):
     with vcr.use_cassette('fixtures/all_first_page_one_card.yaml'):
         cards = Card.where(page=1, pageSize=1)
         self.assertEqual(1, len(cards))
예제 #29
0
#! /usr/bin/env python

from pokemontcgsdk import Card
from pokemontcgsdk import Set
from pokemontcgsdk import Type
from pokemontcgsdk import Supertype
from pokemontcgsdk import Subtype
import json

#Gets all info needed
cards = Card.all()
sets = Set.all()
types = Type.all()
subtypes = Subtype.all()
supertypes = Supertype.all()

print('Resources gathered, converting to json...')

#Loops through all cards an eliminates all NoneTypes to eliminate excess null values in json
cards_list = []
for c in cards:
    card_dict = {}

    if c.id is not None:
        card_dict["id"] = c.id

    if c.name is not None:
        card_dict["name"] = c.name

    if c.national_pokedex_number is not None:
        card_dict["national_pokedex_number"] = c.national_pokedex_number
    def show(self, card_id: str) -> Optional[ShowResult]:
        """
        Get details on a specific card.

        :param card_id: The unique ID on the card
        :returns: The result of the card lookup, or None if no card matches
        """
        card = Card.find(card_id)
        card_set = Set.find(card.set_code)
        if not card:
            return None

        if card.supertype == "Pokémon":
            fields = []

            # If the Pokemon has an ability, it goes in its own field
            if card.ability:
                fields.append(
                    (f"{card.ability['type']}: {card.ability['name']}",
                     card.ability["text"] or "\u200b"))

            # Each attack is its own field
            if card.attacks:
                for attack in card.attacks:
                    name = ""
                    text = ""
                    for cost in attack["cost"]:
                        name += emoji[cost]
                    name += f" {attack['name']}"
                    if "damage" in attack and attack["damage"] != "":
                        name += f" - {attack['damage']}"
                    if "text" in attack and attack["text"] != "":
                        text = attack["text"]
                    else:
                        text = "\u200b"
                    fields.append((name, text))

            # Weakness, resistances and retreat all go on the same line
            bottom_line = ""
            if card.weaknesses:
                bottom_line += "Weakness: "
                bottom_line += ", ".join([
                    f"{emoji[w['type']]} ({w['value']})"
                    for w in card.weaknesses
                ])
            if card.resistances:
                bottom_line += " - Resistance: "
                bottom_line += ", ".join([
                    f"{emoji[r['type']]} ({r['value']})"
                    for r in card.resistances
                ])
            if card.retreat_cost:
                bottom_line += f" - Retreat: {emoji['Colorless'] * len(card.retreat_cost)}"
            if bottom_line != "":
                fields.append(("\u200b", bottom_line))

            return ShowResult(
                name=card.name,
                supertype=card.supertype,
                subtype=card.subtype,
                legality=PokemonTCGIOV1Provider._newest_legal_format(card),
                set_name=card_set.name,
                set_no=card.number,
                set_max=card_set.total_cards,
                image=card.image_url,
                set_icon=card_set.symbol_url,
                fields=fields,
                hp=card.hp,
                evolves_from=card.evolves_from,
                types=card.types)
        else:
            return ShowResult(
                name=card.name,
                supertype=card.supertype,
                subtype=card.subtype,
                legality=PokemonTCGIOV1Provider._newest_legal_format(card),
                set_name=card_set.name,
                set_no=card.number,
                set_max=card_set.total_cards,
                image=card.image_url,
                set_icon=card_set.symbol_url,
                fields=[("\u200b", text) for text in card.text])
def show(name, card_set):
	# If the card set includes a specific number, we can just use that to
	# get the card
	card = None
	if "-" in card_set:
		card = Card.find(card_set)
		if card == None:
			return "No results for card `%s`" % card_set
	else:
		# Search for the given card
		cards = Card.where(name = name).where(setCode=card_set).all()

		if len(cards) == 0:
			return ("No results found for '%s' in set `%s`" %
				(name, card_set))

		if len(cards) > 1:
			return (
"""
Too many results. Try specifying the card number too. For example
`!show %s %s-%s`
""" % (name, card_set, cards[0].number)
			)

		card = cards[0]

	# Create a string for the card text
	return_str = "%s\n" % card.image_url
	return_str += "```\n"

	# Pokemon are the most involved as they have a lot going on
	if card.supertype == "Pokémon":
		# Start with the Pokemon's name and type(s)
		return_str += "%s - %s" % (card.name, "/".join(card.types))

		# Some Pokemon have no HP (e.g. the second half of LEGEND cards),
		# so do only add it if it exists
		if card.hp != None:
			return_str += " - HP%s\n" % (card.hp)
		else:
			return_str += "\n"

		return_str += "%s Pokemon\n\n" % card.subtype

		# Add the ability if present
		if card.ability != None:
			return_str += "%s: %s\n" % (card.ability['type'], card.ability['name'])
			return_str += "%s\n" % card.ability['text']
			return_str += "\n"

		# Add any attacks, including shorthand cost, text and damage
		if card.attacks != None:
			for attack in card.attacks:
				for cost in attack['cost']:
					return_str += "%s" % short_energy[cost]
				return_str += " %s" % attack['name']
				if attack['damage'] != '':
					return_str += ": %s damage\n" % attack['damage']
				else:
					return_str += "\n"
				if attack['text'] != None:
					return_str += "%s\n" % attack['text']
				return_str += "\n"

		# Add weakness, resistances and retreat if they exist
		if card.weaknesses != None:
			for weakness in card.weaknesses:
				return_str += ("Weakness: %s (%s)\n" %
					(weakness['type'], weakness['value']))
		if card.resistances != None:
			for resistance in card.resistances:
				return_str += ("Resistance: %s (%s)\n" %
					(resistance['type'], resistance['value']))
		if card.retreat_cost != None:
			return_str += "Retreat: %s" % len(card.retreat_cost)

	# Trainers and Energy are a lot easier
	elif card.supertype == "Trainer" or card.supertype == "Energy":
		return_str += "%s\n" % card.name
		return_str += "%s\n\n" % card.subtype
		return_str += "%s\n" % "\n\n".join(card.text)

	# Finally, get the set and legality info
	card_set = Set.find(card.set_code)
	return_str += "\n\n%s - %s/%s" % (card_set.name, card.number, card_set.total_cards)
	if card_set.standard_legal == True:
		return_str += " (Standard)"
	elif card_set.expanded_legal == True:
		return_str += " (Expanded)"
	else:
		return_str += " (Legacy)"

	return_str += "```\n"
	return return_str
예제 #32
0
for s in Set.all():
    nset = et.SubElement(xmlsets, "set")

    name = et.SubElement(nset, "name")
    longname = et.SubElement(nset, "longname")
    setType = et.SubElement(nset, "setType")
    releasedate = et.SubElement(nset, "releasedate")

    name.text = s.code
    longname.text = s.name
    setType.text = s.series
    releasedate.text = s.release_date

names = []
n = 0
for c in Card.all():
    n += 1
    ncard = et.SubElement(xmlcards, "card")

    name = et.SubElement(ncard, "name")
    cset = et.SubElement(ncard, "set")
    color = et.SubElement(ncard, "color")
    mana = et.SubElement(ncard, "manacost")
    cmc = et.SubElement(ncard, "cmc")
    ctype = et.SubElement(ncard, "type")
    pt = et.SubElement(ncard, "pt")
    tablerow = et.SubElement(ncard, "tablerow")
    text = et.SubElement(ncard, "text")
    font = et.SubElement(ncard, "font")

    name.text = c.name + " " + c.id
예제 #33
0
 def test_all_with_page_and_page_size_returns_card(self):
     with vcr.use_cassette('fixtures/all_first_page_one_card.yaml'):
         cards = Card.where(page=1, pageSize=1)
         self.assertEqual(1, len(cards))
예제 #34
0
def getAllCards():
    ## Card.where(page=5, pageSize=100)
    card = Card.find('xy1-1')
    name = card.name
    print(name)
    return ('', 200)