84 lines
1.5 KiB
Python
84 lines
1.5 KiB
Python
# AGPLv3 or later
|
|
|
|
import json
|
|
import zlib
|
|
import random
|
|
|
|
import handler
|
|
|
|
|
|
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(a, data):
|
|
|
|
resp = {}
|
|
|
|
# Generating new ID for new player
|
|
ID = stripID(a)
|
|
if ID not in players:
|
|
new_id(resp, ID)
|
|
|
|
if "players" in data:
|
|
list_players(resp)
|
|
|
|
if "username" in data:
|
|
set_username(resp, data.get("username"), ID)
|
|
|
|
return resp
|
|
|
|
def stripID(a):
|
|
return a[0]+":"+str(a[1])
|
|
|
|
|
|
def new_id(resp, ID):
|
|
|
|
player = {"username":safe_username("Player")}
|
|
players[ID] = player
|
|
|
|
resp["id"] = ID
|
|
|
|
def safe_username(name):
|
|
|
|
count = 0
|
|
for ID in players:
|
|
player = players[ID]
|
|
if player.get("username", "").startswith(name):
|
|
count += 1
|
|
if not count:
|
|
return name
|
|
else:
|
|
return name + "_" + str(count+1)
|
|
|
|
def set_username(resp, name, ID):
|
|
|
|
if name:
|
|
name = safe_username(name)
|
|
players[ID]["username"] = name
|
|
resp["username"] = name
|
|
else:
|
|
resp["username"] = players[ID]["username"]
|
|
|
|
def list_players(resp):
|
|
|
|
p = []
|
|
|
|
for ID in players:
|
|
player = players[ID]
|
|
p.append(player.get("username", "Player_Unknown"))
|
|
resp["players"] = p
|
|
|
|
|