-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
380 lines (364 loc) · 17.3 KB
/
Copy pathmain.py
File metadata and controls
380 lines (364 loc) · 17.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import bottle
import json
import os
import re
import time
import copy
import socket
import threading
import webbrowser
import urllib.parse
import mimetypes
import sys
from bottle import Bottle, request, response, static_file
from datetime import datetime
BASE_DIR = os.path.dirname(os.path.abspath(__file__)) if not getattr(sys, chr(39)+chr(102)+chr(114)+chr(111)+chr(122)+chr(101)+chr(110)+chr(39), False) else sys._MEIPASS
OUTPUT_DIR = os.path.join(os.path.dirname(sys.executable), 'output') if getattr(sys, 'frozen', False) else os.path.join(BASE_DIR, 'output')
FACTIONS_DIR = os.path.join(BASE_DIR, 'assets', 'factions')
MAPS_DIR = os.path.join(BASE_DIR, 'assets', 'maps')
STYLES_SB_DIR = os.path.join(BASE_DIR, 'styles', 'scoreboard')
STYLES_BP_DIR = os.path.join(BASE_DIR, 'styles', 'banpick')
FACTION_ORDER = ['美国','欧洲联盟','太平洋阵线','苏俄','拉丁同盟','中国','心灵军团','天蝎组织','总部守卫','狂鲨先锋','科洛尼亚侧翼','最后堡垒']
def scan_factions():
factions = []
if not os.path.isdir(FACTIONS_DIR): return factions
for fname in os.listdir(FACTIONS_DIR):
if fname.lower().endswith('.png'):
raw = os.path.splitext(fname)[0]
factions.append({'id':raw,'name':raw,'icon':'/api/faction-asset/'+urllib.parse.quote(raw)})
om = {n:i for i,n in enumerate(FACTION_ORDER)}
factions.sort(key=lambda f: om.get(f['id'], 999))
return factions
def scan_maps():
ml = []
if not os.path.isdir(MAPS_DIR): return ml
for fname in sorted(os.listdir(MAPS_DIR)):
if fname.lower().endswith('.png'):
raw = os.path.splitext(fname)[0]
ml.append({'id':raw,'name':raw,'thumbnail':'/api/map-asset/'+urllib.parse.quote(raw)})
return ml
class AppState:
def __init__(self):
self.lock = threading.Lock()
self.data = {'matchFormat':5,'player1':'Player 1','player2':'Player 2',
'score1':0,'score2':0,'mode':'1v1','player1b':'','player2b':'','player1bFaction':None,'player2bFaction':None,'globalBanFactions':[],'player1BanFactions':[],'player2BanFactions':[],
'globalBanMaps':[],'currentPickMap':None,'player1PickFaction':None,'player2PickFaction':None,
'style':'default','factions':[],'maps':[],
'gameMode':'ban','player1DraftFactions':[],'player2DraftFactions':[],'banpickFontSize':12,'banpickFontColor':'#ffffff','banpickFontStroke':'','banpickStrokeWidth':1,'banpickFontStrokeEnabled':False,'scoreboardSaturation':1.0,'scoreboardBrightness':1.0}
self.records = []; self.is_first_record = True
def get(self):
with self.lock: return copy.deepcopy(self.data)
def set(self, k, v):
with self.lock: self.data[k] = v
def get_snapshot(self):
d = self.data
return {k:d[k] for k in ['matchFormat','player1','player2','score1','score2',
'globalBanFactions','player1BanFactions','player2BanFactions',
'globalBanMaps','currentPickMap','player1PickFaction','player2PickFaction','player1b','player2b','player1bFaction','player2bFaction','gameMode','player1DraftFactions','player2DraftFactions','banpickFontSize','banpickFontColor','banpickFontStroke','banpickStrokeWidth','banpickFontStrokeEnabled','scoreboardSaturation','scoreboardBrightness','mode']}
state = AppState()
app = Bottle()
@app.route('/')
def index():
return '<h2>MO Scoreboard</h2><p><a href="/scoreboard">/scoreboard</a></p><p><a href="/banpick">/banpick</a></p><p><a href="/control">/control</a></p>'
@app.route('/scoreboard')
def serve_sb(): return static_file('index.html', root=os.path.join(BASE_DIR,'renderer','scoreboard'))
@app.route('/banpick')
def serve_bp(): return static_file('index.html', root=os.path.join(BASE_DIR,'renderer','banpick'))
@app.route('/control')
def serve_ct():
response.set_header('Cache-Control', 'no-cache, no-store, must-revalidate')
response.set_header('Pragma', 'no-cache')
response.set_header('Expires', '0')
html = open(os.path.join(BASE_DIR,'renderer','control','index.html'), 'r', encoding='utf-8').read()
sb=['default','neon']
if os.path.isdir(STYLES_SB_DIR):
for f in os.listdir(STYLES_SB_DIR):
if f.endswith('.css') and f not in ('default.css','neon.css'): sb.append(f[:-4])
bp=['default','minimal']
if os.path.isdir(STYLES_BP_DIR):
for f in os.listdir(STYLES_BP_DIR):
if f.endswith('.css') and f not in ('default.css','minimal.css'): bp.append(f[:-4])
merged=list(sb)
for s in bp:
if s not in merged: merged.append(s)
import json
options_str = ''
for s in merged:
options_str += '<option value="' + s + '">' + s + '</option>'
html = html.replace('<select id="select-style"></select>', '<select id="select-style">' + options_str + '</select>')
return html
@app.route('/styles/<path:path>')
def serve_styles(path): return static_file(path, root=os.path.join(BASE_DIR,'styles'))
@app.route('/renderer/<w>/<f>')
def serve_renderer(w, f): return static_file(f, root=os.path.join(BASE_DIR,'renderer',w))
@app.route('/output/<path:path>')
def serve_output(path): return static_file(path, root=os.path.join(BASE_DIR,'output'))
@app.route('/api/faction-asset/<name>')
def serve_fac_asset(name):
if os.path.isdir(FACTIONS_DIR):
for f in os.listdir(FACTIONS_DIR):
if os.path.splitext(f)[0].lower() == name.lower():
with open(os.path.join(FACTIONS_DIR,f),'rb') as fh: data=fh.read()
return bottle.HTTPResponse(data, content_type=mimetypes.guess_type(f)[0] or 'image/png')
return bottle.HTTPError(404)
@app.route('/api/map-asset/<name>')
def serve_map_asset(name):
if os.path.isdir(MAPS_DIR):
for f in os.listdir(MAPS_DIR):
if os.path.splitext(f)[0].lower() == name.lower():
with open(os.path.join(MAPS_DIR,f),'rb') as fh: data=fh.read()
return bottle.HTTPResponse(data, content_type=mimetypes.guess_type(f)[0] or 'image/png')
return bottle.HTTPError(404)
def p_str(k): return request.forms.get(k) or (request.json.get(k) if request.json else None)
def p_int(k):
try: return int(request.forms.get(k) or (request.json.get(k) if request.json else 0))
except: return 0
def p_float(k, d=1.0):
try: return float(request.forms.get(k) or (request.json.get(k) if request.json else d))
except: return float(d)
def ok(**kw):
response.content_type='application/json; charset=utf-8'; kw['ok']=True
return json.dumps(kw, ensure_ascii=False)
@app.route('/api/state')
def api_state():
response.content_type='application/json; charset=utf-8'
return json.dumps(state.get(), ensure_ascii=False)
@app.route('/api/factions')
def api_factions():
response.content_type='application/json; charset=utf-8'
return json.dumps(state.data.get('factions',[]), ensure_ascii=False)
@app.route('/api/maps')
def api_maps():
response.content_type='application/json; charset=utf-8'
return json.dumps(state.data.get('maps',[]), ensure_ascii=False)
@app.route('/api/sb-styles')
def api_sb_styles():
s=['default','neon']
if os.path.isdir(STYLES_SB_DIR):
for f in os.listdir(STYLES_SB_DIR):
if f.endswith('.css') and f not in ('default.css','neon.css'): s.append(f[:-4])
response.content_type='application/json; charset=utf-8'
return json.dumps(s)
@app.route('/api/bp-styles')
def api_bp_styles():
s=['default','minimal']
if os.path.isdir(STYLES_BP_DIR):
for f in os.listdir(STYLES_BP_DIR):
if f.endswith('.css') and f not in ('default.css','minimal.css'): s.append(f[:-4])
response.content_type='application/json; charset=utf-8'
return json.dumps(s)
@app.route('/api/styles')
def api_styles():
sb=['default','neon']
if os.path.isdir(STYLES_SB_DIR):
for f in os.listdir(STYLES_SB_DIR):
if f.endswith('.css') and f not in ('default.css','neon.css'): sb.append(f[:-4])
bp=['default','minimal']
if os.path.isdir(STYLES_BP_DIR):
for f in os.listdir(STYLES_BP_DIR):
if f.endswith('.css') and f not in ('default.css','minimal.css'): bp.append(f[:-4])
merged=list(sb)
for s in bp:
if s not in merged: merged.append(s)
response.content_type='application/json; charset=utf-8'
return json.dumps(merged)
@app.route('/api/player-name','POST')
def api_player_name():
p,n=p_int('player'),p_str('name')
if p==1: state.set('player1',n or '')
elif p==2: state.set('player2',n or '')
elif p==3: state.set('player1b',n or '')
elif p==4: state.set('player2b',n or '')
return ok()
@app.route('/api/change-score','POST')
def api_change_score():
p,d=p_int('player'),p_int('delta')
with state.lock:
if p==1: state.data['score1']=max(0,state.data['score1']+d)
elif p==2: state.data['score2']=max(0,state.data['score2']+d)
return ok()
@app.route('/api/match-format','POST')
def api_mf():
v=p_int('value')
if v>0: state.set('matchFormat',v)
return ok()
@app.route('/api/global-ban-factions','POST')
def api_gbf():
state.set('globalBanFactions',json.loads(p_str('ids') or '[]')[:3]); return ok()
@app.route('/api/player-ban-factions','POST')
def api_pbf():
p,i=p_int('player'),json.loads(p_str('ids') or '[]')
if p==1: state.set('player1BanFactions',i[:3])
elif p==2: state.set('player2BanFactions',i[:3])
return ok()
@app.route('/api/global-ban-maps','POST')
def api_gbm():
state.set('globalBanMaps',json.loads(p_str('ids') or '[]')[:4]); return ok()
@app.route('/api/current-pick-map','POST')
def api_cpm():
m=p_str('id'); state.set('currentPickMap',m if m else None); return ok()
@app.route('/api/player-pick-faction','POST')
def api_ppf():
p,f=p_int('player'),p_str('id')
if p==1: state.set('player1PickFaction',f if f else None)
elif p==2: state.set('player2PickFaction',f if f else None)
elif p==3: state.set('player1bFaction',f if f else None)
elif p==4: state.set('player2bFaction',f if f else None)
return ok()
@app.route('/api/style','POST')
def api_style():
n=p_str('name')
state.set('style',n or 'default')
return ok()
@app.route('/api/record','POST')
def api_record():
now=datetime.now().strftime('%Y-%m-%d %H:%M:%S')
snap=state.get_snapshot(); snap['timestamp']=now
if state.is_first_record: state.records=[snap]; state.is_first_record=False
else: state.records.append(snap)
return ok(msg='Recorded at '+now)
@app.route('/api/clear-records','POST')
def api_cr(): state.records=[]; state.is_first_record=True; return ok()
@app.route('/api/clear-all','POST')
def api_ca():
with state.lock:
state.data['player1']='Player 1'; state.data['player2']='Player 2'
state.data['player1b']=''; state.data['player2b']=''
state.data['player1bFaction']=None; state.data['player2bFaction']=None
state.data['score1']=0; state.data['score2']=0
state.data['globalBanFactions']=[]; state.data['player1BanFactions']=[]
state.data['player2BanFactions']=[]; state.data['globalBanMaps']=[]
state.data['currentPickMap']=None; state.data['player1PickFaction']=None
state.data['player2PickFaction']=None
state.records=[]; state.is_first_record=True; return ok()
@app.route('/api/export','POST')
def api_export():
if not state.records: return ok(ok=False,msg='No data')
os.makedirs(OUTPUT_DIR,exist_ok=True)
ts=datetime.now().strftime('%Y%m%d_%H%M%S')
fp=os.path.join(OUTPUT_DIR,f'MO_Scoreboard_{ts}.txt')
fm={f['id']:f['name'] for f in state.data['factions']}
mm={m['id']:m['name'] for m in state.data['maps']}
with open(fp,'w',encoding='utf-8') as fh:
for i,r in enumerate(state.records):
fh.write(f'=== Game {i+1} ({r.get("timestamp","?")}) ===\n')
if i==0:
fh.write(f'Match Format: BO{r["matchFormat"]}\n')
# Ban/draft data only on first record
if i==0 and r.get('gameMode')=='draft':
p1df = [fm.get(f,f) for f in r.get('player1DraftFactions',[])]
p2df = [fm.get(f,f) for f in r.get('player2DraftFactions',[])]
if r.get('mode')=='2v2':
d1n='Team 1'; d2n='Team 2'
else:
d1n=r.get('player1','P1'); d2n=r.get('player2','P2')
fh.write(f'{d1n} Draft Factions: {', '.join(p1df) or "(none)"}\n')
fh.write(f'{d2n} Draft Factions: {', '.join(p2df) or "(none)"}\n')
fh.write(f'Global Ban Maps: {", ".join([mm.get(m,m) for m in r["globalBanMaps"]]) or "(none)"}\n')
elif i==0:
fh.write(f'Global Ban Factions: {", ".join([fm.get(f,f) for f in r["globalBanFactions"]]) or "(none)"}\n')
fh.write(f'{r["player1"]} Ban Factions: {", ".join([fm.get(f,f) for f in r["player1BanFactions"]]) or "(none)"}\n')
fh.write(f'{r["player2"]} Ban Factions: {", ".join([fm.get(f,f) for f in r["player2BanFactions"]]) or "(none)"}\n')
fh.write(f'Global Ban Maps: {", ".join([mm.get(m,m) for m in r["globalBanMaps"]]) or "(none)"}\n')
if r.get('mode')=='2v2':
fh.write(f'Players (2v2): {r["player1"]} / {r.get("player1b","")} vs {r["player2"]} / {r.get("player2b","")}\n')
else:
fh.write(f'Players: {r["player1"]} vs {r["player2"]}\n')
fh.write(f'Current Map: {mm.get(r.get("currentPickMap",""),r.get("currentPickMap","(none)"))}\n')
if r.get('mode')=='2v2':
fh.write(f'{r["player1"]} (A) Pick: {fm.get(r.get("player1PickFaction",""),r.get("player1PickFaction","(none)"))}\n')
p1bp = fm.get(r.get('player1bFaction',''),r.get('player1bFaction','(none)'))
fh.write(f'{r.get("player1b","")} (B) Pick: {p1bp}\n')
p2bp = fm.get(r.get('player2bFaction',''),r.get('player2bFaction','(none)'))
fh.write(f'{r["player2"]} (A) Pick: {fm.get(r.get("player2PickFaction",""),r.get("player2PickFaction","(none)"))}\n')
fh.write(f'{r.get("player2b","")} (B) Pick: {p2bp}\n')
else:
fh.write(f'{r["player1"]} Pick: {fm.get(r.get("player1PickFaction",""),r.get("player1PickFaction","(none)"))}\n')
fh.write(f'{r["player2"]} Pick: {fm.get(r.get("player2PickFaction",""),r.get("player2PickFaction","(none)"))}\n')
if r.get('mode')=='2v2':
sn1='Team 1'; sn2='Team 2'
else:
sn1=r['player1']; sn2=r['player2']
fh.write(f'Score: {sn1} {r["score1"]} - {r["score2"]} {sn2}\n\n')
return ok(msg='Exported to '+fp,file=fp)
@app.route('/api/game-mode','POST')
def api_game_mode():
m=p_str('mode')
if m in ('ban','draft'): state.set('gameMode',m)
return ok()
@app.route('/api/draft-pick','POST')
def api_draft_pick():
p=p_int('player');ids=json.loads(p_str('ids') or '[]')
if p==1: state.set('player1DraftFactions',ids[:6])
elif p==2: state.set('player2DraftFactions',ids[:6])
return ok()
@app.route('/api/shutdown','POST')
def api_shutdown():
state.records=[]; state.is_first_record=True
threading.Timer(0.5,lambda: os._exit(0)).start(); return ok(msg='Shutting down...')
@app.route('/api/set-mode','POST')
def api_set_mode():
m=p_str('mode')
if m in ('1v1','2v2'): state.set('mode',m)
return ok()
@app.route('/api/banpick-font-size','POST')
def api_bp_fs():
v=p_int('value')
if v and 8<=v<=36: state.set('banpickFontSize',v)
return ok()
@app.route('/api/banpick-font-color','POST')
def api_bp_fc():
v=p_str('value')
if v: state.set('banpickFontColor',v)
return ok()
@app.route('/api/banpick-font-stroke-enabled','POST')
def api_bp_se():
v=p_int('value')
if v in (0,1): state.set('banpickFontStrokeEnabled',bool(v))
return ok()
@app.route('/api/banpick-stroke-width','POST')
def api_bp_sw():
v=p_int('value')
if 0<=v<=10: state.set('banpickStrokeWidth',v)
return ok()
@app.route('/api/banpick-font-stroke','POST')
def api_bp_fst():
v=p_str('value')
state.set('banpickFontStroke',v or '')
return ok()
@app.route('/api/scoreboard-saturation','POST')
def api_sb_sat():
v=p_float('value')
if v: state.set('scoreboardSaturation',v)
return ok()
@app.route('/api/scoreboard-brightness','POST')
def api_sb_bri():
v=p_float('value')
if v: state.set('scoreboardBrightness',v)
return ok()
DEFAULT_PORT = 14567
def find_free_port():
with socket.socket(socket.AF_INET,socket.SOCK_STREAM) as s: s.bind(('',0)); return s.getsockname()[1]
def main():
if len(sys.argv)>1:
try: port=int(sys.argv[1])
except ValueError: port=find_free_port()
else: port=DEFAULT_PORT
base=f'http://127.0.0.1:{port}'
state.data['factions']=scan_factions()
state.data['maps']=scan_maps()
print(f'[MO Scoreboard] Server: {base}')
print(f'[INFO] Factions: {len(state.data["factions"])}, Maps: {len(state.data["maps"])}')
sw,sh=727,1080 # will be updated by GetSystemMetrics
import ctypes; sw=ctypes.windll.user32.GetSystemMetrics(0); sh=ctypes.windll.user32.GetSystemMetrics(1)
ov_w=sw; ov_h=sh//6
bp_h=sh
print(f'[INFO] OBS Scoreboard Browser Source: {base}/scoreboard')
print(f'[INFO] OBS BanPick Browser Source: {base}/banpick')
print(f'[INFO] Control Panel (browser): {base}/control')
print('[INFO] Press Ctrl+C to stop.')
threading.Timer(0.5,lambda: webbrowser.open(f'{base}/control')).start()
bottle.run(app,server='wsgiref',host='127.0.0.1',port=port,quiet=True)
if __name__=='__main__': main()