Пример #1
0
def main():
    initialize()

    deck = Deck.from_deckstring("AAECAR8engGoArUDxwOHBMkErgbFCNsJ7Qn+DJjwAp7wAu/xAqCAA6eCA5uFA/WJA+aWA/mWA76YA7acA56dA/yjA+WkA5+lA6KlA6alA4SnA5+3AwAA")

    for x in deck.cards:
        print("{0}x {1}".format(x[1], get_card(x[0])))
Пример #2
0
def main():
    '''
    Module that combines data acquired on decks and cards and produces full decklists to text file.
    '''
    decks = pd.read_csv(os.path.join(os.getcwd(), cfg.DECKLIST_CSV))
    cards = pd.read_csv(os.path.join(os.getcwd(), cfg.CARDS_CSV))
    deck_dump = open(cfg.DECK_OUTPUT, 'w')

    i = 1
    print('Writing decklists to a .txt file:')
    for index, row in decks.iterrows():
        deck_code = row['CODE']
        deck = Deck.from_deckstring(deck_code)
        utility.printProgressBar(i,
                                 len(decks.index),
                                 prefix='Progress:',
                                 suffix='Complete',
                                 length=50)
        i += 1

        deck_dump.write('Deck list for ' + row['CLASS'] + ' deck titled "' +
                        row['NAME'] + '" from Season ' + str(row['SEASON']) +
                        ':\n')
        for card in deck.cards:
            card_row = cards['NAME'].loc[cards['DATABASE_ID'] == card[0]]
            deck_dump.write('      ' + card_row.tolist()[0] + ' x' +
                            str(card[1]) + '\n')
        deck_dump.write(
            '--------------------------------------------------------------------------------------------------\n'
        )
        deck_dump.write(
            '--------------------------------------------------------------------------------------------------\n'
        )
Пример #3
0
def calculateLacksFromJSONFile(path, collection, db_dbf):
    newlist = []
    with open(path, "rt") as f:
        for line in f.readlines():
            data = json.loads(line)['result']
            deck = Deck.from_deckstring(data['deckstring'])
            if len(deck.cards) <= 0:
                # If there exists some connection problem,
                # we may get an empty deck here.
                # If so, just ignore it.
                continue
            print(data)
            print(deck.cards)
            newdict = {}
            newdict["name"] = data['title'].split(b'-')[0]
            newdict["url"] = data['url']
            newdict["date"] = data['date']
            newdict["type"] = data['type']
            newdict["deck"] = deck
            newdict["lacked"], newdict[
                "alreadyHave"] = collection.calculateLacks(deck.cards)
            #            print (newdict["lacked"])
            _, newdict["dust"] = calcArcaneDust(newdict["lacked"], db_dbf)
            newdict["power"] = 1
            newlist.append(newdict)
    return newlist
Пример #4
0
    def format_deckstring(self, deckstring):
        deck = None
        try:
            deck = Deck.from_deckstring(deckstring)
        except Exception as e:
            return str(e)

        hero = ",".join(
            [self.find_card_name(card_id) for card_id in deck.heroes])

        output = "```"
        output += f"\n###"
        output += f"\n# Hero: {hero}"
        output += f"\n# Format: {list(FormatType)[(deck.format)].name}"
        output += f"\n#"
        for card in deck.cards:
            count = card[1]
            card_id = card[0]
            if card_id in self.db:
                card = self.db[card_id]
                output += f"\n# {count}x ({card.cost}) {card.name}"
            else:
                output += f"\n# {count}x UNKNONWN"
        output += f"\n#"
        output += f"\n{deck.as_deckstring}"
        output += f"\n#"
        output += f"\n# To use this deck, copy it to your clipboard and create a new deck in Hearthstone"
        output += "```"

        return output
Пример #5
0
    def simulate_mulligan(self, deckcode):
        #determine order & draw initial cards
        self.deckcode = str(deckcode)
        self.order = isFirst()
        self.deck = Deck.from_deckstring(self.deckcode)
        self.decklist = fulldecklist(self.deckcode)
        self.originaldecklist = self.decklist
        random.shuffle(self.decklist)

        self.opponent = opponent_selection()
        print("Your opponent is: " + self.opponent)

        self.hand = initial_draw(self.decklist, self.order)

        self.display_cards(self.hand)
        self.display_cards_ID(self.hand)

        #We do not need to assert that the input is correct for this since
        #once we create the Interface, this selection will be based on clicks
        self.hand = self.replace_cards()

        #Display final hand
        self.display_cards(self.hand)

        #End simulation or go to next match
        #Before we reset the simulation we must write each instance into the database
        self.reset()
