Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- import os
- HOME = os.path.expanduser(os.path.join("~", "Documents", "Decks"))
- if HOME[-1] != '/':
- HOME += '/'
- try:
- from Tkinter import Tk
- except ImportError:
- from tkinter import Tk
- cmd_input = input
- else:
- cmd_input = raw_input
- from fnmatch import fnmatch
- cpd = Tk()
- cpd.withdraw()
- class Decklist:
- def __init__(self):
- self.cards = list()
- self.cat = str()
- self.cats = dict()
- self.catList = list()
- self.prompt = '> '
- self.title = 'No Title'
- def add(self, numberOfCards, cardName, cat):
- cards = self.cats[cat]
- cards.append((int(numberOfCards), cardName))
- self.cats[cat] = cards
- def remove(self, index, cat):
- cards = self.cats[cat]
- if index.isdigit():
- del cards[int(index)]
- self.cats[cat] = cards
- return
- else:
- raise ValueError('An index must be passed')
- def addcat(self, cat):
- if cat in self.catList:
- raise ValueError('%s already exists.' % cat)
- self.cats[cat] = list()
- self.catList.append(cat)
- def removecat(self, cat):
- if not cat in self.cats.keys():
- raise KeyError('%s doesn\'t exist.' % cat)
- del self.cats[cat]
- self.catList.remove(cat)
- def clear(self):
- self.cards = []
- self.cat = ''
- self.cats = {}
- self.catList = []
- self.prompt = '> '
- self.title = 'No Title'
- def save(self, name):
- filepath = makeDirAndName(name)
- deckfile = open(filepath, 'w')
- data = '[Meta]\n'
- data += 'Title=%s\n' % self.title
- for cat in self.catList:
- data += '[%s]\n' % cat
- cards = self.cats[cat]
- if len(cards) == 0:
- continue
- for index in range(len(cards)):
- cardData = cards[index]
- data += 'n%s=%s\n' % (index, cardData[0])
- data += 'card%s=%s\n' % (index, cardData[1])
- deckfile.write(data)
- def load(self, name):
- filepath = makeDirAndName(name)
- deckfile = open(filepath, 'r')
- catList, data = iniparse(deckfile.read())
- deckfile.close()
- self.clear()
- if 'Title' in data['Meta'].keys():
- self.title = data['Meta']['Title']
- if 'Comment' in data['Meta'].keys():
- self.comment = data['Meta']['Comment']
- catList.remove('Meta')
- for cat in catList:
- self.addcat(cat)
- cardData = data[cat]
- index = 0
- while True:
- try:
- numberOfCards = cardData['n%s' % index]
- cardName = cardData['card%s' % index]
- except KeyError:
- break
- self.add(numberOfCards, cardName, cat)
- index += 1
- def getDeckList(self, options):
- deck = self.title + '\n'
- for cat in self.catList:
- if len(self.cats[cat]) == 0:
- continue
- deck += ' %s\n' % cat
- for card in self.cats[cat]:
- if options['autocard'] == True:
- deck += ' %sx [c]%s[/c]\n' % (card[0], card[1])
- elif options['link'] == True:
- deck += ' %sx <a target="Magic" href="http://gatherer.wizards.com/pages/card/details.aspx?name=%s">%s</a>\n' % (card[0], card[1].replace(' ', '%20'), card[1])
- else:
- deck += ' %sx %s\n' % (card[0], card[1])
- return deck[:-1]
- def getHtmlDeck(self, options):
- tempCatList = self.catList
- catList = list()
- cardnum = 0
- for cat in tempCatList:
- if len(self.cats[cat]) > 0:
- catList.append(cat)
- table = '<table border="1" cellspacing="0">\n<tbody>\n<tr>\n'
- table += '<th colspan="%s" style="text-align: center;"><big>%s' % (len(catList), self.title)
- table += '</big></th>\n'
- table += '</tr>\n'
- table += '<tr>\n'
- for cat in catList:
- table += '<th>%s</th>\n' % cat
- table += '</tr>\n'
- table += '<tr>\n'
- for cat in catList:
- table += '<td valign="top">\n'
- cardList = self.cats[cat]
- for index in range(len(cardList)):
- cardData = cardList[index]
- if options['autocard'] == True:
- table += '%sx [c]%s[/c]<br />\n' % (cardData[0], cardData[1])
- elif options['link'] == True:
- table += '%sx <a target="Magic" href="http://gatherer.wizards.com/pages/card/details.aspx?name=%s">%s</a><br />\n' % (cardData[0], cardData[1].replace(' ', '%20'), cardData[1])
- else:
- table += '%sx %s<br />\n' % (cardData[0], cardData[1])
- cardnum += int(cardData[0])
- table += '</td>\n'
- table += '</tr>\n<tr>\n'
- for cat in catList:
- total = 0
- for cardData in self.cats[cat]:
- total += int(cardData[0])
- table += '<td>%s cards</td>\n' % (total)
- table += '</tr>\n<tr>\n'
- table += '<th colspan="%s">' % len(catList)
- table += '%s Total' % cardnum
- table += '</th>\n</tr>\n</tbody>\n</table>'
- return table
- def getListOfDecks(self):
- dirs = list()
- decks = list()
- startdir = HOME
- dirs.append(startdir)
- while True:
- cwd = dirs.pop()
- shortdir = cwd[len(startdir)+1:]
- cwddirs = sorted(os.listdir(cwd))
- for direc in cwddirs:
- path = startdir + '/' + direc
- if os.path.isdir(path):
- dirs.append(path)
- continue
- if fnmatch(direc, '*.dck'):
- if len(shortdir) != 0:
- deck = shortdir+'/'+direc[:-4]
- decks.append(deck)
- else:
- decks.append(direc[:-4])
- continue
- if len(dirs) == 0:
- break
- return decks
- def cmd_clear(self, args):
- """Start a new blank decklist, clears away previous existing data.
- No syntax needed."""
- self.clear()
- print('Decklist has been cleared.')
- def cmd_name(self, args):
- """Syntax: name <deck name>
- Change the deck name to <deck name>"""
- if args == '':
- print('No deck name given.')
- print('name <deck name>')
- return
- self.title = args
- print('Deck name changed to "%s"' % args)
- def cmd_add(self, args):
- """Syntax: add <number> <card name>
- Adds <number> of <card name> to the current category.
- You need to select a category before you can use this command.
- cat <category>"""
- if self.cat == '':
- print('No category was specified.\nChoose a category then add cards to it.\ncat <category>')
- return
- if args == '':
- print('No card data was entered.\nadd <number> <card name>')
- return
- try:
- num, cardname = args.split(' ', 1)
- except ValueError:
- print('You need to specify the number of the card to add, then the cardname.\nadd <number> <card name>')
- try:
- num = int(num)
- except ValueError:
- print('Unable to understand your request. Please format the request correctly. <number> needs to be a number.\nadd <number> <card name>')
- return
- self.cats[self.cat].append((num, cardname))
- def cmd_del(self, args):
- """Syntax: del <index>
- Deletes a card from the currently selected category.
- <index> must be the index from the card list you want deleted."""
- if self.cat == '':
- print('No category set yet.\ncat <category>')
- return
- if args == '':
- print('No card was specified.\ndel <card>\n<card> can be the card index or the card name.')
- return
- try:
- self.remove(args, self.cat)
- except IndexError:
- print('The card index is higher than any existing index.')
- except ValueError:
- print('You need to give a number as the index.')
- print('del <index>')
- def cmd_replace(self, args):
- """Syntax: replace <index> <number> <card name>
- Replace the chosen card with another card.
- Example: replace 0 12 Swamp
- That replaces the first card entry with a new one with 12 Swamp cards."""
- if self.cat == '':
- print('No category selected yet.')
- print('cat <category>')
- if args == '':
- print('No information given with this command.')
- print('You need to specify the index to be replaced,')
- print('the quantity of the replacement card, and the')
- print('replacement card\'s name.')
- print('replace <index> <number> <card name>')
- return
- try:
- index, num, name = args.split(' ', 2)
- except ValueError:
- print('Not enough information given. You need to include')
- print('the index to be replaced, and the quantity and name')
- print('of the replacement card.')
- print('replace <index> <number> <card name>')
- return
- try:
- index, num = (int(index), int(num))
- except ValueError:
- print('Both <index> and <number> need to be numbers.')
- print('replace <index> <number> <card name>')
- return
- cards = self.cats[self.cat]
- cards[index] = (num, name)
- self.cats[self.cat] = cards
- def cmd_cat(self, args):
- """Syntax: cat <category>
- Selects the chosen category, creates it if it doesn't already exist.
- """
- if args == '':
- print('No category given. You must specify a category to select it.\ncat <category>')
- if args not in self.catList:
- self.addcat(args)
- self.cat = args
- self.prompt = args + '> '
- self.cards = self.cats[args]
- def cmd_cats(self, args):
- """Syntax: cats
- Prints a list of all current categories"""
- if len(self.catList) == 0:
- print('No categories defined.\ncat <category>')
- return
- msg = ''
- for index in range(len(self.catList)):
- if len(self.catList) > 1 and index == len(self.catList):
- msg += ', and %s.' % self.catList[index]
- elif len(self.catList) == 1 and index == 1:
- msg += ' and %s.' % self.catList[index]
- elif index == 0:
- msg = self.catList[index]
- else:
- msg += ', %s' % self.catList[index]
- print('Categories:\n' + msg)
- def cmd_delcat(self, args):
- """Syntax: delcat <category>
- Deletes the chosen category."""
- if args == '':
- print('You need to specify a category.\ndelcat <category>')
- return
- try:
- self.removecat(args)
- except KeyError:
- print("Category %s doesn't exist." % args)
- else:
- print("Category %s has been deleted." % args)
- def cmd_save(self, args):
- """Syntax: save <name>
- Saves the deck as the chosen name."""
- if args == '':
- print('No deck specified.')
- return
- try:
- self.save(args)
- except IOError:
- print('Invalid path: %s' % (HOME + args + '.dck'))
- else:
- print('Saved %s.' % args)
- def cmd_load(self, args):
- """Syntax: load <name>
- Loads the deck with the chosen name."""
- if args == '':
- print('No deck specified.')
- return
- try:
- self.load(args)
- except IOError:
- print('Invalid path: %s' % HOME + args + '.dck')
- else:
- print('Loaded %s.' % args)
- def cmd_listdecks(self, args):
- """No syntax needed. Just type 'decks'.
- This will list the decks you've saved, sorted by directory.
- """
- decks = self.getListOfDecks()
- if len(decks) == 0:
- print('No decks saved yet.')
- return
- print('Saved Decks:')
- for deck in decks:
- print(deck)
- def cmd_print(self, args):
- """Syntax: print [-flags]
- Prints a decklist, you can change the appearance by specifying flags.
- Print a decklist using an HTML table: print -h
- Print a decklist that autocards: print -c
- Print a decklist with direct links to Gatherer cards: print -l
- Flags can be mixed, though -c and -l don't mix.
- Print a decklist that autocards in an HTML table: print -hc
- """
- args = args.split()
- options = {'autocard': False, 'html': False, 'link': False}
- for arg in args:
- if arg[0] != '-':
- continue
- for char in arg:
- if char == '-':
- continue
- if char == 'c' and options['link'] == False:
- options['autocard'] = True
- continue
- if char == 'h':
- options['html'] = True
- if char == 'l' and options['autocard'] == False:
- options['link'] = True
- if options['html'] == True:
- deck = self.getHtmlDeck(options)
- else:
- deck = self.getDeckList(options)
- print(deck+'\n')
- cpd.clipboard_clear()
- cpd.clipboard_append(deck)
- cmd_input('Press any key to continue.')
- def iniparse(data):
- struct = dict()
- cat = None
- catList = list()
- for line in data.split('\n'):
- if len(line) > 2 and line[0] == '[' and line[-1] == ']':
- cat = line[1:-1]
- struct[cat] = dict()
- catList.append(cat)
- continue
- else:
- if type(line) != str or len(line) == 0:
- break
- key, value = line.split('=', 1)
- struct[cat][key] = value
- return (catList, struct)
- def makeDirAndName(name):
- filepath = HOME + name + '.dck'
- path = filepath.split('/')
- name = path.pop()
- path = '/'.join(path) + '/'
- if not os.path.exists(path):
- os.makedirs(path)
- return path + name
- def main():
- dl = Decklist()
- cmds = {
- 'add': dl.cmd_add,
- 'cat': dl.cmd_cat,
- 'cats': dl.cmd_cats,
- 'clear': dl.cmd_clear,
- 'decks': dl.cmd_listdecks,
- 'del': dl.cmd_del,
- 'delcat': dl.cmd_delcat,
- 'load': dl.cmd_load,
- 'name': dl.cmd_name,
- 'print': dl.cmd_print,
- 'replace': dl.cmd_replace,
- 'save': dl.cmd_save
- }
- keys = list()
- for key in cmds:
- keys.append(key)
- keys.sort()
- while True:
- if dl.cat == '':
- dl.prompt = '> '
- elif dl.cat not in dl.cats.keys():
- dl.cat = ''
- dl.prompt = '> '
- else:
- dl.cards = dl.cats[dl.cat]
- print(dl.cat)
- for index in range(len(dl.cards)):
- card = dl.cards[index]
- print('%2d) %2dx %s' % (index, card[0], card[1]) )
- cmd = cmd_input('\n'+dl.prompt).rstrip().split(None, 1)
- print('')
- if cmd == '':
- continue
- if len(cmd) == 2:
- args = cmd.pop()
- else:
- args = ''
- cmd = cmd[0].lower()
- if cmd == 'exit':
- break
- if cmd == 'help':
- if args == '':
- print('The commands are:')
- keys.sort()
- for key in keys:
- print(key)
- print("\nType 'help' followed by the name of the command you want to learn more about the command.\n")
- elif (args.split()[0].lower() in cmds.keys()):
- key = args.split()[0].lower()
- print(cmds[key].__doc__)
- else:
- print("You didn't give a valid command to find help on.")
- continue
- if cmd not in keys:
- print("%s is not a valid command." % cmd)
- continue
- cmds[cmd](args)
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment