import asyncio import json from websockets.server import serve import traceback import time print("-------") print("started") print("-------") json.dump({}, open("p.json", "w")) json.dump({}, open("b.json", "w")) async def echo(websocket): timout = 2500 async for message in websocket: if message == "data": p = json.load(open("p.json")) b = json.load(open("b.json")) await websocket.send(str(b)) else: try: p = json.load(open("p.json")) b = json.load(open("b.json")) jm = json.loads(message) if jm["token"] == None: await websocket.send(json.dumps({"type": "error", "data": "No token"})) if jm["type"] == "login": if jm["token"] not in p.keys(): p.update({jm["token"]: {"pos": {"x": 0,"y": 0, "vy": 0}}}) p[jm["token"]]["time"] = time.time() * 1000 json.dump(p, open("p.json", "w")) await websocket.send(json.dumps({"type": "init", "data": p[jm["token"]]})) elif jm["type"] == "update": if time.time() * 1000 - p[jm["token"]]["time"] >= timout: await websocket.send(json.dumps({"type": "reconnect"})) else: p.update({jm["token"]: jm["data"]}) json.dump(p, open("p.json", "w")) players = [] bullets = [] for key, value in p.items(): if key != jm["token"]: if time.time() * 1000 - value["time"] < timout: players.append({"pos": value["pos"], "name": value["name"], "color": value["color"]}) await websocket.send(json.dumps({"type": "update", "data": {"players": players}})) for key, value in b.items(): if type(value) is list: for i in value: if (time.time() - i["time"] / 1000) * 60 <= 420: bullets.append(value) await websocket.send(json.dumps({"type": "bullet", "data": bullets})) elif jm["type"] == "bullet": print(jm) if jm["token"] not in b.keys(): b.update({jm["token"]: []}) b[jm["token"]].append(jm["data"]) json.dump(b, open("b.json", "w")) except Exception: print(traceback.format_exc()) print(message) print(p) print(b) async def main(): async with serve(echo, "0.0.0.0", 7860): await asyncio.Future() asyncio.run(main())