Пример #6
0
    def load_deckstring(self, deckstring):
        cards = []

        try:
            deck = Deck.from_deckstring(deckstring)
        except binascii.Error:
            print('Deck string is invalid base64 string: {}'.format(deckstring))
            return None

        total_cost = 0
        for (dbfId, count) in deck.cards:
            count = int(count)
            found = False
            for card in self.mycollection:
                if card['dbfId'] == dbfId:
                    found = True
                    if card['count'] >= count:
                        cards.append((card, count, 0))
                    else:
                        missing = count - card['count']
                        cards.append((card, card['count'], missing))

            card = None
            if not found:
                card = self.collectible_by_Id(dbfId)
                if not card:
                    card = { 'name': 'INVALID DBFID ({})'.format(dbfId) }
                    count = 0
                cards.append((card, 0, count))

        return cards
Пример #7
0
def deck_code_decode(deck_code):
    # Deckstring decode. See:
    # https://hearthsim.info/docs/deckstrings/
    deck = Deck.from_deckstring(deck_code)
    deck_hero = deck.heroes[0]
    deck_card = deck.cards

    return [deck_hero, deck_card]
Пример #8
0
def parse_deck(text):
    for i in range(3):
        try:
            deck = Deck.from_deckstring(text + '=' * i)
            return deck
        except Exception as e:
            continue
    return None
Пример #9
0
    def initFromDeckStringFile(self, path):
        """Init the database from a deckstring file
        The file should contain a set of deckstrings, every string in a line

        Args:
          path: The deckstring file's path
        """
        with open (path, "rt") as f:
            for line in f.readlines():
                deck = Deck.from_deckstring(line)
                for cardPair in deck.cards:
                    self.add(cardPair)
Пример #10
0
def fulldecklist(deckcode):
    """
    This function takes in the deckcode, and deciphers the deckcode into the complete list of cards
    where the tuples (x,y) are separated into a list [x] y times.
    """
    ##First imports the deckcode as a deck
    ##Example Mage Deck we will be using ("AAECAf0ECO0Fcem6AoivAuwHobcCxQS/CAuBsgKVA8HBApYF17YCmMQCqwTAAbC8ArsCo7YCAA==")

    deck = Deck.from_deckstring(str(deckcode))
    complete_deck = []
    for card, copy in deck.cards:
        l = [card] * copy
        complete_deck.extend(l)
    return complete_deck
Пример #11
0
def get_decklist(deckstring):
    try:
        deck = Deck.from_deckstring(deckstring)
    except:
        return None

    decklist = []
    with open(f'{BASE_DIR}/static/cards.collectible.json', 'rb') as f:
        data = json.load(f)
        for i in range(len(deck.cards)):
            card = [{'id': 'NOT_EXISTS', 'cost': 404}, deck.cards[i][1]]
            for j in range(len(data)):
                if deck.cards[i][0] == data[j]['dbfId']:
                    card = [data[j], deck.cards[i][1]]
            decklist.append(card)

    decklist = sorted(decklist, key=lambda cost: cost[0]['cost'])
    return decklist, deck.format.name.split('_')[1]
Пример #12
0
def find_and_decode_deckstrings(text):
    b64_text = remove_non_b64(text)
    decks = []
    for chunk in b64_text.split():
        if any(word in chunk for word in ["###", "#\\#\\#"]):
            return []
        if not chunk.startswith(("AAEBA", "AAECA", "AAEDA")):
            continue
        if chunk in [deck._deckstring for deck in decks]:
            continue
        try:
            deck = Deck.from_deckstring(chunk)
        except Exception:
            continue

        deck._deckstring = chunk
        decks.append(deck)

    return decks
