DanisRace_Multiplayer/api.py

85 lines
1.5 KiB
Python
Raw Normal View History

2025-03-18 23:01:22 +02:00
# AGPLv3 or later
import json
import zlib
2025-03-18 23:03:58 +02:00
import random
2025-03-18 23:01:22 +02:00
import handler
2025-03-18 23:03:58 +02:00
2025-03-18 23:01:22 +02:00
players = {}
def RandomString(size=16):
# This will generate random strings, primarily
# for the purpose of recognizing the same objects
# on the network.
good = "1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM"
text = ""
for i in range(size):
text = text + random.choice(good)
return text
def run(data):
resp = {}
# NEW ID
if "id" in data and not data["id"]:
new_id(resp)
2025-03-18 23:23:38 +02:00
if "players" in data:
list_players(resp)
2025-03-18 23:43:05 +02:00
if "username" in data and data.get("id"):
set_username(resp, data["username"], data.get("id"))
2025-03-18 23:01:22 +02:00
return resp
def new_id(resp):
# Generates a new ID
ID = RandomString()
while ID in players:
ID = RandomString()
player = {"username":safe_username("Player")}
players[ID] = player
resp["id"] = ID
resp["player"] = player
def safe_username(name):
2025-03-18 23:13:21 +02:00
count = 0
2025-03-18 23:17:33 +02:00
for ID in players:
player = players[ID]
2025-03-18 23:13:21 +02:00
if player.get("username", "").startswith(name):
count += 1
if not count:
return name
else:
return name + "_" + str(count+1)
2025-03-18 23:43:05 +02:00
def set_username(resp, name, ID):
name = safe_username(name)
2025-03-18 23:44:24 +02:00
players[ID]["username"] = name
2025-03-18 23:43:05 +02:00
resp["username"] = name
2025-03-18 23:23:38 +02:00
def list_players(resp):
2025-03-18 23:01:22 +02:00
2025-03-18 23:23:38 +02:00
p = []
for ID in players:
player = players[ID]
p.append(player.get("username", "Player_Unknown"))
resp["players"] = p
2025-03-18 23:01:22 +02:00