-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
Copy pathsheetWorkers.js
3837 lines (3383 loc) · 168 KB
/
sheetWorkers.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
// --- ALL SHEET WORKERS START --- //
const PLAYER = 'player';
const SHEET_WORKER = 'sheetworker';
const SUCCESS = 1;
const INFO = 2;
const WARNING = 3;
const ERROR = 4;
const ERRATA_FIELD = 'errata';
const PSIONICS_HANDBOOK = 'The Complete Psionics Handbook';
const BOOK_FIELDS = [
'book-phb','book-tcfhb','book-tcthb','book-tcprhb','book-tcwhb','book-psionics',
'book-tom','book-aaeg',
'book-dwarves','book-bards','book-elves','book-humanoids','book-rangers',
'book-paladins','book-druids','book-barbarians','book-necromancers','book-ninjas',
'book-combat-and-tactics','book-skills-and-powers','book-spells-and-magic'
];
const LEVEL_FIELDS = {
'level-class1': 'class1',
'level-class2': 'class2',
'level-class3': 'class3',
'level-class4': 'class4',
'level-class5': 'class5',
};
const THAC0_FORMULAS = {
'warrior': l => 21-l,
'wizard': l => 21-Math.ceil(l/3),
'priest': l => 22-(Math.ceil(l/3)*2),
'rogue': l => 21-Math.ceil(l/2),
'psionicist': l => 21-Math.ceil(l/2),
}
const SPELL_LEVEL_REQUIREMENT = {
'Wizard': {
'1': 1,
'2': 3,
'3': 5,
'4': 7,
'5': 9,
'6': 12,
'7': 14,
'8': 16,
'9': 18,
},
'Priest': {
'1': 1,
'2': 3,
'3': 5,
'4': 7,
'5': 9,
'6': 11,
'7': 14,
'q': 10,
}
}
const SCHOOL_SPELLS_AND_MAGIC = 'school-spells-and-magic';
const SCHOOL_FIELDS = [SCHOOL_SPELLS_AND_MAGIC];
const SPHERE_SPELLS_AND_MAGIC = 'sphere-spells-and-magic';
const SPHERE_FIELDS = ['sphere-druids', 'sphere-necromancers', SPHERE_SPELLS_AND_MAGIC];
class RollTemplateBuilder {
constructor(template) {
this.template = template;
this.builder = [];
}
push(args) {
if (Array.isArray(args)) {
this.builder = this.builder.concat(args);
} else {
for (let i = 0; i < arguments.length; i++) {
this.builder.push(arguments[i]);
}
}
}
string() {
return `&{template:${this.template}} ${this.builder.map(s => `{{${s}}}`).join(' ')}`;
}
}
//#region Helper function
const isSheetWorkerUpdate = function (eventInfo) {
return eventInfo.sourceType === SHEET_WORKER;
}
const isPlayerUpdate = function (eventInfo) {
return eventInfo.sourceType === PLAYER;
}
const capitalizeFirst = function (s) {
if (typeof s !== 'string')
return '';
return s.charAt(0).toUpperCase() + s.slice(1).toLowerCase();
}
const displaySize = function(size) {
if (typeof size !== 'string' || size.length === 0)
return '';
let sizeLetter = size.charAt(0).toLowerCase();
switch (sizeLetter) {
case 't': return 'Tiny';
case 's': return 'Small';
case 'm': return 'Medium';
case 'l': return 'Large';
case 'h': return 'Huge';
case 'g': return 'Gargantuan';
default: return capitalizeFirst(size);
}
}
const sizeToInt = function(size) {
if (typeof size !== 'string' || size.length === 0)
return '';
let sizeLetter = size.charAt(0).toLowerCase();
switch (sizeLetter) {
case 't': return 0;
case 's': return 1;
case 'm': return 2;
case 'l': return 3;
case 'h': return 4;
case 'g': return 5;
}
}
const displayWeaponType = function (type) {
if (typeof type !== 'string' || type.length === 0)
return '';
let typeLetter = type.toLowerCase();
switch (typeLetter) {
case 's': return 'Slashing';
case 'p': return 'Piercing';
case 'b': return 'Bludgeoning';
default: return capitalizeFirst(type);
}
}
const parseSourceAttribute = function (eventInfo) {
let parse = {};
if (eventInfo.sourceAttribute.startsWith('repeating')) {
let split = eventInfo.sourceAttribute.split('_');
parse.section = split[1];
parse.rowId = split[2];
parse.attribute = split[3];
} else {
parse.attribute = eventInfo.sourceAttribute;
}
return parse;
}
const conditionalLog = function (bool, msg) {
if (bool)
console.log(msg);
}
const extractQueryResult = async function(query){//Sends a message to query the user for some behavior, returns the selected option.
let queryRoll = await startRoll(`!{{query=[[0[response=${query}] ]]}}`);
finishRoll(queryRoll.rollId);
return queryRoll.results.query.expression.replace(/^.+?response=|\]$/g,'');
};
const extractRoll = async function(rollExpression) {
let queryRoll = await startRoll(`!{{roll=[[${rollExpression}]]}}`);
finishRoll(queryRoll.rollId);
return queryRoll.results.roll;
};
const extractRollResult = async function(rollExpression) {
let roll = await extractRoll(rollExpression);
return roll.result;
};
// Call this when an async function does not call the CRP to keep the reference to the character sheet.
const keepContextRoll = async function () {
let dummyRoll = await startRoll('!{{roll=}}');
finishRoll(dummyRoll.rollId);
}
const printRoll = async function(rollExpression) {
let roll = await startRoll(rollExpression);
finishRoll(roll.rollId);
}
const isRollValid = function (rollExpression, field) {
let expression = rollExpression.trim();
if (!expression)
return false;
let message = `In the field @{${field}} you have unmatched opening and closing`;
let openPara = (expression.match(/\(/g) || []).length
let closePara = (expression.match(/\)/g) || []).length
if (openPara !== closePara) {
showToast(ERROR, 'Unmatched Parenthesis', `${message} parenthesis. You have:\n${openPara}x '('\n${closePara}x ')'`);
return false;
}
let openCurly = (expression.match(/{/g) || []).length
let closeCurly = (expression.match(/}/g) || []).length
if (openCurly !== closeCurly) {
showToast(ERROR, 'Unmatched Curly brackets', `${message} curly brackets. You have:\n${openCurly}x '{'\n${closeCurly}x '}'`);
return false;
}
let openSquare = (expression.match(/\[/g) || []).length
let closeSquare = (expression.match(/]/g) || []).length
if (openSquare !== closeSquare) {
showToast(ERROR, 'Unmatched Square brackets', `${message} square brackets. You have:\n${openSquare}x '['\n${closeSquare}x ']'`);
return false;
}
if (openSquare % 2 !== 0) {
showToast(ERROR, 'Square brackets error', `The field @{${field}} have too few square brackets. Square brackets are used in pairs of two, ie. [[ ]].\nThe expression have an uneven number of bracket pairs: ${openSquare}`);
return false;
}
return true;
}
const getClassesWithLevels = function(values) {
let result = {};
Object.entries(LEVEL_FIELDS).forEach(([levelField, classField]) => {
let levelValue = parseInt(values[levelField]);
if (isNaN(levelValue) || levelValue < 1) {
return;
}
result[levelField] = {level: levelValue, className: values[classField]}
switch (levelField.slice(-1)) {
case "1": result[levelField].classGroup = 'warrior'; break;
case "2": result[levelField].classGroup = 'wizard'; break;
case "3": result[levelField].classGroup = 'priest'; break;
case "4": result[levelField].classGroup = 'rogue'; break;
case "5": result[levelField].classGroup = 'psionicist'; break;
}
});
return result;
}
const getClassSuggestionOptions = function (values) {
return Object.entries(getClassesWithLevels(values)).map(([levelField,classProperties]) => {
// remove comma as it breaks query format
let className = classProperties.className.replaceAll(/[,|]/g,'');
className = className ? className : `${levelField}`;
return `${className} level ${classProperties.level},${levelField}`;
}).join('|');
}
const LEVEL_CLASS_REGEX = /@\{level-class[1-5]}/g;
const checkClassLevel = async function(formulaField, values, rollExpression) {
await keepContextRoll();
let match = rollExpression.match(LEVEL_CLASS_REGEX);
if (!match)
return rollExpression; // There is no scaling
let levelsInExpression = new Set(match);
if (levelsInExpression.size > 1)
return rollExpression; // More than one level-class present. The user presumably knows what he is doing
let classesWithLevels = getClassesWithLevels(values);
let levelsWithValue = Object.keys(classesWithLevels);
if (levelsWithValue.length === 0)
return rollExpression; // The user has not set levels in any fields
let [levelInExpression] = levelsInExpression; // first element from set
let levelInExpressionNoBrackets = levelInExpression.replace(/[@{}]/g, '');
if (levelsWithValue.length === 1) {
if (levelInExpressionNoBrackets === levelsWithValue[0]) {
return rollExpression;
} else {
return rollExpression.replaceAll(levelInExpressionNoBrackets, classesWithLevels[0]);
}
} else {
let suggestedClasses = getClassSuggestionOptions(values);
let query = parseInt(values[levelInExpressionNoBrackets])
? `?{Macro [${formulaField}]: Please confirm the class to use|${suggestedClasses}}`
: `?{Macro [${formulaField}]: ${levelInExpressionNoBrackets} has no value. Please select the class to use|${suggestedClasses}}`;
let field = await extractQueryResult(query);
return rollExpression.replaceAll(levelInExpressionNoBrackets, field);
}
}
const calculateFormula = function(formulaField, calculatedField, doCheckClassLevel) {
getAttrs([formulaField, ...Object.entries(LEVEL_FIELDS).flat()], async function (values) {
let rollExpression = values[formulaField];
let valid = isRollValid(rollExpression, formulaField);
if (!valid)
return;
let valueToSet = {};
if (doCheckClassLevel) {
let updatedRollExpression = await checkClassLevel(formulaField, values, rollExpression);
if (rollExpression !== updatedRollExpression) {
valueToSet[formulaField] = rollExpression = updatedRollExpression;
}
}
if (calculatedField) {
valueToSet[calculatedField] = await extractRollResult(rollExpression);
}
if (Object.keys(valueToSet).length > 0) {
setAttrs(valueToSet);
}
});
}
const getToastObject = function (type, title, message) {
return {
['toast']: 1,
['toast-content']: type,
['toast-title']: title,
['toast-message']: message
}
}
const showToast = function(type, title, message) {
setAttrs(getToastObject(type, title, message));
}
const getActiveSettings = function (settingFields, values) {
let settings = settingFields.map(bField => values[bField])
.filter(Boolean)
.filter(book => book !== '0');
return new Set(settings);
}
const isBookActive = function (books, obj) {
let activeBooks = getActiveSettings(BOOK_FIELDS, books);
console.log(activeBooks);
if (typeof obj === 'string') {
return activeBooks.has(obj);
}
return false
}
const isBookInactive = function (books, obj) {
let activeBooks = getActiveSettings(BOOK_FIELDS, books);
if (Array.isArray(obj))
return obj.every(b => !activeBooks.has(b));
else
return !activeBooks.has(obj['book']);
}
const bookInactiveGetToastObject = function (books, obj) {
let bookInactive = isBookInactive(books, obj);
let result = null;
if (bookInactive) {
if (Array.isArray(obj)) {
let booksString = obj.map(b => '\n* ' + b).join('')
result = getToastObject(ERROR, 'Missing Book(s)', `The book(s):${booksString}\nAre currently not active on your sheet.\nGo to the *Sheet Settings* and activate any of the listed book(s) (if your DM allows for its usage)`);
} else {
result = getToastObject(ERROR, 'Missing Book', `The book *${obj['book']}* is currently not active on your sheet.\nGo to the *Sheet Settings* and activate the book (if your DM allows for its usage)`);
}
}
return result;
}
const bookInactiveShowToast = function(books, obj) {
let bookInactive = isBookInactive(books, obj);
if (bookInactive) {
if (Array.isArray(obj)) {
let booksString = obj.map(b => '\n* ' + b).join('')
showToast(ERROR, 'Missing Book(s)', `The book(s):${booksString}\nAre currently not active on your sheet.\nGo to the *Sheet Settings* and activate any of the listed book(s) (if your DM allows for its usage)`);
} else {
showToast(ERROR, 'Missing Book', `The book *${obj['book']}* is currently not active on your sheet.\nGo to the *Sheet Settings* and activate the book (if your DM allows for its usage)`);
}
}
return bookInactive;
};
const isRemoving0 = function(eventInfo, fieldNames) {
return fieldNames.some(fieldName => !parseInt(eventInfo.removedInfo[`${eventInfo.sourceAttribute}_${fieldName}`]));
};
const isOverwriting0 = function(eventInfo) {
return !parseInt(eventInfo.newValue) && !parseInt(eventInfo.previousValue);
};
const doEarlyReturn = function(eventInfo, fieldNames) {
return eventInfo.removedInfo
? isRemoving0(eventInfo, fieldNames)
: isOverwriting0(eventInfo);
};
const repeatingMultiplySum = function(section, valueField, multiplierField, destination, decimals) {
TAS.repeating(section)
.attr(destination)
.field([valueField, multiplierField])
.reduce(function(m, r) {
return m + r.F[valueField] * r.F[multiplierField];
}, 0, function(t,r,a) {
let dec = parseInt(decimals);
if (isNaN(dec)) {
a[destination] = t;
} else {
a.D[dec][destination] = t;
}
})
.execute();
};
const repeatingCalculateRemaining = function(repeatingName, repeatingFieldsToSum, totalField, remainingField) {
TAS.repeating(repeatingName)
.attrs([totalField, remainingField])
.fields(repeatingFieldsToSum)
.reduce(function (memo, row) {
repeatingFieldsToSum.forEach(column => {
memo += row.I[column];
});
return memo;
}, 0, function (memo,_,attrSet) {
attrSet.I[remainingField] = attrSet.I[totalField] - memo;
}).execute();
};
const repeatingCalculateRemainingRecursive = function (tail, accumulator, resultFieldName) {
let head = tail.shift();
if (!head) {
setAttrs({
[resultFieldName] : accumulator
});
return;
}
TAS.repeating(head.section)
.fields(head.slotsField)
.each(function (r) {
accumulator -= r.I[head.slotsField];
})
.execute(() => repeatingCalculateRemainingRecursive(tail, accumulator, resultFieldName));
};
//#endregion
//#region Generic Setup functions
const setupStaticCalculateTotal = function(totalField, fieldsToSum) {
let onChange = fieldsToSum.map(field => `change:${field}`).join(' ');
on(onChange, function () {
getAttrs(fieldsToSum, function (values) {
let total = 0;
fieldsToSum.forEach(field => {
total += parseInt(values[field]) || 0;
});
setAttrs({
[totalField]: total
});
});
});
}
function setupRepeatingRowCalculateTotal(repeatingName, repeatingFieldsToSum, repeatingTotalField) {
let onChange = repeatingFieldsToSum.map(field => `change:repeating_${repeatingName}:${field}`).join(' ');
on(`${onChange} remove:repeating_${repeatingName}`, function(eventInfo){
if (eventInfo.removedInfo)
return;
TAS.repeating(repeatingName)
.fields([...repeatingFieldsToSum, repeatingTotalField])
.tap(function(rowSet) {
let rowId = parseSourceAttribute(eventInfo).rowId;
let row = rowSet[rowId];
let total = 0;
repeatingFieldsToSum.forEach(column => {
total += row.I[column];
});
row[repeatingTotalField] = total;
})
.execute();
});
}
//#endregion
on('clicked:hide-toast', function(eventInfo) {
setAttrs({
['toast']: 0,
['toast-content']: 0,
});
});
//#region Ability Scores logic
// Ability Score Parser function
const EXCEPTIONAL_STRENGTH_REGEX = /18[\[(]([0-9]{1,3})[\])]/; // Ie. 18[65], 18(65)
function getLookupValue(abilityScoreString, defaultValue, isStrength = false) {
if (abilityScoreString === '') {
return defaultValue;
}
let abilityScoreNumber = parseInt(abilityScoreString);
if (isNaN(abilityScoreNumber) || abilityScoreNumber < 1 || abilityScoreNumber > 25) {
return 0; // Return error value
}
if (isStrength) {
let exceptionalMatch = abilityScoreString.match(EXCEPTIONAL_STRENGTH_REGEX);
if (exceptionalMatch !== null) {
let exceptionalStrNumber = parseInt(exceptionalMatch[1]);
if (1 <= exceptionalStrNumber && exceptionalStrNumber <= 50) {
return '18[01-50]';
}
if (51 <= exceptionalStrNumber && exceptionalStrNumber <= 75) {
return '18[51-75]'
}
if (76 <= exceptionalStrNumber && exceptionalStrNumber <= 90) {
return '18[76-90]'
}
if (91 <= exceptionalStrNumber && exceptionalStrNumber <= 99) {
return '18[91-99]'
}
// 100 can be written as [00] or [100]
if (exceptionalStrNumber === 0 || exceptionalStrNumber === 100) {
return '18[00]'
}
}
}
return abilityScoreNumber;
}
//Set sub-attributes based on Strength, Stamina, and Muscle
on('change:strength change:stamina change:muscle', function() {
getAttrs(['strength','stamina','muscle'], function(values) {
let strengthRaw = values.strength.replace(/\s+/g, '');
let staminaRaw = values.stamina.replace(/\s+/g, '');
let muscleRaw = values.muscle.replace(/\s+/g, '');
let strength = getLookupValue(strengthRaw, '', true);
if (strength === '') {
return;
}
if (strength === 0) {
assignStr(0,0, strengthTable['strnotes'][0], strengthTable['str2notes'][0]);
return;
}
let stamina = getLookupValue(staminaRaw, strength, true);
let muscle = getLookupValue(muscleRaw, strength, true);
let strnotes;
let str2notes;
if (staminaRaw === '' && muscleRaw === '') {
strnotes = [strengthTable['str2notes'][strength], strengthTable['strnotes'][strength]].filter(Boolean).join(', ');
str2notes = '';
} else {
strnotes = stamina === 0 ? 'INVALID STAMINA' : strengthTable['strnotes'][strength];
str2notes = muscle === 0 ? 'INVALID MUSCLE' : strengthTable['str2notes'][muscle];
}
assignStr(stamina, muscle, strnotes, str2notes);
function assignStr(stamina, muscle, strnotes, str2notes) {
setAttrs({
strengthhit: strengthTable['strengthhit'][muscle],
strengthdmg: strengthTable['strengthdmg'][muscle],
carryweight: strengthTable['carryweight'][stamina],
maxpress: strengthTable['maxpress'][muscle],
opendoor: strengthTable['opendoor'][muscle],
bendbar: strengthTable['bendbar'][muscle],
strnotes: strnotes,
str2notes: str2notes,
});
}
});
});
// Set sub-attributes based on Dexterity, Aim, and Balance
on('change:dexterity change:aim change:balance', function() {
getAttrs(['dexterity','aim','balance'], function(values) {
let dexterityRaw = values.dexterity.replace(/\s+/g, '');
let aimRaw = values.aim.replace(/\s+/g, '');
let balanceRaw = values.balance.replace(/\s+/g, '');
let dexterity = getLookupValue(dexterityRaw, '');
if (dexterity === '') {
return;
}
if (dexterity === 0) {
assignAttributes(0, 0, 0, dexterityTable['dexnotes'][0], dexterityTable['dexnotes'][0], false);
return;
}
let aim = getLookupValue(aimRaw, dexterity);
let balance = getLookupValue(balanceRaw, dexterity);
let dexnotes;
let dex2notes;
let standardRules = false;
if (aimRaw === '' && balanceRaw === '') {
dexnotes = dexterityTable['dexnotes'][dexterity];
dex2notes = '';
standardRules = true;
} else {
dexnotes = aim === 0 ? 'INVALID AIM' : dexterityTable['dexnotes'][aim];
dex2notes = balance === 0 ? 'INVALID BALANCE' : dexterityTable['dexnotes'][balance];
}
assignAttributes(dexterity, aim, balance, dexnotes, dex2notes, standardRules);
function assignAttributes(dexterity, aim, balance, dexnotes, dex2notes, standardRules) {
setAttrs({
ppd: dexterityTable['pickpocket'][aim],
old: dexterityTable['openlocks'][aim],
rtd: dexterityTable['findtraps'][aim],
msd: dexterityTable['movesilently'][balance],
hsd: dexterityTable['hideinshadows'][balance],
cwd: standardRules ? '0' : dexterityTable['climbwalls'][balance],
tud: dexterityTable['tunneling'][dexterity],
ebd: dexterityTable['escapebonds'][dexterity],
dexreact: dexterityTable['dexreact'][balance],
dexmissile: dexterityTable['dexmissile'][aim],
dexdefense: dexterityTable['dexdefense'][balance],
dexnotes: dexnotes,
dex2notes: dex2notes,
});
}
});
});
// Set sub-attributes based on Constitution, Health, and Fitness
on('change:constitution change:health change:fitness', function() {
getAttrs(['constitution','health','fitness'], function(values) {
let constitutionRaw = values.constitution.replace(/\s+/g, '');
let healthRaw = values.health.replace(/\s+/g, '');
let fitnessRaw = values.fitness.replace(/\s+/g, '');
let constitution = getLookupValue(constitutionRaw, '');
if (constitution === '') {
return;
}
if (constitution === 0) {
assignAttributes(0,0, 0, constitutionTable['connotes'][0], constitutionTable['con2notes'][0]);
return;
}
let health = getLookupValue(healthRaw, constitution);
let fitness = getLookupValue(fitnessRaw, constitution);
let connotes;
let con2notes;
if (healthRaw === '' && fitnessRaw === '') {
connotes = [constitutionTable['con2notes'][constitution], constitutionTable['connotes'][constitution]].filter(Boolean).join(', ');
con2notes = '';
} else {
connotes = health === 0 ? 'INVALID HEALTH' : constitutionTable['connotes'][constitution];
con2notes = fitness === 0 ? 'INVALID FITNESS' : constitutionTable['con2notes'][fitness];
}
assignAttributes(constitution, health, fitness, connotes, con2notes);
function assignAttributes(constitution, health, fitness, connotes, con2notes) {
setAttrs({
conadj: constitutionTable['conadj'][fitness],
conshock: constitutionTable['conshock'][health],
conres: constitutionTable['conres'][fitness],
conpoisonsave: constitutionTable['conpoisonsave'][health],
conregen: constitutionTable['conregen'][constitution],
connotes: connotes,
con2notes: con2notes,
});
}
});
});
// Set sub-attributes based on Intelligence, Reason, and Knowledge
on('change:intelligence change:reason change:knowledge', function() {
getAttrs(['intelligence','reason','knowledge'], function(values) {
let intelligenceRaw = values.intelligence.replace(/\s+/g, '');
let reasonRaw = values.reason.replace(/\s+/g, '');
let knowledgeRaw = values.knowledge.replace(/\s+/g, '');
let intelligence = getLookupValue(intelligenceRaw, '');
if (intelligence === '') {
return;
}
if (intelligence === 0) {
assignAttributes(0, 0, 0, intelligenceTable['intnotes'][0], intelligenceTable['intnotes'][0]);
return;
}
let reason = getLookupValue(reasonRaw, intelligence);
let knowledge = getLookupValue(knowledgeRaw, intelligence);
let intnotes;
let int2notes;
if (reasonRaw === '' && knowledgeRaw === '') {
intnotes = intelligenceTable['intnotes'][intelligence];
int2notes = '';
} else {
intnotes = reason === 0 ? 'INVALID REASON' : '';
int2notes = knowledge === 0 ? 'INVALID KNOWLEDGE' : intelligenceTable['intnotes'][knowledge];
}
assignAttributes(intelligence, reason, knowledge, intnotes, int2notes);
function assignAttributes(intelligence, reason, knowledge, intnotes, int2notes) {
setAttrs({
intlang: intelligenceTable['intlang'][knowledge],
intlvl: intelligenceTable['intlvl'][reason],
intchance: intelligenceTable['intchance'][knowledge],
intmax: intelligenceTable['intmax'][reason],
intimm1st: intelligenceTable['intimm1st'][reason],
intimm2nd: intelligenceTable['intimm2nd'][reason],
intimm3rd: intelligenceTable['intimm3rd'][reason],
intimm4th: intelligenceTable['intimm4th'][reason],
intimm5th: intelligenceTable['intimm5th'][reason],
intimm6th: intelligenceTable['intimm6th'][reason],
intimm7th: intelligenceTable['intimm7th'][reason],
intnotes: intnotes,
int2notes: int2notes,
});
}
});
});
// Set sub-attributes based on Wisdom, Intuition, and Willpower
async function parseWisBonus(abilityScore, wisdom) {
let bonus = {
'1st': 0,
'2nd': 0,
'3rd': 0,
'4th': 0,
'5th': 0,
'6th': 0,
'7th': 0,
'wind': 0,
'wisbonus': '—',
'wisbonus-prime': '—',
'wisbonus-extra': '—',
};
if (abilityScore < 13 && wisdom < 13) {
await keepContextRoll();
return bonus;
}
let answer = await extractQueryResult('?{Priests get bonus spells from high Wisdom (but not Paladins and Rangers). Do you play a priest?|My character is a priest,true|My character is a different class,false}');
if (answer !== 'true') {
return bonus;
}
// Combine all spell levels into one string
let bonusString = '';
for (let i = 13; i <= abilityScore; i++) {
bonusString += wisdomTable['wisbonus'][i];
}
// Count instances of each spell level
bonus = {
'1st': (bonusString.match(/1st/g) || []).length,
'2nd': (bonusString.match(/2nd/g) || []).length,
'3rd': (bonusString.match(/3rd/g) || []).length,
'4th': (bonusString.match(/4th/g) || []).length,
'5th': (bonusString.match(/5th/g) || []).length,
'6th': (bonusString.match(/6th/g) || []).length,
'7th': (bonusString.match(/7th/g) || []).length,
'wind': wisdomTable['wisdom-wind'][wisdom],
};
// Generate bonus prime and bonus extra strings
function format(bonus, key) {
if (bonus[key] === 0) {
return '';
}
if (bonus[key] === 1) {
return key
}
return `${bonus[key]}x${key}`;
}
bonus['wisbonus-prime'] = [format(bonus, '1st'), format(bonus, '2nd'), format(bonus, '3rd'), format(bonus, '4th')].filter(Boolean).join(', ');
bonus['wisbonus-extra'] = [format(bonus, '5th'), format(bonus, '6th'), format(bonus, '7th')].filter(Boolean).join(', ');
bonus['wisbonus'] = [bonus['wisbonus-prime'], bonus['wisbonus-extra']].filter(Boolean).join(', ');
return bonus;
}
on('change:wisdom change:intuition change:willpower', function() {
getAttrs(['wisdom','intuition','willpower'], async function (values) {
let wisdomRaw = values.wisdom.replace(/\s+/g, '');
let intuitionRaw = values.intuition.replace(/\s+/g, '');
let willpowerRaw = values.willpower.replace(/\s+/g, '');
let wisdom = getLookupValue(wisdomRaw, '');
if (wisdom === '') {
return;
}
let bonusSpells;
if (wisdom === 0) {
bonusSpells = await parseWisBonus(0, 0);
assignAttributes(0, 0, 0, bonusSpells, wisdomTable['wisimmune'][0], wisdomTable['wisimmune'][0], wisdomTable['wisnotes'][0], wisdomTable['wisnotes'][0]);
return;
}
let intuition = getLookupValue(intuitionRaw, wisdom);
let willpower = getLookupValue(willpowerRaw, wisdom);
let wisimm1;
let wisimm2;
let wisnotes;
let wis2notes;
if (intuitionRaw === '' && willpowerRaw === '') {
wisnotes = wisdomTable['wisnotes'][wisdom];
wis2notes = '';
wisimm2 = '';
let wisImmuneArray = [];
for (let i = wisdom; i > 18; i--) {
wisImmuneArray.push(wisdomTable['wisimmune'][i]);
}
wisimm1 = wisImmuneArray.filter(Boolean).join(', ');
} else {
wisnotes = intuition === 0 ? 'INVALID INTUITION' : wisdomTable['wisnotes'][intuition];
wis2notes = willpower === 0 ? 'INVALID WILLPOWER' : wisdomTable['wisnotes'][willpower];
let wisImmuneArray = [];
for (let i = willpower; i > 18; i--) {
wisImmuneArray.push(wisdomTable['wisimmune'][i]);
}
let slicePoint = Math.round(wisImmuneArray.length / 2);
wisimm1 = wisImmuneArray.slice(0, slicePoint).filter(Boolean).join(', ');
wisimm2 = wisImmuneArray.slice(slicePoint).filter(Boolean).join(', ');
}
bonusSpells = await parseWisBonus(intuition, wisdom);
assignAttributes(wisdom, intuition, willpower, bonusSpells, wisimm1, wisimm2, wisnotes, wis2notes);
function assignAttributes(wisdom, intuition, willpower, bonusSpells, wisimm1, wisimm2, wisnotes, wis2notes) {
let newValue = {};
newValue['wisdef'] = wisdomTable['wisdef'][willpower];
newValue['wisbonus'] = bonusSpells['wisbonus'];
newValue['wisbonus-prime'] = bonusSpells['wisbonus-prime'];
newValue['wisbonus-extra'] = bonusSpells['wisbonus-extra'];
newValue['wisfail'] = wisdomTable['wisfail'][intuition];
newValue['wisimm'] = wisimm1;
newValue['wisimm1'] = wisimm1;
newValue['wisimm2'] = wisimm2;
newValue['wisnotes'] = wisnotes;
newValue['wis2notes'] = wis2notes;
newValue['spell-priest-level1-wisdom'] = bonusSpells['1st'];
newValue['spell-priest-level2-wisdom'] = bonusSpells['2nd'];
newValue['spell-priest-level3-wisdom'] = bonusSpells['3rd'];
newValue['spell-priest-level4-wisdom'] = bonusSpells['4th'];
newValue['spell-priest-level5-wisdom'] = bonusSpells['5th'];
newValue['spell-priest-level6-wisdom'] = bonusSpells['6th'];
newValue['spell-priest-level7-wisdom'] = bonusSpells['7th'];
newValue['wisdom-wind'] = bonusSpells['wind'];
setAttrs(newValue);
}
});
});
// Set sub-attributes based on Charisma, Leadership, and Appearance
on('change:charisma change:leadership change:appearance', function() {
getAttrs(['charisma','leadership','appearance'], function(values) {
let charismaRaw = values.charisma.replace(/\s+/g, '');
let leadershipRaw = values.leadership.replace(/\s+/g, '');
let appearanceRaw = values.appearance.replace(/\s+/g, '');
let charisma = getLookupValue(charismaRaw, '');
if (charisma === '') {
return;
}
if (charisma === 0) {
assignAttributes(0,0, 0, charismaTable['chanotes'][0], charismaTable['chanotes'][0]);
return;
}
let leadership = getLookupValue(leadershipRaw, charisma);
let appearance = getLookupValue(appearanceRaw, charisma);
let chanotes;
let cha2notes;
if (leadershipRaw === '' && appearanceRaw === '') {
chanotes = charismaTable['chanotes'][charisma];
cha2notes = '';
} else {
chanotes = leadership === 0 ? 'INVALID LEADERSHIP' : charismaTable['chanotes'][leadership];
cha2notes = appearance === 0 ? 'INVALID APPEARANCE' : charismaTable['chanotes'][appearance];
}
assignAttributes(charisma, leadership, appearance, chanotes, cha2notes);
function assignAttributes(charisma, leadership, appearance, chanotes, cha2notes) {
setAttrs({
chamax: charismaTable['chamax'][leadership],
chaloy: charismaTable['chaloy'][leadership],
chareact: charismaTable['chareact'][appearance],
chanotes: chanotes,
cha2notes: cha2notes,
});
}
});
});
on('clicked:opendoor-check', function (eventInfo){
getAttrs(['opendoor'], async function (values){
let rollBuilder = new RollTemplateBuilder('2Echeck');
rollBuilder.push('character=@{character_name}','checkroll=[[1d20cs1cf20]]','color=blue','success=The door swings open!');
let checkTarget;
let match = values.opendoor.match(/(\d+)\((\d+)\)/);
if (match) {
checkTarget = await extractQueryResult(`?{What kind of door?|Heavy / Stuck door,${match[1]}|Locked / Barred / Magical door,${match[2]}}`);
} else {
checkTarget = '@{opendoor}';
}
rollBuilder.push(`checktarget=[[${checkTarget}+(@{misc-mod})]]`);
if (!match || checkTarget === match[1]) {
rollBuilder.push('checkvs=Open Heavy/Stuck Doors Check','fail=The door stays shut, but you can try again with a cumulative -1 penalty for each try.');
} else {
rollBuilder.push('checkvs=Open Locked/Barred/Magically Held Doors Check','fail=The door stays shut. No further attempts can be made by @{character_name}.');
}
return printRoll(rollBuilder.string());
});
});
//#endregion
//#region Saving throws autofill
on('clicked:saving-throws-character', function (eventInfo) {
const ravenloftTab = 'tab2';
getAttrs([ravenloftTab, ...Object.entries(LEVEL_FIELDS).flat()], async function (values) {
let classesWithLevels = getClassesWithLevels(values);
let numberOfClasses = Object.keys(classesWithLevels).length;
if (numberOfClasses === 0) {
return showToast(ERROR,'Saving throws not updated','All class levels were 0. Please set your class levels on the Character->Info->Details tab');
} else if (numberOfClasses > 1) {
let characterType = await extractQueryResult('?{Are you a Multi-class or Dual-class?|Multi-class|Dual-class}');
if (characterType === 'Dual-class') {
let classSuggestionOptions = getClassSuggestionOptions(values);
let activeClass = await extractQueryResult(`?{Which class is your current active class?|${classSuggestionOptions}}`);
let restrictionsLifted = Object.entries(classesWithLevels)
.every(([levelField,classProperties]) => levelField === activeClass || classesWithLevels[activeClass].level > classProperties.level);
if (!restrictionsLifted) {
Object.keys(classesWithLevels).forEach(key => key === activeClass || delete classesWithLevels[key])
}
}
}
// Ensure all levels are below 21 to keep within index
Object.values(classesWithLevels).forEach(classProperties => Math.min(classProperties.level,21));
let classInfo = Object.values(classesWithLevels).map(cp => `• ${capitalizeFirst(cp.classGroup)} level: ${cp.level}`).join('\n');
let toastObject = getToastObject(SUCCESS,'Saving throw updated',`Character saving throws updated based on the following class(es):\n${classInfo}`);
let newValue = {...toastObject};
newValue['partar'] = Math.min(...Object.values(classesWithLevels).map(cp => SAVING_THROWS[cp.classGroup]['paralyzePoisonDeath'][cp.level]));
newValue['poitar'] = Math.min(...Object.values(classesWithLevels).map(cp => SAVING_THROWS[cp.classGroup]['paralyzePoisonDeath'][cp.level]));
newValue['deatar'] = Math.min(...Object.values(classesWithLevels).map(cp => SAVING_THROWS[cp.classGroup]['paralyzePoisonDeath'][cp.level]));
newValue['rodtar'] = Math.min(...Object.values(classesWithLevels).map(cp => SAVING_THROWS[cp.classGroup]['rodStaffWand'][cp.level]));
newValue['statar'] = Math.min(...Object.values(classesWithLevels).map(cp => SAVING_THROWS[cp.classGroup]['rodStaffWand'][cp.level]));
newValue['wantar'] = Math.min(...Object.values(classesWithLevels).map(cp => SAVING_THROWS[cp.classGroup]['rodStaffWand'][cp.level]));
newValue['pettar'] = Math.min(...Object.values(classesWithLevels).map(cp => SAVING_THROWS[cp.classGroup]['petrificationPolymorph'][cp.level]));
newValue['poltar'] = Math.min(...Object.values(classesWithLevels).map(cp => SAVING_THROWS[cp.classGroup]['petrificationPolymorph'][cp.level]));
newValue['breathtar'] = Math.min(...Object.values(classesWithLevels).map(cp => SAVING_THROWS[cp.classGroup]['breath'][cp.level]));
newValue['sptar'] = Math.min(...Object.values(classesWithLevels).map(cp => SAVING_THROWS[cp.classGroup]['spell'][cp.level]));
if (values[ravenloftTab] === '2') {
newValue['ftar'] = Math.min(...Object.values(classesWithLevels).map(cp => SAVING_THROWS[cp.classGroup]['fear'][cp.level]));
newValue['horrtar'] = Math.min(...Object.values(classesWithLevels).map(cp => SAVING_THROWS[cp.classGroup]['horror'][cp.level]));
newValue['madtar'] = Math.min(...Object.values(classesWithLevels).map(cp => SAVING_THROWS[cp.classGroup]['madness'][cp.level]));
}
setAttrs(newValue);
});
});
on('clicked:saving-throws-monster', function (eventInfo) {
getAttrs(['hitdice','monsterhpextra','monsterintelligence'], async function (values) {
let hitDice = parseInt(values['hitdice']) || 0;
let monsterExtraHp = parseInt(values['monsterhpextra']) || 0
let intelligentLevel = hitDice + Math.ceil(monsterExtraHp / 4);
let monsterInt = parseInt(values['monsterintelligence']);
if (isNaN(monsterInt)) {
await keepContextRoll();
return showToast(ERROR, 'Monster Intelligence Missing', 'Monster Intelligence must be set to calculate saving throws.');
} else if (monsterInt < 1) {
intelligentLevel = Math.ceil(intelligentLevel / 2);
}
hitDice = Math.min(hitDice, 21);
intelligentLevel = Math.min(intelligentLevel, 21);
let intro = 'Monsters get the best saving throws from all classes.'
let classes = [];
if (await extractQueryResult(`?{${intro} Can the monster fight (Warrior)?|Yes|No}`) === 'Yes') {
classes.push('warrior');
}