Пример #13
0
def calculateLacksFromFile(path, collection, db_dbf):
    """Calculate the lacked cards from decks stored in file PATH.
    The file should contain a set of deckstrings, every string in a line.
    This may will be removed in the future,
    since the function calculateLacksFromJSONFile() is more practical.

    Args:
      path: The file that contains the deckstrings
      collection: Cards collection for calculation
      db_dbf: The all-cards database
    Returns:
      newlist: A list of dict, each of which contains the results for a deck
    """
    newlist = []
    with open (path, "rt") as f:
        for line in f.readlines():
            cardsInDeck = 0
            deck = Deck.from_deckstring(line)
            for cardPair in deck.cards:
                cardsInDeck += cardPair[1]
            if cardsInDeck < 30:
                # Ignore the decks containing less than 30 cards
                continue
            newdict = {}
            newdict["name"] = "Deck name"
            newdict["url"] = "Unknown"
            newdict["date"] = "Unknown"
            newdict["type"] = "Unknown"
            newdict["rating-sum"] = "Unknown"
            newdict["deck-type"] = "Unknown"
            newdict["rarchetype"] = "Unknown"
            newdict["deck"] = deck
            newdict["deckstring"] = line
            newdict["lacked"], newdict["alreadyHave"] = collection.calculateLacks(deck.cards)
            _, newdict["dust"] = calcArcaneDust(newdict["lacked"], db_dbf)
            newdict["power"] = 1
            newlist.append(newdict)
    return newlist
Пример #14
0
def generate_images(deck_dict, dest, ordered=False):
    for name in deck_dict:
        deck_imgs = []
        for deckcode in deck_dict[name]:
            deck = Deck.from_deckstring(deckcode)
            if deck != None:
                img = deck_to_image(deck, name)
                deck_imgs.append(img)
        if len(deck_imgs) == 0:
            print('Player {} has no decks'.format(name))
            continue
        img = merge(deck_imgs)
        img = img.convert('RGB')
        name = name.replace('/', '\\')
        if ordered:
            if (ord(name[0].upper()) >= ord('A')
                    and ord(name[0].upper()) <= ord('Z')):
                img.save(u'{}/{}/{}.jpg'.format(dest, name[0].upper(), name),
                         'JPEG')
            else:
                img.save(u'{}/{}/{}.jpg'.format(dest, 'etc', name), 'JPEG')
        else:
            img.save(u'{}/{}.jpg'.format(dest, name), 'JPEG')
Пример #15
0
# for archetype in archetypes:
    # print(archetypes[archetype][0])
    
r = csv.reader(open(deckListFile, newline=''), delimiter='\t', quotechar='|') #opens tespa match csv
tespaDecks = {}
fixValue = 0 #lets me skip the header

print('Scraping Tespa Decks.')
for row in r: #primary deck scraping loop
    try:
        if fixValue == 0:
            fixValue = fixValue + 1
        else:
            #print(row[2])
            #print(row[1])
            deckOneObj = Deck.from_deckstring(row[2]+'==') #creates deck objects - note that I could probably consolidate this into another for loop for all four decks but I'm fine with it as is.
            deckOneCards = []
            for card in deckOneObj.cards: #iterates through cards in the deck object
                for n in range(0,card[1]): #counts how many copies of the cards are in the deck)
                    for cardDbfId in cardDbfIds: #iterates through cardIDs from the card list
                        if card[0] == cardDbfId: #checks if the card's ID is equivalent to a given card in the card list.
                            deckOneCards = deckOneCards + [cardName[cardDbfIds.index(cardDbfId)]] #if the card is found in the card list, its name is stored in the deck
            deckOneHero = className[classIDs.index(deckOneObj.heroes[0])] #gets the name of the hero for the deck
            deckOneArchetype = ''
            for archetype in archetypes: #iterates through the archetypes to try and find if the deck matches a given archetype
                if set(archetypes[archetype]).issubset(deckOneCards):
                    deckOneArchetype = archetype
                    break
            if deckOneArchetype == '': #if it doesnt fit, stores deck archetype as unknown
                deckOneArchetype = 'Unknown ' + deckOneHero
            #print(deckOneArchetype)
import sys

from prettytable import PrettyTable

from hearthstone.deckstrings import Deck
from hearthstone.cardxml import load_dbf
from hearthstone.enums import get_localized_name

for i, hs_deck in enumerate(sys.argv):
    unknown = 0
    if not i == 0:
        locale = 'enUS'
        deck = Deck.from_deckstring(hs_deck)
        db, _ = load_dbf(locale=locale)
        english_db = db

        card_includes = deck.cards
        cards = []
        for dbf_id, count in card_includes:
            try:
                cards.append((db[dbf_id], count))
            except KeyError:
                unknown += 1
        cards.sort(key=lambda include: (include[0].cost, include[0].name))
        try:
            hero = db[deck.heroes[0]]
            class_name = get_localized_name(hero.card_class, locale=locale)
            hero_name = f"{class_name} ({hero.name})"
        except KeyError:
            hero_name = "Unknown"
