This repository was archived by the owner on Jan 9, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdynamicInitiative.js
More file actions
1226 lines (1120 loc) · 42.3 KB
/
dynamicInitiative.js
File metadata and controls
1226 lines (1120 loc) · 42.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
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
var Tracker = Tracker || (function () {
'use strict';
const version = '0.1.0',
ALL_STATUSES = ["red", "blue", "green", "brown", "purple", "pink", "yellow",
"dead", "skull", "sleepy", "half-heart", "half-haze", "interdiction", "snail", "lightning-helix", "spanner",
"chained-heart", "chemical-bolt", "death-zone", "drink-me", "edge-crack", "ninja-mask", "stopwatch",
"fishing-net", "overdrive", "strong", "fist", "padlock", "three-leaves", "fluffy-wing", "pummeled", "tread",
"arrowed", "aura", "back-pain", "black-flag", "bleeding-eye", "bolt-shield", "broken-heart", "cobweb",
"broken-shield", "flying-flag", "radioactive", "trophy", "broken-skull", "frozen-orb", "rolling-bomb",
"white-tower", "grab", "screaming", "grenade", "sentry-gun", "all-for-one", "angel-outfit", "archery-target"
],
STATUS_ALIASES = {
'crippled': "arrowed",
'helpless': "cobweb",
'pinned': "flying-flag",
'prone': "back-pain",
'frenzied': "strong",
'stunned': "pummeled",
'unaware': "half-haze",
'hidden': "ninja-mask",
'aiming': "archery-target",
'braced': "sentry gun",
'defensive': "white-tower",
'guarded': "bolt-shield",
'overwatch': "all-for-one",
'inspired': "trophy",
'hallucinating': "aura",
'haywire': "spanner",
'bloodloss': "half-haze",
'blinded': "bleeding-eye",
'deafened': "lightning-helix",
'fire': "three-leaves",
'engaged': "fist",
'grabbed': "grab",
'feared': "screaming",
'unconscious': "sleepy",
'uselesslimb': "broken-skull",
'criticallywounded': "broken-heart",
'heavilywounded': "half-heart",
'lightlywounded': "chained-heart",
'prone': "tread",
'fullaim': "frozen-orb",
'alloutatk': "overdrive",
'majinitpenalty': "yellow",
'lginitpenalty': "half-haze",
'initpenalty': "pink",
'mininitpenalty': "purple",
'mininitbonus': "green",
'initbonus': "blue",
'lginitbonus': "brown",
'majinitbonus': "red"
},
//TODO: test the alias/status utility fcns
INITIATIVE_MOD = {
'unconscious': -100,
'helpless': -20,
'stunned': -20,
'majinitpenalty': -20,
'feared': -15,
'pinned': -15,
'fire': -15,
'lrginitpenalty': -15,
'grabbed': -10,
'alloutatk': -10,
'initpenalty': -10,
'crippled': -5,
'prone': -5,
'blinded': -5,
'deafened': -5,
'heavilywounded': -5,
'mininitpenalty': -5,
'aiming': 5,
'mininitbonus': 5,
'guarded': 10,
'fullaim': 10,
'initbonus': 10,
'lginitbonus': 15,
'defensive': 20,
'majinitbonus': 20
},
//for use with the complex status handler; sets status aliases to either persistent, rounds, or round
STATUS_TYPES = {
'crippled': "persistent",
'helpless': "persistent",
'pinned': "persistent",
'prone': "persistent",
'frenzied': "persistent",
'stunned': "rounds",
'unaware': "round",
'hidden': "persistent",
'aiming': "round",
'braced': "persistent",
'defensive': "round",
'guarded': "round",
'overwatch': "round",
'inspired': "round",
'hallucinating': "rounds",
'haywire': "rounds",
'bloodloss': "persistent",
'blinded': "rounds",
'deafened': "rounds",
'fire': "rounds",
'engaged': "persistent",
'grabbed': "persistent",
'feared': "round",
'unconscious': "persistent",
'uselesslimb': "rounds",
'criticallywounded': "persistent",
'heavilywounded': "persistent",
'lightlywounded': "persistent",
'prone': "persistent",
'fullaim': "round",
'alloutatk': "round",
'majinitpenalty': "round",
'lginitpenalty': "round",
'initpenalty': "round",
'mininitpenalty': "round",
'mininitbonus': "round",
'initbonus': "round",
'lginitbonus': "round",
'majinitbonus': "round"
},
//TODO: Build the code for the wh40ksheet, wh40krollscripts
CONFIG_PARAMS = [
['announceRounds', "Announce Each Round"],
['announceTurns', "Announce Each Player's Turn"],
['announceExpiration', "Announce Status Expirations"],
['highToLow', "High-to-Low Initiative Order"],
['pooledInit', "Pooled Mook Initiative Rolls"],
['dynamicInit', "Dynamic Initiative"],
['statusTurn', "Status Updated on Turn or Round"],
['wh40ksheet', "using Args WH40k sheet"],
['wh40krollscripts', "using Args WH40k scripts"],
['autoremovedead', "automatically remove dead tokens"],
['complexstatushandler', "handles status markers differently"]
];
let initConfig = function initConfig() {
if (!state.hasOwnProperty('InitiativeTracker')) {
state.InitiativeTracker = {
'highToLow': true,
'announceRounds': true,
'announceTurns': true,
'announceExpiration': true,
'pooledInit': true,
'dynamicInit': true,
'statusTurn': true,
'wh40ksheet': true,
'wh40krollscripts': true,
'autoremovedead': true,
'complexstatushandler': true,
};
}
if (!state.InitiativeTracker.hasOwnProperty('round')) {
sendChat('', "the initiative tracker needs a token:" + state.InitiativeTracker.toString());
state.InitiativeTracker.round = null;
}
if (!state.InitiativeTracker.hasOwnProperty('count')) {
sendChat('', "the initiative tracker needs a token:" + state.InitiativeTracker.toString());
state.InitiativeTracker.count = null;
}
if (!state.InitiativeTracker.hasOwnProperty('token')) {
sendChat('', "the initiative tracker needs a token:" + state.InitiativeTracker.toString());
state.InitiativeTracker.token = {};
}
},
write = function (s, who, style, from) {
if (who) {
who = "/w " + who.split(" ", 1)[0] + " ";
}
sendChat(from, who + s.replace(/</g, "<").replace(/>/g, ">").replace(/\n/g, "<br>"));
},
reset = function () {
state.InitiativeTracker.round = null;
state.InitiativeTracker.count = null;
state.InitiativeTracker.token = {};
},
dataSync = function () {
//Rebuilds the "back end" to match the current tokens and status markers on the map. Does not reset the initiative order AND also doesn't sync the current init of mooks and generics
let oldTurnOrderStr = Campaign().get('turnorder') || "[]";
let turnOrder = JSON.parse(oldTurnOrderStr);
let tokenid, turn, expires, tokenInit, nextInitiative, statusname, alias;
let tokenStatusStr = '';
let tokenStatusArr = [];
let statusArr = [];
let currentPageGraphics = findObjs({
_pageid: Campaign().get("playerpageid"),
_type: "graphic",
_subtype: "token",
});
state.InitiativeTracker.token = {};
_.each(currentPageGraphics, function (selToken) {
if (selToken.get('bar3_value') != '' && (state.InitiativeTracker['autoremovedead'] === false || !selToken.get('statusmarkers').includes('dead'))) {
//get a qualifying token and find a matching entry in the initiative order to get its init
tokenid = selToken.get('id');
nextInitiative = 0;
statusArr = [];
//get token's status markers and build the status array
tokenStatusStr = selToken.get('statusmarkers');
tokenStatusArr = tokenStatusStr.split(',');
if (tokenStatusArr[0] != '' && tokenStatusArr[0] != undefined) {
_.each(tokenStatusArr, function (selStatus) {
statusname = selStatus.split('@')[0];
if (statusname != '' && statusname != undefined) {
if (selStatus.split('@')[1]) expires = selStatus.split('@')[1];
else expires = 999;
alias = _.invert(STATUS_ALIASES)[statusname];
if (!alias) alias = '';
if (INITIATIVE_MOD[alias]) nextInitiative += INITIATIVE_MOD[alias];
else if (INITIATIVE_MOD[statusname]) nextInitiative += INITIATIVE_MOD[statusname];
statusArr.push({
'duration': expires,
'count': state.InitiativeTracker.count,
'name': statusname,
'alias': alias,
'severity': 0,
});
}
});
}
//assign initiative values; uniques get their value from the turn order, generics and mooks get assigned a current init equal to their next-turn init
turn = turnOrder.find(function (o) {
return o.id === tokenid;
});
if (turn != undefined) tokenInit = turnOrder[turn.id];
else tokenInit = nextInitiative;
//fully set the entry for the token
state.InitiativeTracker.token[tokenid] = {
initiative: tokenInit,
nextInitiative: nextInitiative,
name: selToken.get('name'),
statuses: statusArr,
expiredStatuses: []
};
}
});
},
getInitModFromAliasOrStatus = function (name) {
//utility function that takes a status name or status alias and searches the initiative list for both. Returns an init mod of 0 if the name doesn't match a status or alias
let output;
if (INITIATIVE_MOD[name]) {
output = INITIATIVE_MOD[name];
return output;
}
//if we don't get a name match, try looking for a paired status or alias and try again
if (STATUS_ALIASES[name]) name = STATUS_ALIASES[name];
else if (_.invert(STATUS_ALIASES)[name]) name = _.invert(STATUS_ALIASES)[name];
if (INITIATIVE_MOD[name]) output = INITIATIVE_MOD[name];
else output = 0;
return output;
},
getAliasOrName = function (status) {
//utility function that, given a status object, returns the alias (if it has one) or, in the absence of an alias, the status name (if it has one)
let output;
if (status.alias != undefined) output = status.alias;
else if (status.name != undefined) output = status.name;
else output = 'unknown';
return output;
},
stackTokenSync = function (id) {
//utility function that checks for a token object with a given id and builds one if missing
if (!state.InitiativeTracker.token[id]) {
let name = getObj("graphic", id).get('name');
if (!name) name = 'unknown';
state.InitiativeTracker.token[id] = {
initiative: 0,
nextInitiative: 0,
name: name,
statuses: [],
expiredStatuses: []
};
}
},
rebuildTurnOrder = function () {
var charid = '';
var tokenid = '';
var matchingCharacters = {}; //tracks character sheets with the same character name as a token's name
var initBonus = 0;
var roll = 0;
var usedCharArray = []; //tracks the charids that have already been rolled for
var turnorder = [];
var oldstack = [];
var newEntry = {};
var rollArray = {};
var duplicateInit = false;
var page_id = '';
var exists = false;
var stackToken = {};
var adjRollArray = [];
var stackTokenInit = 0;
var characterName;
var currentPageGraphics = findObjs({
_pageid: Campaign().get("playerpageid"),
_type: "graphic",
_subtype: "token",
});
if (currentPageGraphics.length != 0) {
page_id = currentPageGraphics[0].get('pageid');
}
//Set up the Round Start entry if using dynamic initiative
if (state.InitiativeTracker['highToLow'] === true) {
turnorder.push({
id: "-1",
pr: 100,
custom: "Round Start",
_pageid: page_id
});
} else {
turnorder.push({
id: "-1",
pr: -100,
custom: "Round Start",
_pageid: page_id
});
}
_.each(currentPageGraphics, function (graphic) {
tokenid = graphic.get('id');
//only check tokens which have bar3 values and--if autoremove is enabled-- are not dead (are character tokens of some kind)
if (graphic.get('bar3_value') != '' && (state.InitiativeTracker['autoremovedead'] === false || !graphic.get('statusmarkers').includes('dead'))) {
if (state.InitiativeTracker['statusTurn'] === false) {
var selStackToken = state.InitiativeTracker.token[tokenid];
selStackToken.expiredStatuses = [];
_.each(selStackToken.statuses, function (selStatus, index) {
selStatus.duration--;
if (selStatus.duration <= 0) {
graphic.set("status_" + selStatus.name, false);
selStackToken.nextInitiative -= getInitModFromAliasOrStatus(Tracker.getAliasOrName(selStatus));
announceStatusExpiration(getAliasOrName(selStatus), graphic.get('name'));
selStackToken.expiredStatuses.push(selStackToken.statuses.splice(i, 1)[0]);
} else if (selStatus.duration < 10) {
// status has nine or fewer rounds left; update marker to reflect remaining rounds
graphic.set("status_" + selStatus.name, selStatus.duration);
}
});
}
exists = false;
//synchronize the init tracker stucture with the extant tokens
stackTokenSync(tokenid);
stackToken = state.InitiativeTracker.token[tokenid];
stackToken.initiative = stackToken.nextInitiative;
stackTokenInit = stackToken.initiative;
//check to see if the token is linked to a character
charid = graphic.get('represents');
if (charid != undefined && charid != '') {
//if the token represents a character we handle it uniquely
initBonus = getAttrByName(charid, "AgilityMod", "current");
//TODO: eventually, we want linked characters to have their initiative modifier reflected in the character sheet
roll = randomInteger(10) + parseInt(initBonus);
} else {
//if there's no linked char, see if we can find any characters with the exact same name as the token
characterName = graphic.get('name');
matchingCharacters = findObjs({
_type: "character",
name: characterName,
});
if (matchingCharacters.length == 0) {
//generic tokens with no matching character get a generic roll
initBonus = 0;
roll = randomInteger(10);
} else {
//if there's a matching character but the token isn't directly linked then the character is a mook
charid = matchingCharacters[0].get('id');
if (state.InitiativeTracker['pooledInit'] === true) {
exists = !usedCharArray.every(function (used) {
return used !== charid;
});
}
if (exists === false) {
//handles first instance of a mook
initBonus = getAttrByName(charid, "AgilityMod", "current");
roll = randomInteger(10) + parseInt(initBonus);
rollArray[charid] = roll;
usedCharArray.push(charid);
} else {
//handles subsequent instances of a mook
initBonus = getAttrByName(charid, "AgilityMod", "current");
roll = rollArray[charid];
}
}
}
//add any status-based initiative modifications
roll += parseInt(stackTokenInit);
if (charid) {
duplicateInit = _.some(adjRollArray[charid], function (value) {
return value === roll;
});
if (exists === false) adjRollArray[charid] = [];
if (duplicateInit === false) adjRollArray[charid].push(roll);
}
//place in ordered turnorder array IF the character hasn't already been added OR the character is a mook with an adjusted initiative value
if (exists === false || (exists === true && duplicateInit === false)) {
//place the new entry in an ordered position on the stack
newEntry = {
id: tokenid,
pr: roll,
custom: graphic.get('name'),
_pageid: page_id
};
//remove items from the stack until we encounter a roll entry equal to or less than the top of the stack
if (state.InitiativeTracker['highToLow'] === true) {
while (newEntry.pr > turnorder[turnorder.length - 1].pr) {
oldstack.push(turnorder.pop());
}
//check the tiebreaker if tied or just add it to the stack
if (newEntry.pr === turnorder[turnorder.length - 1].pr) {
//get the initiative bonuses for the requisite tokens' characters
var newTokenInitBonus, oldTokenInitBonus;
if (charid) newTokenInitBonus = getAttrByName(charid, "AgilityMod", "current");
else newTokenInitBonus = 0;
oldTokenInitBonus = getObj("graphic", turnorder[turnorder.length - 1].id).get('represents');
if (oldTokenInitBonus) oldTokenInitBonus = getAttrByName(oldTokenInitBonus, "AgilityMod", "current");
else {
matchingCharacters = findObjs({
_type: "character",
name: characterName,
});
if (matchingCharacters.length === 0) oldTokenInitBonus = 0;
else oldTokenInitBonus = getAttrByName(matchingCharacters[0].id, "AgilityMod", "current");
}
if (newTokenInitBonus > oldTokenInitBonus) oldstack.push(turnorder.pop());
turnorder.push(newEntry);
} else if (newEntry.pr < turnorder[turnorder.length - 1].pr) {
turnorder.push(newEntry);
} else {
log("something fucked up");
}
//restore the bottom of the stack
while (oldstack.length > 0) {
turnorder.push(oldstack.pop());
}
} else {
while (newEntry.pr < turnorder[turnorder.length - 1].pr) {
oldstack.push(turnorder.pop());
}
//check the tiebreaker if tied or just add it to the stack
if (newEntry.pr === turnorder[turnorder.length - 1].pr) {
//get the initiative bonuses for the requisite tokens' characters
var newTokenInitBonus, oldTokenInitBonus;
if (charid) newTokenInitBonus = getAttrByName(charid, "AgilityMod", "current");
else newTokenInitBonus = 0;
oldTokenInitBonus = getObj("graphic", turnorder[turnorder.length - 1].id).get('represents');
if (oldTokenInitBonus) oldTokenInitBonus = getAttrByName(oldTokenInitBonus, "AgilityMod", "current");
else {
matchingCharacters = findObjs({
_type: "character",
name: characterName,
});
if (matchingCharacters.length === 0) oldTokenInitBonus = 0;
else oldTokenInitBonus = getAttrByName(matchingCharacters[0].id, "AgilityMod", "current");
}
if (newTokenInitBonus < oldTokenInitBonus) oldstack.push(turnorder.pop());
turnorder.push(newEntry);
} else if (newEntry.pr > turnorder[turnorder.length - 1].pr) {
turnorder.push(newEntry);
} else {
log("something fucked up");
}
//restore the bottom of the stack
while (oldstack.length > 0) {
turnorder.push(oldstack.pop());
}
}
}
}
});
//Push turnorder to roll20
log("Turn Order Str: " + JSON.stringify(turnorder));
Campaign().set("turnorder", JSON.stringify(turnorder));
},
announceRound = function (round) {
if (!state.InitiativeTracker.announceRounds) {
return;
}
sendChat("", "/desc Start of Round " + round);
},
announceTurn = function (count, tokenName, tokenId) {
if (!state.InitiativeTracker.announceTurns) {
return;
}
if (!tokenName) {
var token = getObj("graphic", tokenId);
if (token) {
tokenName = token.get('name');
}
}
sendChat("", "/desc Start of Turn " + state.InitiativeTracker.round + " for " + tokenName + " (" + count + ")");
},
announceStatusExpiration = function (status, tokenName) {
if (!state.InitiativeTracker.announceExpiration) {
return;
}
sendChat("", "/desc Status " + status + " expired on " + tokenName);
},
handleTurnChange = function (newTurnOrder, oldTurnOrder) {
var newTurns = JSON.parse((typeof (newTurnOrder) == typeof ("") ? newTurnOrder : newTurnOrder.get('turnorder') || "[]"));
var oldTurns = JSON.parse((typeof (oldTurnOrder) == typeof ("") ? oldTurnOrder : oldTurnOrder.turnorder || "[]"));
var matchingTokens = [];
if ((!newTurns) || (!oldTurns)) {
return;
}
if ((newTurns.length == 0) && (oldTurns.length > 0)) {
return reset();
} // turn order was cleared; reset
if ((!newTurns.length) || (newTurns.length != oldTurns.length)) {
return;
} // something was added or removed; ignore
if ((state.InitiativeTracker.round == null) || (state.InitiativeTracker.count == null)) {
// first change: see if it's time to start tracking
var startTracking = false;
for (var i = 0; i < newTurns.length; i++) {
if (newTurns[i].id != oldTurns[i].id) {
// turn order was sorted; start tracking
startTracking = true;
break;
}
if (newTurns[i].pr != oldTurns[i].pr) {
break;
} // a token's initiative count was changed; don't start tracking yet
}
if (!startTracking) {
return;
}
state.InitiativeTracker.round = 1;
state.InitiativeTracker.count = newTurns[0].pr;
announceRound(state.InitiativeTracker.round);
announceTurn(newTurns[0].pr, newTurns[0].custom, newTurns[0].id);
return;
}
if (newTurns[0].id == oldTurns[0].id) {
return;
} // turn didn't change
var newCount = newTurns[0].pr;
var oldCount = state.InitiativeTracker.count;
if (!state.InitiativeTracker.highToLow) {
// use negatives for low-to-high initiative so inequalities work out the same as high-to-low
newCount = -newCount;
oldCount = -oldCount;
}
var roundChanged = newCount > oldCount;
//if status markers are set to update every turn...do that
if (state.InitiativeTracker['statusTurn'] === true) {
//Adjust statuses for the token whose turn just ended (the previous token)
if (newTurns[newTurns.length - 1].id != -1) {
var currentToken = getObj("graphic", newTurns[newTurns.length - 1].id);
//create a new token entry if necessary
stackTokenSync(newTurns[newTurns.length - 1].id);
var currentStackToken = state.InitiativeTracker.token[newTurns[newTurns.length - 1].id];
var characterName = currentToken.get('name');
let charid = currentToken.get('represents');
if(charid != undefined && charid != ''){
matchingTokens.push(currentToken);
}else{
matchingTokens = findObjs({
_pageid: Campaign().get("playerpageid"),
_type: "graphic",
_subtype: "token",
name: characterName
});
}
//find all tokens that match a given character name
_.each(matchingTokens, function (selToken) {
//Tracker.stackTokenSync(selToken.id);
stackTokenSync(selToken.id);
var selStackToken = state.InitiativeTracker.token[selToken.id];
if (selStackToken.initiative == currentStackToken.initiative) {
selStackToken.expiredStatuses = [];
for (var i = 0; i < selStackToken.statuses.length; i++) {
var selStatus = selStackToken.statuses[i];
selStatus.duration--;
if (selStatus.duration <= 0) {
selToken.set("status_" + selStatus.name, false);
selStackToken.nextInitiative -= getInitModFromAliasOrStatus(getAliasOrName(selStatus));
announceStatusExpiration(getAliasOrName(selStatus), selToken.get('name'));
selStackToken.expiredStatuses.push(selStackToken.statuses.splice(i, 1)[0]);
log("the expired status stack has: " + selStackToken.expiredStatuses[selStackToken.expiredStatuses.length - 1].name + "on the stack")
i -= 1;
} else if (selStatus.duration < 10) {
// status has nine or fewer rounds left; update marker to reflect remaining rounds
selToken.set("status_" + selStatus.name, selStatus.duration);
}
}
}
});
}
}
if (roundChanged) {
handleRoundChange();
}
//Look ahead and see if the next turn will have a round change TODO: adjust for no dynamic init
if (state.InitiativeTracker['dynamicInit'] === true && ((newTurns[0].pr < newTurns[1].pr && state.InitiativeTracker['highToLow']) || (newTurns[0].pr > newTurns[1].pr && !state.InitiativeTracker['highToLow']))) {
Tracker.oldRoundOrder = Campaign().get('turnorder') || "[]";
log("Latched turn order str: " + Tracker.oldRoundOrder);
}
state.InitiativeTracker.count = newTurns[0].pr;
announceTurn(newTurns[0].pr, newTurns[0].custom, newTurns[0].id);
},
handleRoundChange = function () {
state.InitiativeTracker.round += 1;
announceRound(state.InitiativeTracker.round);
//Dynamic Init hook: find all the tokens on the map and reroll their initiative
if (state.InitiativeTracker['dynamicInit'] === true) {
rebuildTurnOrder();
}
if (state.InitiativeTracker['statusTurn'] === false) {
//TODO: update all token statuses
}
},
getConfigParam = function (who, param) {
if (param == null) {
for (var i = 0; i < CONFIG_PARAMS.length; i++) {
var head = CONFIG_PARAMS[i][1] + " (" + CONFIG_PARAMS[i][0] + "): ";
write(head + state.InitiativeTracker[CONFIG_PARAMS[i][0]], who, "", "Tracker");
}
} else {
var err = true;
for (var i = 0; i < CONFIG_PARAMS.length; i++) {
if (CONFIG_PARAMS[i][0] == param) {
var head = CONFIG_PARAMS[i][1] + " (" + CONFIG_PARAMS[i][0] + "): ";
write(head + state.InitiativeTracker[CONFIG_PARAMS[i][0]], who, "", "Tracker");
err = false;
break;
}
}
if (err) {
write("Error: Config parameter '" + param + "' not found", who, "", "Tracker");
}
}
},
setConfigParam = function (who, param, value) {
var err = true;
for (var i = 0; i < CONFIG_PARAMS.length; i++) {
if (CONFIG_PARAMS[i][0] == param) {
state.InitiativeTracker[CONFIG_PARAMS[i][0]] = (value == null ? !state.InitiativeTracker[CONFIG_PARAMS[i][0]] : value);
err = false;
break;
}
}
if (err) {
write("Error: Config parameter '" + param + "' not found", who, "", "Tracker");
}
},
showTrackerHelp = function (who, cmd) {
write(cmd + " commands:", who, "", "Tracker");
var helpMsg = "";
helpMsg += "help: display this help message\n";
helpMsg += "round [NUM]: display the current round number, or set round number to NUM\n";
helpMsg += "forward: advance the initiative counter to the next token\n";
helpMsg += "fwd: synonym for forward\n";
helpMsg += "back: rewind the initiative counter to the previous token\n";
helpMsg += "start: sort the tokens in the initiative counter and begin tracking\n";
helpMsg += "get [PARAM]: display the value of the specified config parameter, or all config parameters\n";
helpMsg += "set PARAM [VALUE]: set the specified config parameter to the specified value (defaults to true)\n";
helpMsg += "enable PARAM: set the specified config parameter to true\n";
helpMsg += "disable PARAM: set the specified config parameter to false\n";
helpMsg += "toggle PARAM: toggle the specified config parameter between true and false";
write(helpMsg, who, "font-size: small; font-family: monospace", "Tracker");
},
handleTrackerMessage = function (args, msg) {
var who = msg.who;
var selected = msg.selected;
let cmd = args.shift();
switch (cmd) {
case "sync":
dataSync();
log("backend synced with tabletop");
break;
case "back":
try {
//TODO: Better error handling & turn/round announcements
var oldTurnOrderStr = Campaign().get('turnorder') || "[]";
var turnOrder = JSON.parse(oldTurnOrderStr);
if (turnOrder.length > 0) {
var oldCount = turnOrder[0].pr;
turnOrder.unshift(turnOrder.pop());
var newCount = turnOrder[0].pr;
var newTurnOrderStr = JSON.stringify(turnOrder);
//with the turnorder set, handle statuses
if (state.InitiativeTracker['statusTurn'] == true) {
if (turnOrder[0].id != -1) {
var currentToken = getObj("graphic", turnOrder[0].id);
//create a new token entry if necessary
stackTokenSync(turnOrder[0].id);
var currentStackToken = state.InitiativeTracker.token[turnOrder[0].id];
var characterName = currentToken.get('name');
var matchingTokens = findObjs({
_pageid: Campaign().get("playerpageid"),
_type: "graphic",
_subtype: "token",
name: characterName
});
//find all tokens that match a given character name
_.each(matchingTokens, function (selToken) {
var selStackToken = state.InitiativeTracker.token[selToken.id];
if (selStackToken.initiative == currentStackToken.initiative) {
for (var i = 0; i < selStackToken.statuses.length; i++) {
var selStatus = selStackToken.statuses[i];
selStatus.duration++;
if (selStatus.duration < 10) {
// status has nine or fewer rounds left; update marker to reflect remaining rounds
selToken.set("status_" + selStatus.name, selStatus.duration);
} else {
selToken.set("status_" + selStatus.name, true);
}
}
while (selStackToken.expiredStatuses.length > 0) {
var selExpStatus = selStackToken.expiredStatuses.pop();
selStackToken.statuses.push(selExpStatus);
selToken.set("status_" + selExpStatus.name, 1);
selStackToken.nextInitiative += getInitModFromAliasOrStatus(getAliasOrName(selExpStatus));
}
}
});
}
}
if (!state.InitiativeTracker.highToLow) {
// use negatives for low-to-high initiative so inequalities work out the same as high-to-low
newCount = -newCount;
oldCount = -oldCount;
}
var roundChanged = newCount < oldCount;
log("the old count is: " + oldCount + " and the new count is: " + newCount);
if (roundChanged && state.InitiativeTracker['dynamicInit'] === true) {
state.InitiativeTracker.count = turnOrder[0].pr;
state.InitiativeTracker.round -= 1;
Campaign().set('turnorder', Tracker.oldRoundOrder);
log("Going back and restoring the latched TO str: " + Tracker.oldRoundOrder);
} else if (roundChanged && state.InitiativeTracker['dynamicInit'] === false) {
state.InitiativeTracker.count = turnOrder[0].pr;
state.InitiativeTracker.round -= 1;
Campaign().set('turnorder', newTurnOrderStr);
} else {
state.InitiativeTracker.count = turnOrder[0].pr;
Campaign().set('turnorder', newTurnOrderStr);
}
}
} catch (e) {
write("Error: No previous round data is stored", who, "", "Tracker");
}
break;
case "restart":
var turnOrder = JSON.parse(Campaign().get('turnorder') || "[]");
//sync the backend OR sync and clear the backend if optional parameters are provided
if (args[0] && args[0] === 'sync') {
dataSync();
} else if (args[0] && args[0] === 'del') {
let currentPageGraphics = findObjs({
_pageid: Campaign().get("playerpageid"),
_type: "graphic",
_subtype: "token",
});
_.each(currentPageGraphics, function (selToken) {
if (selToken.get('bar3_value') != '') {
selToken.set("statusmarkers", '');
}
});
dataSync();
}
//reset the tracker and turn order
if (turnOrder.length > 0) {
turnOrder.sort(function (x, y) {
return (state.InitiativeTracker.highToLow ? y.pr - x.pr : x.pr - y.pr);
});
Campaign().set('turnorder', JSON.stringify(turnOrder));
state.InitiativeTracker.round = 1;
state.InitiativeTracker.count = turnOrder[0].pr;
rebuildTurnOrder();
announceRound(state.InitiativeTracker.round);
announceTurn(turnOrder[0].pr, turnOrder[0].custom, turnOrder[0].id);
}
break;
case "start":
//TODO: make this work
break;
case "get":
if (args.length < 1) {
getConfigParam(who, null);
} else {
getConfigParam(who, args[0]);
}
break;
case "set":
if (args.length < 1) {
write("Error: The 'set' command requires at least one argument (the parameter to set)", who, "", "Tracker");
break;
}
var value = true;
if (args.length > 1) {
if ((args[1] != "true") && (args[1] != "yes") && (args[1] != "1")) {
value = false;
}
}
setConfigParam(who, args[0], value);
break;
case "enable":
if (args.length != 1) {
write("Error: The 'enable' command requires exactly one argument (the parameter to enable)", who, "", "Tracker");
break;
}
setConfigParam(who, args[0], true);
break;
case "disable":
if (args.length != 1) {
write("Error: The 'disable' command requires exactly one argument (the parameter to disble)", who, "", "Tracker");
break;
}
setConfigParam(who, args[0], false);
break;
case "toggle":
if (args.length != 1) {
write("Error: The 'toggle' command requires exactly one argument (the parameter to toggle)", who, "", "Tracker");
break;
}
setConfigParam(who, args[0], null);
break;
case "help":
showTrackerHelp(who, cmd);
break;
default:
write("Error: Unrecognized command: " + cmd, who, "", "Tracker");
showTrackerHelp(who, cmd);
}
},
addStatus = function (tokenId, status, duration, description) {
let alias, selectedToken;
let token = getObj("graphic", tokenId);
let matchingTokens = [];
if (!token) {
log("didn't find a token");
return;
}
//log("addStatus:" + tokenId + "," + status + "," + duration);
if (state.InitiativeTracker['complexstatushandler'] === true) {
if (STATUS_TYPES[status] == "persistent") {
duration = 300;
} else if (STATUS_TYPES[status] == "round") {
duration = 1;
} else if (STATUS_TYPES[status] == "rounds") {}
}
//determine the alias and status
if (STATUS_ALIASES[status]) {
alias = status;
status = STATUS_ALIASES[status];
} else if (_.invert(STATUS_ALIASES)[status]) {
alias = _.invert(STATUS_ALIASES)[status];
} else {
alias = '';
status = '';
}
//if updating statuses after every turn, check current turn order and +1 for current turn token
//TODO: make sure this works for generic tokens
if (state.InitiativeTracker['statusTurn'] === true) {
var oldTurnOrderStr = Campaign().get('turnorder') || "[]";
var turnOrder = JSON.parse(oldTurnOrderStr);
var currentTurnToken = getObj("graphic", turnOrder[0].id);
if(currentTurnToken){
var characterName = currentTurnToken.get('name');
let charid = currentTurnToken.get('represents');
if(charid != undefined && charid != ''){
matchingTokens.push(currentTurnToken);
}else{
matchingTokens = findObjs({
_pageid: Campaign().get("playerpageid"),
_type: "graphic",
_subtype: "token",
name: characterName
});
}
let curTurn = _.find(matchingTokens, function(checkid){ return checkid.id ===tokenId; });
if(curTurn) duration++;
}
}
//sync stack with extant tokens
stackTokenSync(tokenId);
selectedToken = state.InitiativeTracker.token[tokenId];
selectedToken.nextInitiative += getInitModFromAliasOrStatus(status);
state.InitiativeTracker.token[tokenId].statuses.push({
'duration': duration,
'count': state.InitiativeTracker.count,
'name': status,
'alias': alias,
'severity': 0
});
if (duration > 10) {
duration = true;
}
token.set("status_" + status, duration);
},
showStatusHelp = function (who, cmd) {
write(cmd + " commands:", who, "", "Tracker");
var helpMsg = "";
helpMsg += "help: display this help message\n";
helpMsg += "add DUR ICON DESC: add DUR rounds of status effect with specified icon and description to selected tokens\n";
helpMsg += "list: list all status effects for selected tokens\n";
helpMsg += "show: synonym for list\n";
helpMsg += "remove [ID]: remove specified status effect, or all status effects from selected tokens\n";
helpMsg += "rem, delete, del: synonyms for remove\n";
helpMsg += "icons: list available status icons and aliases";
write(helpMsg, who, "font-size: small; font-family: monospace", "Tracker");
},
handleStatusMessage = function (args, msg) {
let who = msg.who;
let selected = msg.selected;
let output = '';
if (!args) return showStatusHelp(who, "filler");
let cmd = args.shift();
switch (cmd) {
case "add":
if ((!selected) || (selected.length <= 0)) {
write("Error: The 'add' command requires at least one selected token", who, "", "Tracker");
break;
}
if (args.length < 3) {
write("Error: The 'add' command requires three arguments (duration, icon, description)", who, "", "Tracker");