remove all useless .pyc files
[mlpccg-meta.git] / mlpccg / DeckList.py
1 import logging
2 import operator
3 import xml.etree.ElementTree as ET
4 from collections import defaultdict
5
6 import mlpccg.CardDb
7
8 class DeckList:
9 def __init__(self, name=None, xml=None, url=None, txt=None):
10 self.cards = []
11 self.name = name
12
13 if xml:
14 self.parse_ponyhead_xml(xml)
15 elif url:
16 self.parse_ponyhead_link(url)
17
18 def __repr__(self):
19 return self.name
20
21 @property
22 def aspects(self):
23 mane = None
24 aspects = defaultdict(int)
25 for card in self.cards:
26 if card['type'] == 'Mane':
27 mane = (card['title'], mlpccg.CardDb.CardDb.set_ids[card['set']].upper())
28
29 elif card['type'] == 'Friend':
30 aspects[card['color']] += 1
31
32 elif card['type'] != 'Problem':
33 aspects[card['type']] += 1
34
35 aspects_sorted = sorted(aspects.iteritems(), reverse=True, key=operator.itemgetter(1))
36 aspects_sum = float(sum([aspect[1] for aspect in aspects_sorted]))
37 aspects_filtered = []
38 cutoff = 0.6
39 amount = 0.0
40 for aspect, value in aspects_sorted:
41 amount += value / aspects_sum
42 aspects_filtered += [aspect]
43 if amount >= cutoff:
44 break
45
46 return (mane, aspects_filtered)
47
48 @property
49 def description(self):
50 mane, aspects = self.aspects
51 if not mane or len(aspects) == 0:
52 return 'Unknown'
53
54 return '%s %s %s' % (mane[0], mane[1], '/'.join(aspects))
55
56 @property
57 def ponyhead_link(self):
58 cards = defaultdict(int)
59 for card in self.cards:
60 cards[card['id'].replace('pf', 'PF').replace('f', 'F')] += 1
61
62 cards = ['%sx%d' % (id, amount) for id, amount in cards.iteritems()]
63
64 return 'http://ponyhead.com/deckbuilder?v1code=%s' % '-'.join(cards)
65
66 def parse_ponyhead_xml(self, path):
67 logging.debug('loading decklist from xml')
68
69 try:
70 root = ET.parse(path).getroot()
71 card_names = [element.text.strip() for element in root.findall('.//card/name')]
72 for card_name in card_names:
73 self.cards += [mlpccg.CardDb.CARDDB.by_name(card_name)['id']]
74 except:
75 logging.exception('failed')
76
77 def parse_ponyhead_link(self, link):
78 logging.debug('loading decklist by parsing url')
79
80 try:
81 id_list = [id.split('x') for id in link.split('=')[-1].split('-')]
82 for id, amount in id_list:
83 self.cards += [mlpccg.CardDb.CARDDB.by_id(id)] * int(amount)
84 except:
85 logging.exception('failed: %s', link)
86
87 def parse_ponyhead_txt(self):
88 pass