Пример #17
0
def calculateLacksFromJSONFile(path, collection, db_dbf, dateLimit="07/01/2017", ratingLimit=20, filteredJSONFile=None):
    """Calculate the lacked cards from a json file

    Args:
      path: The path of the input json file (which contains decks produced by pyspider)
      collection: My card collection
      db_dbf: The database of all cards
      dateLimit: A date string, we only consider the decks newer than that
      ratingLimit: An int, ignore the decks who's 'rating-sum' is smaller than it
      filteredJSONFile: If it isn't None, store the filted JSON into it.
    Returns:
      newlist: a list of dict, each of which is the result for a deck
    """
    newlist = []
    deckstringSet = set()
    date = dt.strptime(dateLimit, "%m/%d/%Y")
    with open (path, "rt") as f:
        if filteredJSONFile != None:
            JSONOut = open(filteredJSONFile, "wt")
        for line in f.readlines():
            cardsInDeck = 0
            linedict = json.loads(line)
            if linedict.get('result') != None: # A json file produced by pyspider directly
                data = linedict['result']
            else:
                data = linedict
            deckCreatedDate = dt.strptime(data['date'].split(' ')[1], "%m/%d/%Y")
            if date > deckCreatedDate: # Ignore old decks
                continue
            if data['deckstring'] in deckstringSet: # The deckstring has already processed
                continue
            deckstringSet.add(data['deckstring'])
            deckRating = int(data['rating-sum'])
            if ratingLimit > deckRating: # Ignore decks with small rank points
                continue
            try:
                deck = Deck.from_deckstring(data['deckstring'])
            except:
                print("exception catched, dechstring:", data['deckstring'])
            for cardPair in deck.cards:
                cardsInDeck += cardPair[1]
            if cardsInDeck < 30:
                # Ignore the decks containing less than 30 cards
                continue
            newdict = {}
            newdict["name"] = data['title'].split('-')[0]
            newdict["url"] = data['url']
            newdict["date"] = data['date'].split(' ')[1]
            newdict["type"] = data['type']
            newdict["rating-sum"] = int(data['rating-sum'])
            newdict["deck-type"] = data['deck-type'].split(':')[1]
            newdict["archetype"] = data['archetype'].split(':')[1]
            newdict["deck"] = deck
            newdict["deckstring"] = data['deckstring']
            newdict["cardclass"] = calcCardClass(deck.cards, db_dbf)
            newdict["lacked"], newdict["alreadyHave"] = collection.calculateLacks(deck.cards)
            _, newdict["dust"] = calcArcaneDust(newdict["lacked"], db_dbf)
            newdict["power"] = 1
            newlist.append(newdict)
            if filteredJSONFile != None:
                json.dump(data, JSONOut)
                JSONOut.write('\n')

        if filteredJSONFile != None:
            JSONOut.close()

    return newlist
