import json import toggle_game as tg def recieve_game(game_fp) -> dict: """ Load game in from json string, returning game dict Raises exception on invalid game """ game = json.load(game_fp) if game['size'] < 0 or game['size'] > 100: raise Exception("Invalid Board size") if game['size'] != len(game['board']): raise Exception("Game size and Board size do not match") if game['finished']: raise Exception("The game is finished") if game['human_turn']: raise Exception("Not the computer's turn") if game['version'] != "0.0.0": raise Exception("Invalid version") return game def create_game(length: int) -> None: return { 'size': length, 'finished': False, 'board': [True] * length, 'turn': 0, 'version': '0.0.0', 'human_turn': , 'winner': '' } def send_game(game: dict) -> str: game_json = json.dumps(game) return game_json.encode('utf-8') def play_game(game: dict) -> None: if game['turn'] == 0: game['human_turn'] = not tg.P(game['size']) > 0 game['turn'] += 1 if game['human_turn']: return game['turn'] += 1 i = tg.find_move(game) game['board'] = tg.make_move(game, i) game['human_turn'] = True game['finished'] = tg.i_have_won(game) if game['finished']: game['winner'] = 'Computer' def application(env, start_response): headers = [('Content-Type', 'application/json')] start_response('200 OK', headers) query = env['QUERY_STRING'] path_info = env['PATH_INFO'] match env['REQUEST_METHOD'], env['PATH_INFO']: case ('GET', '/toggle/newgame'): # TODO: return descriptive status code game = create_game(query['size']) return [send_game(game)] case ('POST', '/toggle/play'): # TODO: return descriptive status code try: game = recieve_game(env['wsgi.input']) except json.JSONDecodeError: return [json.dumps({'Error': 'json parsing error, is your request formatted correctly?'}).encode('utf-8')] play_game(game) return [send_game(game)] case ('DELETE', _): start_response('405 Method Not Allowed', headers) case _: start_response('404 Not Found', headers) return [json.dumps({'not_post': True}).encode('utf-8')] def main(): pass