forked from jogordo/DnD_Archive
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
99 lines
2.8 KiB
99 lines
2.8 KiB
import os, glob
|
|
|
|
def get_kinds():
|
|
basepath = '../Rules/'
|
|
return sorted([pth for pth in os.listdir(basepath) if os.path.isdir(os.path.join(basepath, pth))])
|
|
|
|
class Rule(object):
|
|
CACHE_FNAME = {}
|
|
CACHE_NAME = {}
|
|
|
|
@classmethod
|
|
def get_cached(cls, path):
|
|
ret = cls.CACHE_FNAME.get(path)
|
|
if not ret:
|
|
ret = cls(path)
|
|
cls.CACHE_FNAME[path] = ret
|
|
return ret
|
|
|
|
@classmethod
|
|
def get_named(cls, name):
|
|
return cls.CACHE_NAME.get(name)
|
|
|
|
def __init__(self, path):
|
|
try:
|
|
f = open(path, 'r')
|
|
except OSError:
|
|
self.name = 'Invalid Rule'
|
|
self.kind = 'Invalid Kind'
|
|
self.content = 'Non-existent rule ' + path
|
|
else:
|
|
self.kind = os.path.basename(os.path.dirname(path))
|
|
lines = f.read().split('\n')
|
|
self.name = lines.pop(0)
|
|
lines.pop(0) # Divider
|
|
while not lines[0]:
|
|
lines.pop(0)
|
|
self.content = '\n'.join(lines)
|
|
self.CACHE_NAME[self.name] = self
|
|
|
|
class ManualRule(object):
|
|
def __init__(self, name, content, kind):
|
|
self.name = name
|
|
self.content = content
|
|
self.kind = kind
|
|
self.invalid = True
|
|
|
|
def rules_of_kind(kind):
|
|
basepath = os.path.join('../Rules', kind)
|
|
for fn in os.listdir(basepath):
|
|
fullfn = os.path.join(basepath, fn)
|
|
if os.path.isfile(fullfn):
|
|
yield Rule.get_cached(fullfn)
|
|
|
|
def sorted_rules_of_kind(kind):
|
|
return sorted(rules_of_kind(kind), key=lambda ru: ru.name)
|
|
|
|
def get_rules():
|
|
for kind in get_kinds():
|
|
for rule in rules_of_kind(kind):
|
|
yield rule
|
|
|
|
def sorted_rules():
|
|
return sorted(get_rules(), key=lambda ru: ru.name)
|
|
|
|
class Campaign(object):
|
|
def __init__(self, path):
|
|
f = open(path, 'r')
|
|
lines = f.read().split('\n')
|
|
self.name = lines.pop(0)
|
|
lines.pop(0) # Divider
|
|
while not lines[0]:
|
|
lines.pop(0)
|
|
|
|
kinds = set(get_kinds())
|
|
self.content = []
|
|
self.rules = []
|
|
for line in lines:
|
|
kind, sep, name = line.partition(':')
|
|
name = name.strip()
|
|
if sep and kind in kinds:
|
|
rule = Rule.get_named(name)
|
|
if rule:
|
|
self.rules.append(rule)
|
|
else:
|
|
self.rules.append(ManualRule(name, 'Rule not found.', 'Invalid Kind'))
|
|
continue
|
|
self.content.append(line)
|
|
self.content = '\n'.join(self.content)
|
|
|
|
def get_campaigns():
|
|
list(get_rules()) # Populate cache
|
|
basepath = '../Rules'
|
|
for fn in os.listdir(basepath):
|
|
fullfn = os.path.join(basepath, fn)
|
|
if os.path.isfile(fullfn):
|
|
yield Campaign(fullfn)
|
|
|
|
def get_sorted_campaigns():
|
|
return sorted(get_campaigns(), key=lambda ca: ca.name)
|