Пример #18
0
def main(code, lang):
    start_time = datetime.datetime.now()

    deck = Deck.from_deckstring(code)
    new = []
    with open(test_json, 'rb') as f:
        data = json.load(f)  #list of dicts
        for i in range(len(deck.cards)):
            ext = data[str(deck.cards[i][0])]
            start = [deck.cards[i][0], deck.cards[i][1]]
            start.extend(ext)
            new.append(start)
    # print(new)

    new_sorted = sorted(new, key=lambda student: student[2])
    # print(new_sorted) #[[138, 2, 2, 'NEUTRAL', 'NEW1_021'], [47982, 1, 3, 'MAGE', 'BOT_103'],...] #id, quntity, cost, class, id

    lang = lang
    asyncio.run(main2(new_sorted, lang))
    # print(images_deck[0][0])
    print(images_deck.keys())

    l = len(deck.cards)
    image_y = math.ceil(l / 7)

    card_width = 256
    card_height = 387
    card_down = 340
    position_x = card_width
    position_y = card_height

    img = Image.new('RGB', (card_width * 7, card_height * image_y))

    x2 = Image.open(x2png)  #x2-42.png 56,44
    for i in range(l):
        # print(deck.cards[i][0])
        if i <= 6:
            position = (position_x * i, position_y * 0)
        elif i <= 13:
            position = (position_x * (i - 7), position_y)
        elif i <= 20:
            position = (position_x * (i - 7 * 2), position_y * 2)
        elif i <= 27:
            position = (position_x * (i - 7 * 3), position_y * 3)
        else:
            position = (position_x * (i - 7 * 4), position_y * 4)

        # print(position)
        # img.paste(get_image(deck.cards[i][0]), (position))
        # img.paste(images_deck, (position))

        img_part = Image.open(BytesIO(images_deck[i]))
        img.paste(img_part, (position))
        # img.paste(img_part, (320*i, 0))

        print(new_sorted[i])
        if new_sorted[i][1] == 2:
            img.paste(x2, (position[0] + int(card_width / 2 - 28),
                           position[1] + card_down))

    today = datetime.datetime.today()
    file_name = "{}.jpg".format(today.strftime("%Y-%m-%d-%H.%M.%S"))

    # draw some text
    class_ = ''
    for i in range(l):
        if new_sorted[i][3] != 'NEUTRAL':
            class_ = new_sorted[i][3]
            break
        print(new_sorted[i][3])
    draw = ImageDraw.Draw(img)
    font = ImageFont.truetype(mildrttf, 24)
    draw.text((23, 7), class_, (100, 100, 100), font=font)

    file_name_for_save = os.path.join(
        BASE_DIR2,
        "hsdic" + os.sep + "static" + os.sep + "hsdic" + os.sep + file_name)
    img.save(file_name_for_save)

    finish_time = datetime.datetime.now()
    print(finish_time - start_time)
    return file_name
