def application(environ, start_response): try: if environ['REQUEST_METHOD'] == 'POST': request_body_size = int(environ.get('CONTENT_LENGTH', '0')) request_body = environ['wsgi.input'].read(request_body_size) data = json.loads(request_body.decode()) WORLDS = {} world = data['world'] if world not in WORLDS: with open('public/' + world + '/OBJECTS.json') as f: objects = json.load(f) with open('public/' + world + '/ROOMS.json') as f: rooms = json.load(f) WORLDS['world'] = [objects, rooms] world = WORLDS['world'] game = GameEngine(world[0], world[1]) game.set_state(data['state']) cmd = game.decode_button_command(data['user_command']) prs = game.process_command(cmd) audio_prs = game.prompts_only(prs) text_prs = game.text_only(prs) ndata = { 'text': text_prs, 'audio': audio_prs, 'state': game.get_state() } start_response('200 OK', [('Content-Type', 'application/json')]) return [json.dumps(ndata).encode()] else: # If we are running alongside a web server then the server will handle static files. # This is for the stand-alone case (like running on the Farmer Says) fn = environ['PATH_INFO'] if fn == '/': fn = '/index.html' print('*', fn, '*') with open('public' + fn, 'rb') as f: data = f.read() if fn.endswith('.json'): start_response('200 OK', [('Content-Type', 'application/json')]) else: start_response('200 OK', [('Content-Type', 'text/html')]) return [data] except Exception: with open('ex.txt', 'w') as f: f.write(traceback.format_exc()) raise
class Application: def __init__(self, game, use_audio=True): if use_audio: print('Loading hardware ...') from farmer_says import FarmerSays print('... done') self._hardware = FarmerSays() self._hardware.start_audio_thread() else: self._hardware = None with open('public/' + game + '/ROOMS.json') as f: rooms = json.load(f) with open('public/' + game + '/OBJECTS.json') as f: objects = json.load(f) self._engine = GameEngine(objects, rooms) if self._hardware: self._hardware.set_audio_path('public/' + game + '/audio/') def print_long(self, txt): paras = txt.split('\n') for para in paras: print(textwrap.fill(para.strip(), COLUMNS)) def play_prompts(self, prs): if not self._hardware: return # stop any existing audio self._hardware.stop_audio() for pr in prs: self._hardware.queue_prompt([pr, 0.25]) def console_loop(self): known = [ 'NORTH', 'SOUTH', 'EAST', 'WEST', 'ACTION', 'LOOK', 'GETLEFT', 'GETRIGHT', 'DROPLEFT', 'DROPRIGHT', 'USELEFT', 'USERIGHT' ] replace = {'E': 'EAST', 'W': 'WEST', 'N': 'NORTH', 'S': 'SOUTH'} first_cmd = True while True: while True: if first_cmd: cmd = 'LOOK' first_cmd = False else: cmd = input('> ').upper().replace(' ', '') if cmd in replace: cmd = replace[cmd] if cmd not in known: print('## Unknown command:', cmd) continue cmd = self._engine.decode_button_command(cmd.upper()) prs = self._engine.process_command(cmd) if prs: aud_prs = self._engine.prompts_only(prs) self.play_prompts(aud_prs) prs = self._engine.text_only(prs) self.print_long(prs)