minecraft_manager/external/stats.py

92 lines
2.6 KiB
Python
Raw Normal View History

2018-09-20 02:56:17 +00:00
import os, json
from minecraft_manager.models import Player
from django.conf import settings
stats_dir = os.path.join(settings.MINECRAFT_BASE_DIR, getattr(settings, "WORLD", "world"), "stats")
2018-10-11 02:42:55 +00:00
stats_filter = getattr(settings, 'STATS_FILTER', [])
2018-09-20 02:56:17 +00:00
def get_score(data):
return data['score']
def get_stats():
stats = {}
for filename in os.listdir(stats_dir):
with open(stats_dir + "/" + filename) as json_file:
2018-10-11 02:42:55 +00:00
raw = json.load(json_file)['stats']
clean = {}
for r in raw:
if not any(sf.lower() in r.lower() for sf in stats_filter):
clean[r] = raw[r]
2018-09-20 02:56:17 +00:00
uuid = filename.replace(".json", "")
2018-10-11 02:42:55 +00:00
stats[uuid] = clean
2018-09-20 02:56:17 +00:00
return stats
def get_names(stats=None, sort=False):
names = []
if not stats:
stats = get_stats()
for uuid in stats:
for base in stats[uuid]:
for stat in stats[uuid][base]:
name = "{}.{}".format(base, stat)
if name not in names:
names.append(name)
if sort:
names = sorted(names)
return names
def top_ten_stat(stat):
stats = get_stats()
top_ten = []
parts = stat.split('.')
for s in stats:
if parts[0] in stats[s]:
top_ten.append({'uuid': s, 'score': stats[s][parts[0]][parts[1]] if parts[1] in stats[s][parts[0]] else 0})
top_ten = sorted(top_ten, key=get_score, reverse=True)[:10]
for idx, tt in enumerate(top_ten):
uuid = tt['uuid']
try:
top_ten[idx]['username'] = Player.objects.get(uuid=uuid).username
except:
top_ten[idx]['username'] = uuid
return top_ten
def top_ten_player(uuid):
stats = get_stats()
names = get_names(stats)
top_ten_list = {}
for name in names:
top_ten_list[name] = []
parts = name.split('.')
for stat in stats:
bases = stats[stat]
if parts[0] in bases:
top_ten_list[name].append({'uuid': stat, 'score': bases[parts[0]][parts[1]] if parts[1] in bases[parts[0]] else 0})
top_ten_list[name] = sorted(top_ten_list[name], key=get_score, reverse=True)
top_ten = []
for tt in top_ten_list:
idx = 0
for ttl in top_ten_list[tt]:
if idx > 10:
break
if ttl['uuid'] == uuid:
ttl['rank'] = idx+1
ttl['stat'] = tt
top_ten.append(ttl)
break
idx += 1
return top_ten
def one_single(uuid, stat):
stats = get_stats()
if uuid in stats:
return [{'uuid': uuid, 'stat': stat, 'score': stats[uuid][stat]}]
return 0