Пример #19
0
    async def deck(self, ctx, target: str):
        deck = Deck.from_deckstring(target)

        image = ""
        hero = deck.heroes[0]
        if str(hero) == "274" or str(hero) == "50484":
            hero = "Druid"
            image ="https://d1u5p3l4wpay3k.cloudfront.net/hearthstone_gamepedia/8/8d/Icon_Druid_64.png?version=b6a84e24ff9417d99c04f883b5687ed3"
        if str(hero) == "637" or str(hero) == "2829" or str(hero) == "39117":
            hero = "Mage"
            image ="https://d1u5p3l4wpay3k.cloudfront.net/hearthstone_gamepedia/f/f2/Icon_Mage_64.png?version=f16b540384ed113585c2f6b117aeb7d0"
        if str(hero) == "31" or str(hero) == "2826":
            hero = "Hunter"
            image ="https://d1u5p3l4wpay3k.cloudfront.net/hearthstone_gamepedia/f/f4/Icon_Hunter_64.png?version=b9ee98cd8936a875ba84bc9d3f83bebc"
        if str(hero) == "7" or str(hero) == "2828":
            hero = "Warrior"
            image = "https://d1u5p3l4wpay3k.cloudfront.net/hearthstone_gamepedia/1/19/Icon_Warrior_64.png?version=d0252ccedf6faab67e5ab506dddda2ea"
        if str(hero) == "893" or str(hero) == "47817" or str(hero) == "51834":
            hero = "Warlock"
            image = "https://d1u5p3l4wpay3k.cloudfront.net/hearthstone_gamepedia/2/2e/Icon_Warlock_64.png?version=5f7037f5cb0b4be064ceb9f6c4528e73"
        if str(hero) == "1066" or str(hero) == "40183":
            hero = "Shaman"
            image = "https://d1u5p3l4wpay3k.cloudfront.net/hearthstone_gamepedia/a/a8/Icon_Shaman_64.png?version=08bc485fb8261048c7a3a480953c7169"
        if str(hero) == "930":
            hero = "Rogue" or str(hero) == "40195"
            image = "https://d1u5p3l4wpay3k.cloudfront.net/hearthstone_gamepedia/7/76/Icon_Rogue_64.png?version=04949ddceba669263317bf44edb981c1"
        if str(hero) == "813"  or str(hero) == "41887":
            hero = "Priest"
            image = "https://d1u5p3l4wpay3k.cloudfront.net/hearthstone_gamepedia/2/23/Icon_Priest_64.png?version=a5d7b4e15c40dfd667e6868165b10677"
        if str(hero) == "671" or str(hero) == "2827" or str(hero) == "46116":
            hero = "Paladin"
            image = "https://d1u5p3l4wpay3k.cloudfront.net/hearthstone_gamepedia/7/7b/Icon_Paladin_64.png?version=2a4e7cdbb3b5402f3e8a34ea156f9cf1"

        embed = discord.Embed()
        num_of_spells = 0
        num_of_minions = 0

        deckids = []
        fulldeck = []
        total_cost = 0
        for card in deck.cards:
            num_of_cards = card[1]
            card = card[0]
            search = "https://api.hearthstonejson.com/v1/26996/enUS/cards.collectible.json"
            async with aiohttp.ClientSession() as session:
                async with session.get(search) as r:
                    result = await r.json(content_type='application/json')

                    x = 0
                    while x < len(result):
                        z = result[x]["dbfId"]
                        if z == card:
                            # todo: add expansion, hsreplay link/data, etc.

                            for _ in range(num_of_cards):
                                deckids.append(str(result[x]["id"]))

                            types_of_rarity = ["🏛️", "💿", "💙", "💜", "💛"]  # free, common, rare, epic, legendary

                            name = result[x]["name"]
                            cost = result[x]["cost"]
                            rarity = result[x]["rarity"]

                            if result[x]["type"] == "SPELL":
                                num_of_spells += (1 * num_of_cards)

                            if result[x]["type"] == "MINION":
                                num_of_minions += (1 * num_of_cards)

                            if rarity == "LEGENDARY":
                                total_cost += 1600 * int(num_of_cards)
                                rarity = types_of_rarity[4]
                            if rarity == "EPIC":
                                total_cost += 400 * int(num_of_cards)
                                rarity = types_of_rarity[3]
                            if rarity == "RARE":
                                total_cost += 100 * int(num_of_cards)
                                rarity = types_of_rarity[2]
                            if rarity == "COMMON":
                                total_cost += 40 * int(num_of_cards)
                                rarity = types_of_rarity[1]
                            if rarity == "FREE":
                                rarity = types_of_rarity[0]

                            y = [str(num_of_cards), " x ", str(rarity) + " | ", str(name), "| " + str(cost) + " mana |", int(cost)]
                            fulldeck.append(y)
                            x = len(result)
                        else:
                            x += 1

        def getcost(elem):
            return elem[-1]

        fulldeck.sort(key=getcost, reverse=True)

        ALPHABET = string.ascii_letters + string.digits

        # The following is yoinked from here:
        # https://github.com/HearthSim/HSReplay.net/blob/54a5e372e6ddd870fa102c7e827c359c28b81187/scripts/generating_deck_ids_example.py
        def int_to_string(number, alphabet, padding=None):
            """
            Convert a number to a string, using the given alphabet.
            """
            output = ""
            alpha_len = len(alphabet)
            while number:
                number, digit = divmod(number, alpha_len)
                output += alphabet[digit]
            if padding:
                remainder = max(padding - len(output), 0)
                output = output + alphabet[0] * remainder
            return output

        def generate_digest_from_deck_list(id_list):
            sorted_cards = sorted(id_list)
            m = hashlib.md5()
            m.update(",".join(sorted_cards).encode("utf-8"))
            return m.hexdigest()

        card_ids = deckids
        digest = generate_digest_from_deck_list(card_ids)
        shortid = int_to_string(int(digest, 16), ALPHABET)

        embed = discord.Embed(title="{}'s Deck 🃏".format(ctx.author.name),
                              description="• Deckcode being used:\n`{}`"
                                          "\n[• View deck stats on HSReplay](https://hsreplay.net/decks/{}/)"
                              .format(deck.as_deckstring, shortid),
                              color=settings.embed_color)
        embed.add_field(name="Format:", value=str(str(deck.format)[14:]).title(), inline=True)
        embed.add_field(name="Cost:", value=str(total_cost), inline=True)
        if "0." in str(num_of_spells / num_of_minions):
            embed.add_field(name="Spells:Minions Ration:",
                            value="{} : 1".format(str(num_of_minions / num_of_spells)[:5]), inline=True)
        else:
            embed.add_field(name="Minions:Spell Ration:",
                            value="{} : 1".format(str(num_of_spells / num_of_minions)[:5]), inline=True)
        embed.set_thumbnail(url=image)
        embed.add_field(name="# of Spells:", value=str(num_of_spells), inline=True)
        embed.add_field(name="# of Minions:", value=str(num_of_minions), inline=True)
        embed.add_field(name="Cards:", value='\n'.join(' '.join(elems[:-1]) for elems in fulldeck), inline=True)
        await asyncio.sleep(1)
        await ctx.send(embed=embed)

        search = "https://hsreplay.net/decks/{}/#tab=overview".format(shortid)
        async with aiohttp.ClientSession() as session:
            async with session.get(search) as r:
                print(search)
                text = await r.read()

                await asyncio.sleep(1)
                soup = BeautifulSoup(text.decode('utf-8'), 'html5lib')

                print(soup)

                data = soup.find('span', attrs={'class': 'infobox-value'})
                print(data)
