from __future__ import with_statement import MySQLdb import operator import dice import common def uncomment(line): 'Remove comment from a configuration file.' return line[:line.find('#')] if '#' in line else line def parse(line): 'Parse line from a configuration file.' return (v.strip() for v in line.split('=')) def getconfig(): 'Load variables from the configuration file.' with open('dbconfig') as dbconfig: return dict(parse(uncomment(line)) for line in dbconfig) DB = MySQLdb.connect(**getconfig()) def query(query): cursor = DB.cursor(MySQLdb.cursors.DictCursor) cursor.execute(query) return cursor.fetchall() def valueqry(type): return query('SELECT * FROM ' + type + '_values ORDER BY dice_lower') def namerealmqry(type, valid, realm): qry = """SELECT * FROM %s_names xn JOIN %s_realms xr ON xr.%s_name_id = xn.id JOIN realms r ON r.id = xr.realm_id WHERE xn.%s_value_id = %s AND r.name = '%s'""" qrymix = qry % (type, type, type, type, valid, realm) return query(qrymix) def nameqry(type, valid): qry = 'SELECT * FROM %s_names WHERE %s_value_id = %s' qrymix = qry % (type, type, valid) return query(qrymix) def treasureqry(el, type): qry = """SELECT * FROM treasure_listings tl JOIN treasure_subtypes ts ON ts.id = tl.treasure_subtype_id WHERE tl.el = %d AND ts.`type` = \'%s\' ORDER BY dice_lower """ % (el, type) return query(qry) def alchemqry(): alchemquery = """SELECT mai.dice_lower, mai.dice_upper, mai.dice_number, mai.dice_sides, ai.* FROM mundane_alchemical_items mai JOIN alchemical_items ai ON mai.alchemical_item_id = ai.id """ return query(alchemquery) def meleeqry(): commonqry = """ SELECT * FROM common_melee_weapons cmw JOIN weapons w ON cmw.weapon_id = w.id ORDER BY cmw.dice_lower """ return query(commonqry) def uncommonqry(): ucommonqry = """ SELECT * FROM uncommon_weapons uw JOIN weapons w ON uw.weapon_id = w.id ORDER BY uw.dice_lower """ return query(ucommonqry) def gearqry(): qry = """ SELECT * FROM mundane_gear mg JOIN gear g ON g.id = mg.gear_id ORDER BY mg.dice_lower """ return query(qry) def armorqry(id): return query('SELECT * FROM armor WHERE id = %d' % id)[0] def weaponqry(id): return query('SELECT * FROM weapons WHERE id = %d' % id)[0] def typeqry(type, filter=None): qry = 'SELECT * FROM %s ' % type if filter: qry += 'WHERE ' + filter + ' ' qry += 'ORDER BY dice_lower' return query(qry) def xtypes(type, x, hash=operator.itemgetter('id'), filter=None): return xraw(x, hash, typeqry(type, filter)) def xraw(x, hash, typerows): typelist = [dice.getroll(typerows, dice.d100()) for i in range(0, x)] return common.list2counts(typelist, hash) def ytypes(type, y, filter=None): return yraw(y, typeqry(type, filter)) def yraw(y, typerows): typelist = [dice.getroll(typerows, dice.d100()) for i in range(0, y)] return common.list2countstuple(typelist, operator.itemgetter('id'))