from flask import Flask, render_template, request, redirect, url_for, flash, session from uuid import uuid4 from .classes import Game app = Flask(__name__) def find_game_by_id(id:str) -> dict: games = [] with open('games.json', 'r') as f: games = json.load(f) index = 0 for game in games: if game['id'] == id: return {"game": game, "idx": index} index += 1 return {"error": "Game not found"} def start_game(game:dict): pass @app.route('/') def index(): return "Empty for now" @app.route('/new//', methods=['POST']) def new_game(name, players): # Log new game into json file and return a websocket url for the game games = [] with open('games.json', 'r') as f: games = json.load(f) # Create new game game = { "game": name, "players": players, "in": [request.remote_addr], "join": None, "id": f"{uuid4().hex}", "status": "waiting", } games.append(game) with open('games.json', 'w') as f: json.dump(games, f) @app.route('/join/', methods=['POST']) def join_game(game_id): # Check if game exists game = find_game_by_id(game_id) if "error" in game: return {"error": "Game not found"} # Check if game is full game, idx = game['game'], game['idx'] if len(game['in']) >= game['players']: return {"error": "Game is full"} # Add player to game game['in'].append(request.remote_addr) # Check if game is ready if len(game['in']) == game['players']: game['status'] = "ready" start_game(game) return {"status": "starting"} games = [] with open('games.json', 'r') as f: games = json.load(f) games[game.index(game)] = game with open('games.json', 'w') as f: json.dump(games, f)