Пример #20
0
from hearthstone.deckstrings import Deck
from hearthstone.enums import FormatType

# Create a deck from a deckstring
deck = Deck()
deck.heroes = [7]  # Garrosh Hellscream
deck.format = FormatType.FT_WILD
# Nonsense cards, but the deckstring doesn't validate.
deck.cards = [(1, 3), (2, 3), (3, 3), (4, 3)]  # id, count pairs
print(deck.as_deckstring)  # "AAEBAQcAAAQBAwIDAwMEAw=="

# Import a deck from a deckstring
deck = Deck.from_deckstring("AAEBAQcAAAQBAwIDAwMEAw==")
assert deck.heroes == [7]
assert deck.format == FormatType.FT_WILD
assert deck.cards == [(1, 3), (2, 3), (3, 3), (4, 3)]
Пример #21
0
    return next((card for card in db if card["dbfId"] == dbf_id), None)
def sort_cards():
    cards = []
    for s in deck.cards:
        card = get_card(s[0])
        card["ammount"] = int(s[1])
        cards.append(card)
    return sorted(cards, key=lambda card:(card["cost"], card["cardClass"], card["name"]))
parser = argparse.ArgumentParser(description="Print hearthstone decklist to terminal from deckid")
parser.add_argument('<deckid>', type=str, help='Hearthstone deckID to be converted')
args = parser.parse_args()

db_url = "https://api.hearthstonejson.com/v1/latest/enUS/cards.collectible.json"
db_path = "./db.json"
deckstring = decode_base64(sys.argv[1])
deck = Deck.from_deckstring(deckstring)
lb = "="*30
if os.path.exists(db_path):
    with open(db_path, "r") as f:
        db = json.loads(f.read())
else:
    response = requests.get(db_url)
    if response.status_code == 200:
        with open(db_path, "wb") as f:
            f.write(response.text.encode("utf-8"))
            db = response.json()
    else:
        raise RuntimeError("Couldn't download cards database: %s"
                           % response.text)
print (get_card(deck.heroes[0])["cardClass"])
print (get_format())
Пример #22
0
from hearthstone.deckstrings import Deck
from hearthstone.enums import FormatType
from hearthstone.cardxml import load
from hearthstone.enums import Locale, Rarity
from collection import Collection

# Create a deck from a deckstring
deck = Deck()
deck.heroes = [7]  # Garrosh Hellscream
deck.format = FormatType.FT_WILD
# Nonsense cards, but the deckstring doesn't validate.
deck.cards = [(1, 3), (2, 3), (3, 3), (4, 3)]  # id, count pairs
print(deck.as_deckstring)  # "AAEBAQcAAAQBAwIDAwMEAw=="

# Import a deck from a deckstring
deck = Deck.from_deckstring(
    "AAEBAf0ECMAB5gT7BPsFigbYE5KsAv2uAgucArsClQONBKsEtAThBJYF7Ae8CImsAgA=")
print(deck.cards)

# load card database from CardDefs.xml and use it to initialize DBF database
db, xml = load(os.path.join("hsdata", "CardDefs.xml"), locale="zhCN")

db_dbf = {}
for card in db:
    #print (card)
    db_dbf[db[card].dbf_id] = db[card]

#print (db)
for cardPair in deck.cards:
    #    print (cardPair[0])
    card = db_dbf[cardPair[0]]
    print(cardPair[1], "x(", card.cost, ")", card.name, card.rarity)
Пример #23
0
def decode(code, name):
    deck = Deck.from_deckstring(code)
    return write_deck(deck, name)
Пример #24
0
def load_deck(deckstring, cards):
    return frozenset(
        map(
            lambda x: (cards[x[0]], x[1]),
            Deck.from_deckstring(deckstring).cards,
        ))