-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
1971 lines (1433 loc) · 49.1 KB
/
server.js
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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/node
console.log("Starting Xoclock");
// you may attach additional arguments to aplay, check aplay -L
const aplay = "aplay -D sysdefault"
//const aplay = "aplay "
// load libs
var http = require("http");
var https = require("https");
var auth = require('http-auth');
var fs = require("fs");
var sys = require('sys');
var exec = require('child_process').exec;
var spawn = require('child_process').spawn;
var crypto = require('crypto');
var hash_typ = "sha512";
var hash_dig = "hex";
var express = require('express');
// https needs certificates
var options = {
key: fs.readFileSync("key.pem"),
cert: fs.readFileSync("crt.pem")
};
// voice generation of display texts with api
var speeches = {};
var speechex = {};
function filename(text) {
return text.replace('.', '').trim().toLowerCase().replace(/ /g, '_').replace(/:/g, 'to') + ".wav";
};
function dspx(texts) {
texts.split('|').forEach(function(e) {
var key=filename(e);
speechex[key] = e;
});
return texts;
}
function dsp(texts) {
texts.split('|').forEach(function(e) {
var key=filename(e);
speeches[key] = e;
});
return texts;
}
function write_speechex() {
for (i in index) {
dspx(index[i].team);
}
fs.writeFileSync('speechex.json', JSON.stringify(speechex,null,4));
}
function write_speeches() {
for (var i=0; i<10; i++) {
for (var j=0; j<10; j++) {
dsp(i+":"+j);
}
}
fs.writeFileSync('speeches.json', JSON.stringify(speeches,null,4));
}
// Imports the Google Cloud client library
const textToSpeech = require('@google-cloud/text-to-speech');
// Creates a client
const client = new textToSpeech.TextToSpeechClient();
const AUDIO = "audio";
const TEAMS = "teams";
function download(dir, filename, text) {
const file = dir + "/" + filename;
if (fs.existsSync(file)) return;// console.log(filename + "already exists");
setTimeout(function(){
// Construct the request
const request = {
input: {text: text},
// Select the language and SSML Voice Gender (optional)
voice: {languageCode: 'en-US', ssmlGender: 'NEUTRAL', name: 'en-US-Wavenet-C'},
// Select the type of audio encoding
audioConfig: {audioEncoding: 'LINEAR16'},
};
// Performs the Text-to-Speech request
client.synthesizeSpeech(request, (err, response) => {
if (err) return console.error('ERROR:', err);
// Write the binary audio content to a local file
fs.writeFile(file, response.audioContent, 'binary', err => {
if (err) return console.error('ERROR:', err);
console.log('Audio content written to file:', file);
});
});
}, Math.floor(Math.random() * 60) * 100);
}
function speech_downloads() {
for (var i in speeches) {
download(AUDIO, i, speeches[i]);
}
write_speechex();
for (var j in speechex) {
download(TEAMS, j, speechex[j]);
}
for (var k=1; k<=60; k++ ) {
download(AUDIO, "gametime_" + k + '_seconds.wav', 'gametime ' + k + 'seconds');
};
for (var k=60; k<=600; k++ ) {
if (k<120) download(AUDIO, "gametime_" + k + '_seconds.wav', 'gametime 1 minute' + (k%60) + 'seconds');
else download(AUDIO, "gametime_" + k + '_seconds.wav', 'gametime ' + Math.floor(k/60) + ' minutes' + (k%60) + 'seconds');
};
}
// read input files
// TEAM INDEX
var index = [{},{}];
// set some defaults
index[0].team = dsp("Local Team");
index[1].team = dsp("Guest Team");
index[0].pin = "1111";
index[1].pin = "2222";
var groups = [{
a: 0,
b: 1
}];
// main xoclock object for currently running game
var xo = {};
xo.game_group = 0;
xo.title = "Paintball Turnament";
if (groups.length > 0) xo.groups = groups;
try {
index = JSON.parse(fs.readFileSync('index.json', 'utf8'));
console.log("Team-index loaded", index);
} catch(err) {
console.log("didnt load index.json ",err)
}
try {
groups = JSON.parse(fs.readFileSync('groups.json', 'utf8'));
console.log("groups loaded");
} catch(err) {
console.log("didnt load groups.json ",err)
}
var settings = {};
try {
settings = JSON.parse(fs.readFileSync('settings.json', 'utf8'));
} catch(err) {
console.log("didnt load settings.json ",err)
}
try {
xo = JSON.parse(fs.readFileSync('xo.json', 'utf8'));
console.log("loaded xo.json to continue.");
} catch(err) {
console.log("didnt load the xo.json ", err);
xo.groups = groups;
}
function save() {
fs.writeFile('xo.json', JSON.stringify(xo, null, 4), function(err) {
if(err) {
console.log(err);
} else {
console.log("xo JSON saved.");
}
});
}
function save_index() {
fs.writeFile('index.json', JSON.stringify(index, null, 4), function(err) {
if(err) console.log(err);
});
}
function save_groups() {
fs.writeFile('groups.json', JSON.stringify(xo.groups, null, 4), function(err) {
if(err) console.log(err);
});
}
//if (groups.length > 1 && !xo.groups) xo.groups = groups;
//if (groups.length > 0) xo.groups = groups;
function make_roundrobin() {
var t = index.length
//
var dualpits = true;
//We build a half matrix cut at the identity line, and conquer it parallel to identity
var s = (t * t - t)/2
console.log(t + ' teams in team-index, matches total: ' + s)
if (dualpits) console.log('Generating round-robin in dual-pits')
var A = [];
// n is the number of round robin teams
var n = t;
// that needs to b even
if (t % 2 === 1) n++;
// we make a dual-pit system here, so we need at least 4 teams
if (t < 4) {
dualpits = false;
}
var ns = (n*n-n)/2 // roundrobin teams
var r = n/2 // halfring-length
// we consider 0 as the fixed element
// we calculate the round-robin teams in a functional way
function getX(e) {
var o = e % r // step in the halfring
var t = ~~(e/r) // block: rotation times.
// the fixed element
if (o === 0) return 0
// ringify
return ( (o+t-1) % (n-1) ) +1
}
function getY(e) {
var o = e % r // step in the halfring
var t = ~~(e/r) // block: rotation times.
return ( (n - o + t -2) % (n-1) ) +1
}
function place(x,y) {
l = A.length - 1
if (dualpits) {
if (A[l] !== undefined && A[l].c === undefined && A[l].d === undefined) {
console.log('+',index[x].team,'|',index[y].team)
A[l].c = x;
A[l].d = y;
return;
}
}
console.log('-',index[x].team,'|',index[y].team)
A.push({a:x,b:y});
}
for (i = 0; i < ns; i++) {
var ix = getX(i)
var iy = getY(i)
// skip the bye elements
if (t % 2 === 1) {
if (ix === t || iy == t) continue
}
place(ix,iy)
}
return A;
// make roundrobin end
}
// verify team index format and files
function check_team_index() {
console.log("Check team index");
if (index.length < 2) {
index[0] = {team: 'Home team', pin: '1111'};
index[1] = {team: 'Guest team', pin: '2222'};
}
for (var i = 0; i < index.length; i++) {
// check teamname
if (!index[i].team) index[i].team = "Team-" + i;
// check team pin
if (!index[i].pin) index[i].pin = "" + Math.floor((Math.random() * 9) + 1) + "" + Math.floor((Math.random() * 9) + 1) + "" + Math.floor((Math.random() * 9) + 1) + "" + Math.floor((Math.random() * 9) + 1);
}
groups = make_roundrobin();
xo.groups = groups;
xo.game_group = 0;
init_xo(xo.groups[xo.game_group]);
io.emit('xo',xo);
rio.emit('xo',xo);
io.emit('setIndex', index);
rio.emit('setIndex', index);
save();
save_index();
save_groups();
speech_downloads();
};
function team_index_add(team) {
console.log("Add to team index", team)
for (var i = 0; i < index.length; i++) {
// check teamname
if (index[i].team === team) return console.log("Already in the index");
}
var ti = {};
ti.team = team;
ti.pin = "" + Math.floor((Math.random() * 10) + 1) + "" + Math.floor((Math.random() * 10) + 1) + "" + Math.floor((Math.random() * 10) + 1) + "" + Math.floor((Math.random() * 10) + 1);
index.push(ti);
check_team_index()
};
function team_index_remove(team) {
console.log("Remove from team index", team)
for (var i = 0; i < index.length; i++) {
// check teamname
if (index[i].team === team) index.splice(i,1);
}
check_team_index()
};
function team_index_clear() {
groups=[];
xo.groups = groups;
xo.game_group = 0;
io.emit('xo',xo);
rio.emit('xo',xo);
};
// verify team index format and files
function find_team_by_pin(pin) {
for (var i = 0; i < index.length; i++) {
// check password hash
//if (!index[i].hash && !index[i].pass) {
// var pass = Math.random().toString(36).slice(9);
// index[i].hash = crypto.createHash(hash_typ).update(pass).digest(hash_dig);
// console.log("ADDED team/password for " + index[i].team + " password: " + pass);
//}
if (index[i].pin == pin) return index[i].team;
}
return "visitor";
};
//console.log('admin ' + crypto.createHash(hash_typ).update('xxxxxx').digest(hash_dig));
// helper function to get the username from http-auth in socket.io
function getUserName(socket) {
if (!socket.handshake.headers.authorization) return;
if (socket.handshake.headers.authorization.search('Basic ') !== 0) return;
var auth = new Buffer(socket.handshake.headers.authorization.split(' ')[1], 'base64').toString().split(":");
return auth.shift();
};
// Set the default ports
if (!settings.http_port) settings.http_port = 80;
if (!settings.https_port) settings.https_port = 443;
if (!settings.keys_port) settings.keys_port = 8443;
// default is an empty password - for testing and devel!
// if (!settings.admin_hash) settings.admin_hash = "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e";
if (!settings.admin_pin) settings.admin_pin='0000';
// default admin username
if (!settings.admin_user) settings.admin_user = 'admin';
// minimum time for the other group to enter the filed
if (!settings.entrytime) settings.entrytime = 50;
// delay for announcments and such, ..
if (!settings.clock_delay) settings.clock_delay = 10;
if (!settings.volume) settings.volume = {};
if (!settings.volume.music) settings.volume.music = 30;
if (!settings.volume.announce) settings.volume.announce = 'on';
if (!settings.format) settings.format = {}
if (!settings.beep) settings.beep = true;
// quantize to multiples of 15s
if (!settings.quantize) settings.quantize = false;
//{
// "teamsize": "5 on 5",
// "condition": "mercy at 4 points",
// "gametime": "10 minutes",
// "rules": "m-500 format x-ball",
// "breaktime": "2 minutes",
// "overtime": "3 minutes",
// "pitsystem": "simple",
// "timeouts": 1
//};
if (!settings.format.teamsize) settings.format.teamsize = "5 on 5";
if (!settings.format.condition) settings.format.condition = "mercy at 4 points";
if (!settings.format.gametime) settings.format.gametime = "10 minutes";
if (!settings.format.rules) settings.format.rules = "M500 format x-ball";
if (!settings.format.breaktime) settings.format.breaktime = "2 minutes";
if (!settings.format.overtime) settings.format.overtime = "3 minutes";
//if (!settings.format.pitsystem) settings.format.pitsystem = "simple";
if (!settings.format.timeouts) settings.format.timeouts = "1";
dsp("1 on 1|2 on 2|3 on 3|4 on 4|5 on 5|6 on 6|7 on 7|8 on 8|9 on 9|10 on 10");
dsp("sudden death|unlimited");
dsp("race to 2|race to 3|race to 4|race to 5|race to 6|race to 7|race to 8");
dsp("mercy at 2 points|mercy at 3 points|mercy at 4 points|mercy at 5 points|mercy at 6 points|mercy at 7 points|mercy at 8 points");
dsp("2 minutes gametime|3 minutes gametime|4 minutes gametime|5 minutes gametime|6 minutes gametime|7 minutes gametime|8 minutes gametime|9 minutes gametime");
dsp("10 minutes gametime|12 minutes gametime|15 minutes gametime|20 minutes gametime|30 minutes gametime|60 minutes gametime");
dsp("M500 format X-ball|M800 format X-ball|Professional X-ball|training mode");
dsp("1 minute breaktime|2 minutes breaktime|3 minutes breaktime|4 minutes breaktime|5 minutes breaktime|6 minutes breaktime");
dsp("no overtime|2 minutes overtime|3 minutes overtime|5 minutes overtime");
// block double keypresses and sound overlays
var block = 0;
// delay for speaches and such if > 0, switch teams to play if === 0, nothing to do if < 0;
var clock_delay = -1;
// bool - for each game
var overtime;
// win condition
var race_to = 0; // points
var mercy_at = 0; // points
// selected team index in the pits
// a vs b and c vs d
function is_dualpit(group) {
if (group)
if (typeof group.b === "number" && typeof group.c === "number") return true;
return false;
}
function init_xo(gg) {
console.log("init_xo_game",gg);
// argument is xo.groups[xo.game_group] object or a custom version of it
// outer - a match is team vs team going for points
xo.match_live = false;
// inner - if the game is live, on live field, players free to fire
xo.game_live = false;
// the status string gets displayed
xo.status = 'prepare for the game';
// the group index currently in the pit
xo.gr = 0;
// one or two objects describing the current pit situation
xo.grs = [];
var d = is_dualpit(gg);
xo.grs[0] = {};
if (d) xo.grs[1] = {};
// left and right
xo.grs[0].l = {};
xo.grs[0].r = {};
if (d) xo.grs[1].l = {};
if (d) xo.grs[1].r = {};
xo.grs[0].l.team = index[gg.a].team;
xo.grs[0].r.team = index[gg.b].team;
if (d) xo.grs[1].l.team = index[gg.c].team;
if (d) xo.grs[1].r.team = index[gg.d].team;
xo.grs[0].l.points = 0;
xo.grs[0].r.points = 0;
if (d) xo.grs[1].l.points = 0;
if (d) xo.grs[1].r.points = 0;
xo.grs[0].l.timeouts = settings.format.timeouts;
xo.grs[0].r.timeouts = settings.format.timeouts;
if (d) xo.grs[1].l.timeouts = settings.format.timeouts;
if (d) xo.grs[1].r.timeouts = settings.format.timeouts;
// each group has its own gametime
xo.grs[0].g = settings.gametime;
if (d) xo.grs[1].g = settings.gametime;
xo.grs[0].b = settings.breaktime;
if (d) xo.grs[1].b = settings.breaktime;
xo.grs[0].overtime = false;
if (d) xo.grs[1].overtime = false;
xo.grs[0].overtime1v1 = false;
if (d) xo.grs[1].overtime1v1 = false;
xo.grs[0].playing = true;
if (d) xo.grs[1].playing = true;
xo.delay = 0;
// by field
xo.left_team_time=false;
xo.right_team_time=false;
};
function setBreakTime() {
if (xo.grs[xo.gr].b < settings.breaktime)
xo.grs[xo.gr].b = settings.breaktime;
};
function select_format() {
settings.gametime = 60 * Number(settings.format.gametime.substr(0, 2));
settings.breaktime = 60 * Number(settings.format.breaktime.substr(0, 2));
settings.overtime = 60 * Number(settings.format.overtime.substr(0, 2));
if (settings.format.condition.substring(0, 7) === "race to") {
race_to = Number(settings.format.condition.substring(8, 10));
settings.format.condition = "race to " + race_to;
} else race_to = 0;
if (settings.format.condition.substring(0, 8) === "mercy at") {
mercy_at = Number(settings.format.condition.substring(9, 10));
settings.format.condition = "mercy at " + mercy_at + " points";
} else mercy_at = 0;
if (settings.format.condition === 'Sudden death') race_to = 1;
//xo.dual_pits = (settings.format.pitsystem === "dual");
xo.training_mode = (settings.format.rules === 'training mode');
if (settings.breaktime === 0) settings.breaktime = 15;
};
// OBSOLETE
// authentication-related
var basic = auth.basic({
realm: "Xoclock admin."
}, function(username, password, callback) {
// Custom authentication method.
var hash = crypto.createHash(hash_typ).update(password).digest(hash_dig);
if (hash === settings.admin_hash) {
//console.log("authenticated as admin");
callback(true);
return;
}
for (var i = 0; i < index.length; i++) {
if (hash === index[i].hash && username === index[i].team) {
callback(true);
return;
}
if (password === index[i].pass && username === index[i].team) {
callback(true);
return;
}
}
console.log("AUTH failed for " + username + " '" + hash + "' :(");
callback(false);
return;
});
// OBSOLETE
var keys_basic = auth.basic({
realm: "Xoclock keys."
}, function(username, password, callback) {
// Custom authentication method.
// var hash = crypto.createHash(hash_typ).update(password).digest(hash_dig);
if (password === settings.keys_pass) {
//console.log("authenticated as admin");
callback(true);
return;
}
console.log("KEYS failed");
callback(false);
return;
});
// HTTPS for admins and team captains
var xoclockapp = express();
// update. We dont use basic auth, but rather a passpin based auth.
// xoclockapp.use(auth.connect(basic));
xoclockapp.use(express.static('public'));
var httpsServer = https.createServer(options, xoclockapp);
var io = require('socket.io')(httpsServer);
// readonly-io HTTP for readers, screens, etc
var readonlyapp = express();
readonlyapp.use(express.static('public'));
var httpServer = http.createServer(readonlyapp);
var rio = require('socket.io')(httpServer);
// keys for buzzers, and keypresses
var keys = express();
keys.use(auth.connect(keys_basic));
var keysServer = https.createServer(options, keys);
var proxy = require("socket.io-client")('https://'+settings.proxy);
// autocorrect .)
function ac(string) {
return string.charAt(0).toUpperCase() + string.slice(1) + '.';
}
var speech_process;
function speak(string) {
console.log("speak string:", string);
//speech_process.close();
var parts = string.split(",");
var args = [];
for (i in parts) {
var file = filename(parts[i]);
if (speeches[file] !== undefined) args.push("audio/" + file);
else if (speechex[file] !== undefined) args.push("teams/" + file);
else args.push("audio/" + file);
}
if (args.length < 1) return console.log(parts, args, "Nothing to say?");
console.log("speak args", args);
speech_process = spawn('play', args);
speech_process.stdout.on('data', (data) => {
console.log(`speech_process stdout: ${data}`);
});
speech_process.stderr.on('data', (data) => {
console.log(`speech_process stderr: ${data}`);
});
speech_process.on('close', (code) => {
console.log(`speech_process child process exited with code ${code}`);
});
};
// speak
function s(string) {
var s = ac(string);
console.log('SPEAK', s);
io.emit('s', s);
rio.emit('s',s);
speak(string);
};
// speak delayed
function sd(string) {
var s = ac(string);
console.log('SPEAK-DELAYED', s);
io.emit('sd', s);
rio.emit('sd', s);
setTimeout(function(){
speak(string);
}, 1200);
};
function beep(beep) {
console.log(beep);
io.emit('beep',beep);
rio.emit('beep',beep);
var child = exec(aplay + ' public/beep/' + beep + '.wav',
function(error, stdout, stderr) {
if (error !== null) {
console.log("exec error: " + error);
}
});
};
function music_on() {
if (settings.volume.music > 0)
var child = exec('/bin/bash music_on.sh ' + (50 + settings.volume.music * 2),
function(error, stdout, stderr) {
if (error !== null) {
console.log("exec error: " + error);
}
});
};
function music_off() {
var child = exec('/bin/bash music_off.sh',
function(error, stdout, stderr) {
if (error !== null) {
console.log("exec error: " + error);
}
});
};
function music_op(arg) {
var child = exec('/bin/bash music_op.sh '+arg,
function(error, stdout, stderr) {
if (error !== null) {
console.log("exec error: " + error);
}
});
};
function timeFormat(t) {
var str = '';
var m = Math.floor(t / 60);
var s = t - m * 60;
if (m < 10) str += '0' + m;
else str = String(m);
str += ':';
if (s < 10) str += '0' + s;
else str += '' + s;
return str;
};
xo.status = 'Xoclock started.';
// broadcast xoclock object
function screen() {
io.emit('xo', xo);
rio.emit('xo', xo);
save();
proxy.emit('xo', xo);
};
function setDelay() {
clock_delay = settings.clock_delay;
//if (xo.training_mode) clock_delay = 2;
};
function game_log(str) {
console.log(str + " GAME " + xo.grs[xo.gr].l.team + " VS " + xo.grs[xo.gr].r.team + " (" + xo.grs[xo.gr].l.points + "-" + xo.grs[xo.gr].r.points + ") gametime: " + xo.grs[xo.gr].g + "sec Status: " + xo.status);
};
dsp("scored a point|threw the towel|state of the game");
function announce_point(team, towel) {
var l = xo.grs[xo.gr].l;
var r = xo.grs[xo.gr].r;
var by = ", scored a point";
if (towel) by = ", threw the towel";
if (l.points < 10 && r.points < 10) sd(team + by + ", " + l.points + ":" + r.points);
else sd(team + by);
};
dsp("Point|Game over|Barrel-socks on|against");
function announce_score(point) {
var l = xo.grs[xo.gr].l;
var r = xo.grs[xo.gr].r;
var pre = "Game over, ";
if (point) pre = "Point, game over, ";
var post = "";
if (!xo.grs[0].playing && !xo.grs[0].playing) post = ', barrel-socks on';
if (l.points < 10 && r.points < 10) sd(pre + l.team + ", against, " + r.team + ", " + l.points + ":" + r.points + post);
else sd(pre + l.team + ", against, " + r.team + ", " + l.points + ", " + r.points + post);
};
dsp("overtime|select a player to compete in a one on one");
function checkWin(point, team, towel) {
// on point, on towel, on time-0
// in current group. Arguments only for announcement
// local variable, is this group game still on?
var on = true;
// check points according to format
if (race_to > 0 && (xo.grs[xo.gr].l.points >= race_to || xo.grs[xo.gr].r.points >= race_to)) on = false;
if (mercy_at > 0 && Math.abs(xo.grs[xo.gr].l.points - xo.grs[xo.gr].r.points) >= mercy_at) on = false;
if (xo.grs[xo.gr].overtime && xo.grs[xo.gr].l.points !== xo.grs[xo.gr].r.points) on = false;
if (on && xo.grs[xo.gr].g < 6) {
// gametime very low
xo.grs[xo.gr].g = 0;
// on equal points
if (xo.grs[xo.gr].l.points == xo.grs[xo.gr].r.points) {
xo.status += ' Stalemate.';
if (xo.grs[xo.gr].overtime) {
// set up the one on one to be played
xo.status += ' One-on-One.';
game_log("Stalemate. One-on-One.");
if (xo.grs[xo.gr].overtime1v1) xo.grs[xo.gr].b = 70;
else xo.grs[xo.gr].b = 130;
xo.grs[xo.gr].g = 120;
sd("select a player to compete in a one on one" );
xo.grs[xo.gr].overtime1v1=true;
} else {
if (settings.overtime > 0) {
// set overtime
xo.grs[xo.gr].overtime = true;
xo.grs[xo.gr].g = settings.overtime;
xo.status += ' Overtime! ';
game_log("OVERTIME");
sd('overtime');
} else {
on = false
};
}
// game over by gametime, with a winner
} else on = false;
}
if (!on && xo.grs[xo.gr].playing) {
// the game ended just now.
if (xo.grs[xo.gr].l.points > xo.grs[xo.gr].r.points) xo.status += ' ' + xo.grs[xo.gr].l.team + ' wins.';
if (xo.grs[xo.gr].l.points < xo.grs[xo.gr].r.points) xo.status += ' ' + xo.grs[xo.gr].r.team + ' wins.';
announce_score(point);
xo.status += " GAME OVER";
screen();
game_log("GAME-OVER");
//xo.grs[xo.gr].b = 0;
//xo.grs[xo.gr].g = 0;
}
// group is playing
if (on && point) announce_point(team, towel);
xo.grs[xo.gr].playing = on;
};
function checkGameOver() {
if (xo.grs.length > 1)
if (!xo.grs[0].playing && !xo.grs[1].playing) {
xo.match_live = false;
xo.status = "BOTH GAMES OVER";
screen();
}
if (xo.grs.length === 1)
if (!xo.grs[0].playing) {
xo.match_live = false;
xo.status = "GAME OVER!";
screen();
}
}
function performSwitch() {
clock_delay = -1;
// dont swich if we are after the overtime in a 1v1
// if (xo.grs[xo.gr].overtime1v1) return;
if (xo.grs.length > 1) {
// dual pits - set group
if (xo.grs[0].playing && xo.grs[1].playing) xo.gr = Math.abs(xo.gr - 1);
if (xo.grs[0].playing && !xo.grs[1].playing) xo.gr = 0;
if (!xo.grs[0].playing && xo.grs[1].playing) xo.gr = 1;
}
if (xo.grs[xo.gr].b < settings.entrytime) xo.grs[xo.gr].b = settings.entrytime;
if (xo.training_mode) xo.grs[xo.gr].b = 20;
xo.status = "enter the field."
screen();
};
/// START THE PROGRAM
select_format();
if (!xo.grs) init_xo(xo.groups[xo.game_group]);
var g = 0;
var b = 0;
dsp("attention 60 seconds rule applies");
dsp("10 seconds|30 seconds|1 minute|2 minutes");
function main(){
block--;
// clock delay has highest priority
if (clock_delay > 0) {
clock_delay--;
io.emit('clock_delay', clock_delay);
rio.emit('clock_delay', clock_delay);
proxy.emit('clock_delay', clock_delay);
return;
}
io.emit('block', block);
rio.emit('block', block);
checkGameOver()
// a match is played, clocks are running
if (xo.match_live) {
if (clock_delay === 0) performSwitch();
if (xo.grs.length > 1) {
xo.grs[Math.abs(xo.gr - 1)].b--;
}
// the game is live, field is live
if (xo.game_live) {
// clock calc
if (xo.grs[xo.gr].g > 0) xo.grs[xo.gr].g--;
g = xo.grs[xo.gr].g;
if (g === 60 && !xo.grs[xo.gr].overtime1v1) s('attention 60 seconds rule applies');
if (g === 0) {
// gametime is up.
beep("stop_sound");
xo.game_live = false;
xo.status = "Time is up. ";
setDelay();
setBreakTime();
checkWin(false, null, null);
music_on();
screen();
return;
}
io.emit('g', g);
rio.emit('g', g);
proxy.emit('g', g);
}
// we are in a break
if (!xo.game_live) {
// clock calc
if (xo.grs[xo.gr].b > 0) xo.grs[xo.gr].b--;
b = xo.grs[xo.gr].b;
if (settings.quantize)
if (b === 15) {