Get generated puzzles working

This commit is contained in:
Neale Pickett 2016-10-18 09:51:33 -06:00
parent 12c64ad48a
commit 2a22f3a684
1 changed files with 26 additions and 28 deletions

View File

@ -55,6 +55,9 @@ class Puzzle:
super().__init__()
if not os.path.isdir(path):
raise ValueError("No such directory: {}".format(path))
self._dict = defaultdict(lambda: [])
if os.path.isdir(path):
self._puzzle_dir = path
@ -63,34 +66,32 @@ class Puzzle:
self.message = bytes(random.choice(messageChars) for i in range(20))
self.body = ''
if not os.path.exists(path):
raise ValueError("No puzzle at path: {}".format(path))
elif os.path.isdir(path):
# Expected format is path/<points_int>.moth
pathname = os.path.split(path)[-1]
try:
self.points = int(pathname)
except ValueError:
pass
files = os.listdir(path)
# A list of temporary files we've created that will need to be deleted.
self._temp_files = []
if 'puzzle.moth' in files:
self._read_config(open(os.path.join(path, 'puzzle.moth')))
if 'puzzle.py' in files:
# Good Lord this is dangerous as fuck.
loader = SourceFileLoader('puzzle_mod', os.path.join(path, 'puzzle.py'))
puzzle_mod = loader.load_module()
if hasattr(puzzle_mod, 'make'):
puzzle_mod.make(self)
else:
raise ValueError("Unacceptable file type for puzzle at {}".format(path))
# Expected format is path/<points_int>.moth
pathname = os.path.split(path)[-1]
try:
self.points = int(pathname)
except ValueError:
raise ValueError("Directory name must be a point value: {}".format(path))
files = os.listdir(path)
self._seed = category_seed * self.points
self.rand = random.Random(self._seed)
# A list of temporary files we've created that will need to be deleted.
self._temp_files = []
if 'puzzle.moth' in files:
self._read_config(open(os.path.join(path, 'puzzle.moth')))
if 'puzzle.py' in files:
# Good Lord this is dangerous as fuck.
loader = SourceFileLoader('puzzle_mod', os.path.join(path, 'puzzle.py'))
puzzle_mod = loader.load_module()
if hasattr(puzzle_mod, 'make'):
self.body = '# `puzzle.body` was not set by the `make` function'
puzzle_mod.make(self)
else:
self.body = '# `puzzle.py` does not define a `make` function'
def cleanup(self):
"""Cleanup any outstanding temporary files."""
@ -214,16 +215,13 @@ class Puzzle:
def __getitem__(self, item):
return self._dict[item.lower()]
def make_answer(self, word_count, sep=b' '):
def make_answer(self, word_count, sep=' '):
"""Generate and return a new answer. It's automatically added to the puzzle answer list.
:param int word_count: The number of words to include in the answer.
:param str|bytes sep: The word separator.
:returns: The answer bytes
:returns: The answer string
"""
if type(sep) == str:
sep = sep.encode('ascii')
answer = sep.join(self.rand.sample(self.ANSWER_WORDS, word_count))
self['answer'] = answer