DanisRace_Multiplayer/api.py

85 lines
1.5 KiB
Python
Raw Permalink 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
2025-03-18 23:59:56 +02:00
def run(a, data):
2025-03-18 23:01:22 +02:00
resp = {}
2025-03-18 23:59:56 +02:00
# Generating new ID for new player
ID = stripID(a)
2025-03-19 00:00:31 +02:00
if ID not in players:
2025-03-18 23:59:56 +02:00
new_id(resp, ID)
2025-03-18 23:01:22 +02:00
2025-03-18 23:23:38 +02:00
if "players" in data:
list_players(resp)
2025-03-18 23:59:56 +02:00
if "username" in data:
2025-03-19 00:03:38 +02:00
set_username(resp, data.get("username"), ID)
2025-03-18 23:43:05 +02:00
2025-03-18 23:01:22 +02:00
return resp
2025-03-18 23:59:56 +02:00
def stripID(a):
return a[0]+":"+str(a[1])
2025-03-18 23:01:22 +02:00
2025-03-18 23:59:56 +02:00
def new_id(resp, ID):
2025-03-18 23:01:22 +02:00
player = {"username":safe_username("Player")}
players[ID] = player
resp["id"] = ID
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):
2025-03-18 23:59:56 +02:00
if name:
name = safe_username(name)
players[ID]["username"] = name
resp["username"] = name
else:
resp["username"] = players[ID]["username"]
2025-03-18 23:43:05 +02:00
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