forked from po-devs/po-server-goodies
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tours.js
executable file
·5320 lines (5217 loc) · 253 KB
/
tours.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
/*
Code for tours.js
Coding done by Shadowfist
Files used: tourscores.txt, eventscores.txt, tourscores_tier.txt, tourwinverbs.txt, tourconfig.txt, eventtours.txt,
tourdetails.txt, eventwinners.txt, eventplayers.txt, tourmonthscore_month.txt, tourmutes.txt,
touradmins.json, tastats.json, tourseeds.json, tourhistory.json
*/
if (typeof tourschan !== "string") {
tourschan = sys.channelId("Tournaments")
}
if (typeof tourserrchan !== "string") {
tourserrchan = sys.channelId("Indigo Plateau")
}
if (typeof tours !== "object") {
sendChanAll("Creating new tournament object", tourschan)
tours = {"queue": [], "globaltime": -1, "key": 0, "keys": [], "tour": {}, "history": [], "touradmins": {}, "subscriptions": {}, "activetas": [], "activehistory": [], "tourmutes": {}, "metrics": {}, "eventticks": -1}
}
var utilities = require('utilities.js');
var bfactory = require('battlefactory.js');
var border = "»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»»:";
var htmlborder = "<font color=#3DAA68><b>"+border+"</b></font>";
var flashtag = "<!--f-->"; // This is used to check for flashes in the html code
// Event tournaments highlighted in red
var redborder = "<font color=#FF0000><b>"+border+"</b></font>";
var redhtmlborder = "<font color=#FF0000><timestamp/> <b>"+border+"</b></font>";
var tourcommands = ["join: joins a tournament",
"unjoin: unjoins a normal tournament during signups only, leaves an event tour",
"queue: lists upcoming tournaments",
"viewround: views current round",
"iom: views list of ongoing matches",
"ipm: views list of matches yet to start",
"history: views recently played tiers",
"touradmins: lists all users that can start tournaments",
"leaderboard [tier]: shows tournament rankings, tier is optional",
"eventleaderboard: shows the event leaderboard",
"monthlyleaderboard [month] [year]: shows tour rankings for the current month, or the current month and year if specified",
"tourinfo [name]: gives information on a person's recent tour wins",
"viewstats: views tournament stats",
"viewseeds [tier]: views seed rankings for that tier",
"activeta: lists active tournament admins",
"rules: lists the tournament rules",
"touralerts [on/off]: Turn on/off your tour alerts (Shows list of Tour Alerts if on/off isn't specified)",
"addtouralert [tier] : Adds a tour alert for the specified tier",
"removetouralert [tier] : Removes a tour alert for the specified tier"]
var tourmodcommands = ["*** Parameter Information ***",
"Parameters can be used by putting 'gen=x'; 'mode=singles/doubles/triples'; 'type=single/double'.",
"For example '/tour CC 1v1:gen=RBY mode=doubles type=double' starts a RBY CC 1v1 double elimination tournament.",
"tour [tier]:[parameters]: starts a tier of that tournament.",
"tourmute [player]:[reason]:[time]: tourmutes a problematic player.",
"tourunmute [player]: untourmutes a player.",
"tourmutes: list tour mutes.",
"changecount [number]: changed the number of players for an event tournament",
"endtour [tour]: ends the tour of that tier",
"sub [newname]:[oldname]: subs newname for oldname",
"dq [player]: disqualifies a player",
"remove [tour/number]: removes a tournament from the queue. If a number is put in, it will remove the tour in the queue with the corresponding number. If a tier is put in, it will remove the tournament of that tier (starting from the back)",
"cancelbattle [name]: cancels that player's current battle",
"config: shows config settings",
"start: starts next tournament in the queue immediately (use sparingly)",
"viewstaffstats [name]: views tournament staff stats for a user",
"configset [var]:[value]: changes config settings",
"passta [name]: passes your tour admin to a new name"]
var touradmincommands = ["tourstart [tier]:[parameters]: starts a tier of that tournament immediately, provided one is not in signups.",
"shift [tier]:[parameters]: places a tournament in the front of the queue",
"tadmin[s] [name]: makes someone a megauser - s makes it only show in staff chan",
"tdeadmin[s] [name]: fires someone from being tournament authority - s makes it only show in staff chan",
// "forcestart: ends signups immediately and starts the first round",
"push [player]: pushes a player into a tournament in signups (DON'T USE UNLESS ASKED)",
"tahistory [days]: views the activity of tour admins (days is optional, if excluded it will get the last 7 days if possible)",
"updatewinmessages: updates win messages from the web",
"stopautostart: if there are no tournaments running, this will stop new ones from being automatically started by the server until another one is started manually."]
var tourownercommands = ["tsadmin[s] [name]: makes someone a tournament admin - s makes it only show in staff chan",
"clearrankings: clears the tour rankings (owner only)",
"evalvars: checks the current variable list for tours",
"resettours: resets the entire tournament system in the event of a critical failure",
"fullleaderboard [tier]: gives the full leaderboard",
"getrankings [month] [year]: exports monthly rankings (deletes old rankings as well)",
"loadevents: load event tours"]
var tourrules = ["*** TOURNAMENT GUIDELINES ***",
"Breaking the following rules may result in punishment:",
"#1: Team revealing or scouting in tiers other than CC, Battle Factory or Metronome will result in disqualification.",
"- Scouting is watching the battle of someone else in the tournament to gain information.",
"- Team revealing is revealing any information about other entrants' teams.",
"- Players are always permitted to watch the final match of any tournament.",
"#2: Have a team and be ready when you join, otherwise you can be disqualified",
"#3: Tierspamming, repeatedly asking for tournaments in the chat, is not allowed.",
"#4: Do not abuse the tournament commands.",
"#5: Do not leave or forfeit in a tournament you are in just so you can join another.",
"#6: Do not timestall (i.e. deliberately wait until timeout).",
"#7: Inactive/Idle players will automatically be disqualified.",
"- Post a message and make sure you are not idle, otherwise you risk being disqualified.",
"#8: Ask someone on the /activeta list if you need help or have problems.",
"#9: Event tournaments (marked by red borders)",
"- Be aware that these are all double elimination. Breaking or attempting to break the above rules will result in immediate disqualification.",
"#10: Respecting other players, sportsmanship and integrity:",
"- Avoid complaining about hax, luck or other such things as much as possible.",
"- Avoid making inflammatory remarks/taunts towards other users - treat other users the way you would like to be treated.",
"- Any deliberate attempt to undermine the integrity of tournaments will result in a permanent ban from tournaments.",
"#11: Do not attempt to circumvent the rules",
"- Attempting to circumvent the rules through trickery, proxy or other such methods will be punished."]
function sendBotMessage(user, message, chan, html) {
if (user === undefined) {
return;
}
if (html) {
if (chan === "all") {
sys.sendHtmlMessage(user, "<font color="+tourconfig.tourbotcolour+"><timestamp/><b>"+tourconfig.tourbot+"</b></font>"+message)
}
else {
sys.sendHtmlMessage(user, "<font color="+tourconfig.tourbotcolour+"><timestamp/><b>"+tourconfig.tourbot+"</b></font>"+message,chan)
}
}
else {
if (chan === "all") {
sys.sendHtmlMessage(user, "<font color="+tourconfig.tourbotcolour+"><timestamp/><b>"+tourconfig.tourbot+"</b></font>"+html_escape(message))
}
else {
sys.sendHtmlMessage(user, "<font color="+tourconfig.tourbotcolour+"><timestamp/><b>"+tourconfig.tourbot+"</b></font>"+html_escape(message),chan)
}
}
}
// Functions to send bot messages to channels
// "all" sends to every channel, "~mt" sends to main channel and tours, "~st" sends to staff channels and tours.
function sendBotAll(message, chan, html) {
var staffchan = sys.channelId("Indigo Plateau");
var tachan = sys.channelId("Victory Road");
if (html) {
if (chan === "all") {
sendChanHtmlAll("<font color="+tourconfig.tourbotcolour+"><timestamp/><b>"+tourconfig.tourbot+"</b></font>"+message,-1)
}
else if (chan === "~mt") {
sendChanHtmlAll("<font color="+tourconfig.tourbotcolour+"><timestamp/><b>"+tourconfig.tourbot+"</b></font>"+message,tourschan)
sendChanHtmlAll("<font color="+tourconfig.tourbotcolour+"><timestamp/><b>"+tourconfig.tourbot+"</b></font>"+message,0)
}
else if (chan === "~st") {
sendChanHtmlAll("<font color="+tourconfig.tourbotcolour+"><timestamp/><b>"+tourconfig.tourbot+"</b></font>"+message,tourschan)
sendChanHtmlAll("<font color="+tourconfig.tourbotcolour+"><timestamp/><b>"+tourconfig.tourbot+"</b></font>"+message,staffchan)
sendChanHtmlAll("<font color="+tourconfig.tourbotcolour+"><timestamp/><b>"+tourconfig.tourbot+"</b></font>"+message,tachan)
}
else {
sendChanHtmlAll("<font color="+tourconfig.tourbotcolour+"><timestamp/><b>"+tourconfig.tourbot+"</b></font>"+message,chan)
}
}
else {
if (chan === "all") {
sendChanHtmlAll("<font color="+tourconfig.tourbotcolour+"><timestamp/><b>"+tourconfig.tourbot+"</b></font>"+html_escape(message),-1)
}
else if (chan === "~mt") {
sendChanHtmlAll("<font color="+tourconfig.tourbotcolour+"><timestamp/><b>"+tourconfig.tourbot+"</b></font>"+html_escape(message),tourschan)
sendChanHtmlAll("<font color="+tourconfig.tourbotcolour+"><timestamp/><b>"+tourconfig.tourbot+"</b></font>"+html_escape(message),0)
}
else if (chan === "~st") {
sendChanHtmlAll("<font color="+tourconfig.tourbotcolour+"><timestamp/><b>"+tourconfig.tourbot+"</b></font>"+html_escape(message),tourschan)
sendChanHtmlAll("<font color="+tourconfig.tourbotcolour+"><timestamp/><b>"+tourconfig.tourbot+"</b></font>"+html_escape(message),staffchan)
sendChanHtmlAll("<font color="+tourconfig.tourbotcolour+"><timestamp/><b>"+tourconfig.tourbot+"</b></font>"+html_escape(message),tachan)
}
else {
sendChanHtmlAll("<font color="+tourconfig.tourbotcolour+"><timestamp/><b>"+tourconfig.tourbot+"</b></font>"+html_escape(message),chan)
}
}
}
// Bot forwarding, for data sending
function sendBotData(message, user, html) {
if (!sys.isInChannel(user, tourschan)) {
return;
}
if (message === "") {
return;
}
if (html) {
sys.sendHtmlMessage(user, message, tourschan);
}
else {
sys.sendMessage(user, "TOURSBOT: "+message, tourschan);
}
}
// for sending to the bot
function getReadableList(type, parameter) {
try {
var name = "";
if (type == "leaderboard") {
if (parameter == "") {
var rankdata = sys.getFileContent("tourscores.txt")
name = "General Leaderboard";
}
else if (parameter == "eventscores") {
var rankdata = sys.getFileContent("eventscores.txt")
name = "Event Leaderboard";
}
else {
var tourtier = find_tier(parameter)
if (tourtier === null) {
throw ("Not a valid tier")
}
var rankdata = sys.getFileContent("tourscores_"+tourtier.replace(/ /g,"_").replace(/\//g,"-slash-")+".txt")
name = tourtier+" Leaderboard";
}
if (rankdata === undefined) {
throw ("No data")
}
var rankings = rankdata.split("\n")
var list = [];
for (var p in rankings) {
if (rankings[p] == "") continue;
var rankingdata = rankings[p].split(":::",2)
if (rankingdata[1] < 1) continue;
list.push([rankingdata[0], rankingdata[1]]);
}
list.sort(function(a,b) { return b[1] - a[1] ; });
}
else {
return "";
}
var width=3;
var max_message_length = 30000;
// generate HTML
var table_header = '<table border="1" cellpadding="5" cellspacing="0"><tr><td colspan="' + width + '"><center><strong>' + utilities.html_escape(name) + '</strong></center></td></tr><tr><th>Ranking</th><th>Name</th><th>Points</th></tr>';
var table_footer = '</table>';
var table = table_header;
var line;
var send_rows = 0;
var rankkey = [0, 0] // rank, points
var tmp = list;
while(tmp.length > 0) {
if (rankkey[1] === parseInt((tmp[0])[1])) {
line = '<tr><td>#'+rankkey[0]+'</td><td>'+tmp[0].join('</td><td>')+'</td></tr>';
}
else {
line = '<tr><td>#'+(send_rows+1)+'</td><td>'+tmp[0].join('</td><td>')+'</td></tr>';
rankkey = [send_rows+1, parseInt((tmp[0])[1])];
}
tmp.splice(0,1);
if (table.length + line.length + table_footer.length > max_message_length) {
break;
}
table += line;
++send_rows;
}
table += table_footer;
if (send_rows > 0) {
return table;
}
else {
return "";
}
}
catch (e) {
return "ERROR: "+e;
}
}
// Debug Messages
function sendDebugMessage(message, chan) {
if (chan === tourschan && typeof tourconfig.debug == "string" && sys.existChannel(sys.channel(tourserrchan))) {
if (sys.id(tourconfig.debug) !== undefined && sys.isInChannel(sys.id(tourconfig.debug), tourserrchan))
sendBotMessage(sys.id(tourconfig.debug),message,tourserrchan,false)
}
}
// Tour Admin Activity
function addTourActivity(src) {
if (tours.activetas.indexOf(sys.name(src).toLowerCase()) == -1) {
tours.activetas.push(sys.name(src).toLowerCase());
}
}
// Will escape "&", ">", and "<" symbols for HTML output.
html_escape = utilities.html_escape;
// Channel function
getChan = utilities.get_or_create_channel;
function cmp(x1, x2) {
if (typeof x1 !== typeof x2) {
return false;
}
else if (typeof x1 === "string") {
if (x1.toLowerCase() === x2.toLowerCase()) {
return true;
}
}
else if (x1 === x2) {
return true;
}
else return false;
}
function getFullTourName(key) {
var mode = tours.tour[key].parameters.mode;
var type = tours.tour[key].tourtype;
if (tours.tour[key].parameters.gen != "default") {
return getSubgen(tours.tour[key].parameters.gen,true) + " " + type + (mode != modeOfTier(type) ? " ["+mode+"]" : "");
}
else if (mode != modeOfTier(type)) {
return type + " ["+mode+"]";
}
else return tours.tour[key].tourtype;
}
// Finds a tier
find_tier = utilities.find_tier;
function modeOfTier(tier) {
if (tier.indexOf("Doubles") != -1 || ["JAA", "VGC 2009", "VGC 2010", "VGC 2011", "VGC 2012"].indexOf(tier) != -1) {
return "Doubles";
}
else if (tier.indexOf("Triples") != -1) {
return "Triples";
}
return "Singles";
}
/* Gets subgen. Name is data being converted, getLongName is a boolean value.
If getLongName is true it will convert to the readable format, otherwise it will return the short format
Returns false if not found */
function getSubgen(name, getLongName) {
var subgens = {
"Red/Blue": "1-0",
"RB": "1-0",
"Yellow": "1-1",
"RBY": "1-1",
"RBY Stadium": "1-2",
"Stadium": "1-2",
"RBY Tradebacks": "1-3",
"Gold/Silver": "2-0",
"GS": "2-0",
"Crystal": "2-1",
"GSC": "2-1",
"GSC Stadium": "2-2",
"Stadium 2": "2-2",
"Stadium2": "2-2",
"Ruby/Sapphire": "3-0",
"RS": "3-0",
"Colosseum": "3-1",
"FireRed/LeafGreen": "3-2",
"FRLG": "3-2",
"RSE": "3-3",
"Emerald": "3-3",
"XD": "3-4",
"Diamond/Pearl": "4-0",
"DP": "4-0",
"Platinum": "4-1",
"DPPt": "4-1",
"HeartGold/SoulSilver": "4-2",
"HGSS": "4-2",
"Black/White": "5-0",
"BW": "5-0",
"Black/White 2": "5-1",
"BW2": "5-1",
"1": "1-3",
"2": "2-2",
"3": "3-4",
"4": "4-2",
"5": "5-1"
}
if (getLongName) {
for (var x in subgens) {
if (cmp(name,subgens[x])) {
return x;
}
}
}
else {
for (var y in subgens) {
if (cmp(name,y)) {
return subgens[y];
}
}
}
return false;
}
// handles time and outputs in d/h/m/s format
// eg 3d 5h 16m 22s
function converttoseconds(string) {
var tmp = string.split(" ")
var totaltime = 0
try {
for (var n in tmp) {
var thestring = tmp[n]
var lastchar = thestring.charAt(thestring.length - 1).toLowerCase()
var timestring = parseInt(thestring.substr(0, thestring.length - 1))
if (isNaN(timestring)) {
continue;
}
else if (lastchar == "d") {
totaltime += 24*60*60*timestring;
}
else if (lastchar == "h") {
totaltime += 60*60*timestring;
}
else if (lastchar == "m") {
totaltime += 60*timestring;
}
else if (lastchar == "s") {
totaltime += timestring;
}
else {
continue;
}
}
}
catch (err) {
return "Not a number";
}
return totaltime;
}
// handles time and outputs in d/h/m/s format
function time_handle(time) { //time in seconds
var day = 60*60*24;
var hour = 60*60;
var minute = 60;
if (time <= 0) {
return "No time remaining."
}
var timedays = parseInt(time/day);
var timehours = (parseInt(time/hour))%24;
var timemins = (parseInt(time/minute))%60
var timesecs = (parseInt(time))%60
var output = "";
if (timedays >= 1) {
if (timedays == 1) {
output = timedays + " day";
}
else {
output = timedays + " days";
}
if (timehours >=1 || timemins >=1 || timesecs >=1) {
output = output + ", ";
}
}
if (timehours >= 1) {
if (timehours == 1) {
output = output + timehours + " hour";
}
else {
output = output + timehours + " hours";
}
if (timemins >=1 || timesecs >=1) {
output = output + ", ";
}
}
if (timemins >= 1) {
if (timemins == 1) {
output = output + timemins + " minute";
}
else {
output = output + timemins + " minutes";
}
if (timesecs >=1) {
output = output + ", ";
}
}
if (timesecs >= 1) {
if (timesecs == 1) {
output = output + timesecs + " second";
}
else {
output = output + timesecs + " seconds";
}
}
return output;
}
function parseTimer(time) {
if (isNaN(time) || time < 0) {
return "0:00";
}
var minutes = Math.floor(time/60);
var seconds = time%60;
if (seconds >= 10) {
return minutes+":"+seconds;
}
else {
return minutes+":0"+seconds;
}
}
// Tournaments
// 1v1 tiers have shorter notification times.
function is1v1Tour(key) {
if ((tours.tour[key].tourtype).indexOf("1v1") != -1) {
return true;
}
else return false;
}
// This function will get a user's current tournament points overall
function getTourWinMessages() {
var content = sys.getFileContent("tourwinverbs.txt")
tourwinmessages = content.split("\n")
}
function awardSeedPoints(playername, tier, points) {
try {
// don't award any points to placeholders, or 0 points
if (points <= 0) {
return;
}
if (playername == "~Bye~" || playername == "~DQ~" || isSub(playername)) {
return;
}
if (tourseeds.hasOwnProperty(tier)) {
var tierinfo = tourseeds[tier];
if (tierinfo.hasOwnProperty(playername)) {
tourseeds[tier][playername].points += points;
tourseeds[tier][playername].lastwin = parseInt(sys.time());
}
else {
tourseeds[tier][playername] = {'points': points, 'lastwin': parseInt(sys.time())};
}
}
else {
tourseeds[tier] = {};
tourseeds[tier][playername] = {'points': points, 'lastwin': parseInt(sys.time())};
}
}
catch (err) {
sendChanAll("Error in seed calculation, "+err, tourserrchan)
}
}
function awardEventPoints(playername, points, datestring) {
if (points <= 0) {
return;
}
if (playername == "~Bye~" || playername == "~DQ~" || isSub(playername)) {
return;
}
if (eventscores.hasOwnProperty(playername)) {
var pscore = eventscores[playername];
if (pscore.hasOwnProperty(datestring)){
if (pscore[datestring] < points) {
eventscores[playername][datestring] = points;
}
}
else {
eventscores[playername][datestring] = points;
}
}
else {
eventscores[playername] = {};
eventscores[playername][datestring] = points;
}
}
function saveEventPoints() {
sys.writeToFile('eventdata.json', JSON.stringify(eventscores));
}
function detEventPoints(size, ranking, tier) {
var rank = Math.floor(ranking);
var mag = Math.floor(Math.log(size)/Math.LN2);
var tiers = [1,2,3,4,6,8,12,16,24];
var scale = tiers.indexOf(rank);
if (scale == -1) {
return 0;
}
if (["Battle Factory"].indexOf(tier) > -1) {
mag -= 1;
}
else if (["Challenge Cup"].indexOf(tier) > -1) {
mag -= 2;
}
if (mag < 2) {
return 0;
}
var scorearr = [0];
switch (mag) {
case 2:
scorearr = [1];
break;
case 3:
scorearr = [2,1];
break;
case 4:
scorearr = [4,2,1];
break;
case 5:
scorearr = [7,3,2,1];
break;
case 6:
scorearr = [11,5,3,2,1];
break;
case 7:
scorearr = [16,8,5,4,2,1];
break;
case 8:
scorearr = [22,11,7,5,3,2,1];
break;
case 9:
scorearr = [29,14,9,7,4,3,2,1];
break;
case 10:
scorearr = [37,18,12,9,6,4,3,2,1];
break;
}
if (scale < scorearr.length) {
return scorearr[scale];
}
else {
return 0;
}
}
function detSeedPoints(size, ranking) {
var rank = Math.floor(Math.log(size)/Math.LN2)-Math.floor(ranking);
if (rank < 0) {
return 0;
}
return Math.pow(2,rank);
}
/* This uses 3 factors
decayrate: % that a user's seed ranking is decayed by
decaytime: number of days before decay is applied since winning/placing
decayglobalrate: % of the total of all seed rankings, that will be deducted from all decaying users
*/
function seedDecay(tier) {
try {
if (!tourseeds.hasOwnProperty(tier)) {
return;
}
var tierdecay = tourseeds[tier];
var totalpoints = 0;
for (var t in tierdecay) {
totalpoints += tourseeds[tier][t].points;
}
var totaldecay = Math.floor(totalpoints*tourconfig.decayglobalrate/100) // this will be an integer
for (var x in tierdecay) {
if (parseInt(sys.time())-tierdecay[x].lastwin > tourconfig.decaytime*24*60*60) {
tourseeds[tier][x].lastwin += tourconfig.decaytime*24*60*60 // add decay time back on
var newpoints = (Math.floor(tierdecay[x].points*(100-tourconfig.decayrate)/10)/10)-totaldecay; // to 1dp
if (newpoints <= 0) {
delete tourseeds[tier][x];
}
else {
tourseeds[tier][x].points = newpoints;
}
}
}
}
catch (err) {
sendChanAll("Error in rank decay, "+err, tourserrchan)
}
}
// Gets the top seed
function topSeed(tier) {
try {
if (!tourseeds.hasOwnProperty(tier)) {
return "~Pokemon Online~";
}
var tierseeds = tourseeds[tier];
var leader = ["~Pokemon Online~", 0];
for (var x in tierseeds) {
if (tierseeds[x].points > leader[1]) {
leader = [x, tierseeds[x].points];
}
}
return toCorrectCase(leader[0]);
}
catch (err) {
sendChanAll("Error in determining top seed, "+err, tourserrchan);
return "~Pokemon Online~";
}
}
// This function gets the tier points
function getExtraPoints(player, tier) {
var data = sys.getFileContent("tourscores_"+tier.replace(/ /g,"_").replace(/\//g,"-slash-")+".txt")
if (data === undefined) {
return 0;
}
var array = data.split("\n")
var score = 0
for (var n in array) {
var scores = array[n].split(":::",2)
if (player.toLowerCase() === scores[0].toLowerCase()) {
score = parseInt(scores[1])
break;
}
}
return score;
}
// This function will get a user's current seed points in a tier
function getExtraTierPoints(player, tier) {
var score = 0;
if (tourseeds.hasOwnProperty(tier)) {
var tierinfo = tourseeds[tier];
if (tierinfo.hasOwnProperty(player)) {
return tierinfo[player].points;
}
}
return score;
}
// saving tour admins list
function saveTourKeys() {
var tal = JSON.stringify(tours.touradmins)
sys.writeToFile("touradmins.json", tal)
return;
}
function saveTourHistory() {
var history = {'tours': tours.history, 'staff': tours.activehistory};
sys.writeToFile("tourhistory.json", JSON.stringify(history));
return;
}
// This function will get a tier's clauses in readable format
function getTourClauses(tier) {
// force Self-KO clause
var tierclauses = sys.getClauses(tier) > 255 ? sys.getClauses(tier) : sys.getClauses(tier)+256
var clauselist = ["Sleep Clause", "Freeze Clause", "Disallow Spects", "Item Clause", "Challenge Cup", "No Timeout", "Species Clause", "Wifi Battle", "Self-KO Clause"]
var neededclauses = [];
for (var c=0;c<9;c++) {
var denom = Math.pow(2,c+1)
var num = Math.pow(2,c)
if (tierclauses%denom >= num) {
neededclauses.push(clauselist[c])
}
}
return neededclauses.join(", ");
}
function clauseCheck(tier, issuedClauses) {
// force Self-KO clause every time
var requiredClauses = sys.getClauses(tier) > 255 ? sys.getClauses(tier) : sys.getClauses(tier)+256
var clauselist = ["Sleep Clause", "Freeze Clause", "Disallow Spects", "Item Clause", "Challenge Cup", "No Timeout", "Species Clause", "Wifi Battle", "Self-KO Clause"]
var clause1 = false;
var clause2 = false;
var missing = [];
var extra = [];
for (var c=0;c<9;c++) {
var denom = Math.pow(2,c+1)
var num = Math.pow(2,c)
// don't check for disallow spects in non CC tiers , it's checked manually
if (c == 2 && ["Challenge Cup", "CC 1v1", "Wifi CC 1v1", "Battle Factory"].indexOf(tier) == -1) {
continue;
}
if (requiredClauses%denom >= num) {
clause1 = true;
}
else {
clause1 = false;
}
if (issuedClauses%denom >= num) {
clause2 = true;
}
else {
clause2 = false;
}
if ((clause1 && clause2) || (!clause1 && !clause2)) {
continue;
}
else if (clause1 && !clause2) {
missing.push(clauselist[c]);
continue;
}
else if (!clause1 && clause2) {
extra.push(clauselist[c]);
continue;
}
else {
sendBotAll("Broken clausecheck...", tourserrchan, false)
break;
}
}
return {"missing": missing, "extra": extra}
}
// Is name x a sub?
function isSub(name) {
try {
if (name === null) {
return false;
}
else if (name.indexOf("~Sub") === 0) {
return true;
}
else return false;
}
catch (err) {
sendChanAll("Error in determining whether "+name+" is a sub, "+err, tourserrchan)
return false;
}
}
/* To track tour brackets in logs. */
function sendLog(message, html) {
try {
var stalked_chans = inStalkedChans([sys.channel(tourschan)]);
if (stalked_chans.length > 0) {
if (html) {
var params = {"event":"afterSendHtmlAll", "msg":message, "channels":stalked_chans, timestamp:get_timestamp()};
append_logs(params);
}
else {
var params = {"event":"afterSendAll", "msg":message, "channels":stalked_chans, timestamp:get_timestamp()};
append_logs(params);
}
}
}
catch (e) {
sendChanAll("Logging from Tournaments failed: "+err, tourserrchan);
return false;
}
}
// Sends a message to all tour auth and players in the current tour
function sendAuthPlayers(message,key) {
for (var x in sys.playersOfChannel(tourschan)) {
var arr = sys.playersOfChannel(tourschan);
if (isTourAdmin(arr[x]) || tours.tour[key].players.indexOf(sys.name(arr[x]).toLowerCase()) != -1) {
var newmessage = message;
var htmlname = html_escape(sys.name(arr[x]));
var regex = flashtag+htmlname+flashtag;
var newregex1 = "<font style='BACKGROUND-COLOR: #FFBB00'>"+htmlname+"</font><ping/>";
var flashregex = new RegExp(flashtag,"g");
newmessage = message.replace(regex,newregex1).replace(flashregex,"");
sendBotMessage(arr[x], newmessage, tourschan, true);
}
}
sendLog(message, true);
}
// Sends a html message to all tour auth and players that participated in the current tour
function sendHtmlAuthPlayers(message,key) {
var arr = sys.playersOfChannel(tourschan)
for (var x in arr) {
if (isTourAdmin(arr[x]) || tours.tour[key].seeds.indexOf(sys.name(arr[x]).toLowerCase()) != -1 || tours.tour[key].players.indexOf(sys.name(arr[x]).toLowerCase()) != -1) {
// send highlighted name in bracket
var htmlname = html_escape(sys.name(arr[x]));
var regex = flashtag+htmlname+flashtag;
var newregex1 = "<font style='BACKGROUND-COLOR: #FFAAFF'>"+htmlname+"</font><ping/>";
var flashregex = new RegExp(flashtag,"g");
var newmessage = message.replace(regex,newregex1).replace(flashregex,"");
sys.sendHtmlMessage(arr[x], newmessage, tourschan);
if (isInSpecificTour(sys.name(arr[x]),key) && sys.away(arr[x])) {
sys.changeAway(arr[x], false);
sendBotMessage(arr[x],"You are no longer idle!",tourschan,false);
}
}
}
sendLog(message, true);
}
// Send a flashing bracket
function sendFlashingBracket(message,key) {
var arr = sys.playersOfChannel(tourschan)
for (var x in arr) {
var newmessage = message;
if (tours.tour[key].players.indexOf(sys.name(arr[x]).toLowerCase()) != -1) {
// send highlighted name in bracket
var htmlname = html_escape(sys.name(arr[x]));
var regex = flashtag+htmlname+flashtag;
var newregex1 = "<font style='BACKGROUND-COLOR: #FFAAFF'>"+htmlname+"</font><ping/>";
var flashregex = new RegExp(flashtag,"g");
newmessage = message.replace(regex,newregex1).replace(flashregex,"");
}
sys.sendHtmlMessage(arr[x], newmessage, tourschan);
if (isInSpecificTour(sys.name(arr[x]),key) && sys.away(arr[x])) {
sys.changeAway(arr[x], false);
sendBotMessage(arr[x],"You are no longer idle!",tourschan,false);
}
}
sendLog(message, true);
}
// Sends a message to all tour auth
function sendAllTourAuth(message) {
for (var x in sys.playersOfChannel(tourschan)) {
var arr = sys.playersOfChannel(tourschan)
if (isTourAdmin(arr[x])) {
sys.sendMessage(arr[x], message, tourschan)
}
}
}
/* Get a config value
Returns default if value doesn't exist*/
function getConfigValue(file, key) {
try {
var defaultvars = {
maxqueue: 4,
maxarray: 1023,
maxrunning: 3,
toursignup: 200,
tourdq: 180,
subtime: 90,
touractivity: 200,
breaktime: 120,
absbreaktime: 600,
remindertime: 30,
channel: "Tournaments",
errchannel: "Developer's Den",
tourbotcolour: "#3DAA68",
minpercent: 5,
minplayers: 3,
decayrate: 10,
decaytime: 2,
decayglobalrate: 2,
version: "2.000",
tourbot: "\u00B1"+Config.tourneybot+": ",
debug: false,
points: true,
winmessages: true
}
var configkeys = sys.getValKeys(file)
if (configkeys.indexOf(key) == -1) {
sendChanAll("No tour config data detected for '"+key+"', getting default value", tourschan)
if (defaultvars.hasOwnProperty(key))
return defaultvars[key];
else
throw "Couldn't find the key!"
}
else {
return sys.getVal(file, key);
}
}
catch (err) {
sendChanAll("Error in getting config value '"+key+"': "+err, tourserrchan)
return null;
}
}
function initTours() {
// config object
tourconfig = {
maxqueue: parseInt(getConfigValue("tourconfig.txt", "maxqueue")),
maxarray: 1023,
maxrunning: parseInt(getConfigValue("tourconfig.txt", "maxrunning")),
toursignup: parseInt(getConfigValue("tourconfig.txt", "toursignup")),
tourdq: parseInt(getConfigValue("tourconfig.txt", "tourdq")),
subtime: parseInt(getConfigValue("tourconfig.txt", "subtime")),
activity: parseInt(getConfigValue("tourconfig.txt", "touractivity")),
tourbreak: parseInt(getConfigValue("tourconfig.txt", "breaktime")),
abstourbreak: parseInt(getConfigValue("tourconfig.txt", "absbreaktime")),
reminder: parseInt(getConfigValue("tourconfig.txt", "remindertime")),
channel: "Tournaments",
errchannel: "Developer's Den",
tourbotcolour: getConfigValue("tourconfig.txt", "tourbotcolour"),
minpercent: parseFloat(getConfigValue("tourconfig.txt", "minpercent")),
minplayers: parseInt(getConfigValue("tourconfig.txt", "minplayers")),
decayrate: parseFloat(getConfigValue("tourconfig.txt", "decayrate")),
decaytime: parseFloat(getConfigValue("tourconfig.txt", "decaytime")),
decayglobalrate: parseFloat(getConfigValue("tourconfig.txt", "decayglobalrate")),
version: "2.000",
tourbot: getConfigValue("tourconfig.txt", "tourbot"),
debug: false,
points: true,
winmessages: getConfigValue("tourconfig.txt", "winmessages") === "off" ? false : true
};
tourschan = utilities.get_or_create_channel(tourconfig.channel);
tourserrchan = utilities.get_or_create_channel(tourconfig.errchannel);
if (typeof tours != "object") {
sendChanAll("Creating new tournament object", tourschan);
tours = {"queue": [], "globaltime": -1, "key": 0, "keys": [], "tour": {}, "history": [], "touradmins": {}, "subscriptions": {}, "activetas": [], "activehistory": [], "tourmutes": {}, "metrics": {}, "eventticks": -1};
}
else {
if (!tours.hasOwnProperty('queue')) tours.queue = [];
if (!tours.hasOwnProperty('globaltime')) tours.globaltime = -1;
if (!tours.hasOwnProperty('key')) tours.key = [];
if (!tours.hasOwnProperty('keys')) tours.keys = [];
if (!tours.hasOwnProperty('tour')) tours.tour = {};
if (!tours.hasOwnProperty('history')) tours.history = [];
if (!tours.hasOwnProperty('touradmins')) tours.touradmins = {};
if (!tours.hasOwnProperty('subscriptions')) tours.subscriptions = {};
if (!tours.hasOwnProperty('activetas')) tours.activetas = [];
if (!tours.hasOwnProperty('activehistory')) tours.activehistory = [];
if (!tours.hasOwnProperty('tourmutes')) tours.tourmutes = {};
if (!tours.hasOwnProperty('metrics')) tours.metrics = {};
if (!tours.hasOwnProperty('eventticks')) tours.eventticks = -1;
}
tours.metrics = {'failedstarts': 0};
try {
getTourWinMessages();
sendChanAll(tourconfig.winmessages ? "Win messages loaded" : "Using default win message", tourschan);
}
catch (e) {
// use a sample set of win messages
tourwinmessages = [];
sendChanAll("No win messages detected, using default win message.", tourschan);
}