Advertisement
Guest User

Another RPG Engine stat class code

a guest
Sep 17th, 2019
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.63 KB | None | 0 0
  1. window.Stat = class Stat {
  2. constructor (base) {
  3. this._base = base;
  4. this._mods = {};
  5. this._current = undefined;
  6. }
  7.  
  8. clearCache () {
  9. this._current = undefined;
  10. }
  11.  
  12. addMod (id, mod) {
  13. id = String(id);
  14. if(Number.isFinite(mod)) {
  15. mod = { add: mod };
  16. }
  17. if(typeof mod === "object") {
  18. this._mods[id] = mod;
  19. this.clearCache();
  20. }
  21. }
  22.  
  23. removeMod (id) {
  24. delete this._mods[String(id)];
  25. this.clearCache();
  26. }
  27.  
  28. clearMods () {
  29. this._mods = {};
  30. this.clearCache();
  31. }
  32.  
  33. get base () {
  34. return this._base;
  35. }
  36.  
  37. set base (newBase) {
  38. newBase = Number(newBase);
  39. /* alternative: newBase = setup.roll(newBase) for "3d6" as inputs */
  40. if(!Number.isFinite(newBase)) {
  41. newBase = 0;
  42. }
  43. if (this._base !== newBase) {
  44. this._base = newBase;
  45. this.clearCache();
  46. }
  47. }
  48.  
  49. get current () {
  50. if (this._current === undefined) {
  51. /* gather multipliers */
  52. var mult = Object.values(this._mods)
  53. .map(function(m) { return Number.isFinite(m.mult) ? m.mult : 0; })
  54. .reduce(function(sum, add) { return sum + add; }, 0);
  55. var add = Object.values(this._mods)
  56. .map(function(m) { return Number.isFinite(m.add) ? m.add : 0; })
  57. .reduce(function(sum, add) { return sum + add; }, 0);
  58. this._current = this.base * (mult + 1) + add;
  59. }
  60. return this._current;
  61. }
  62.  
  63. toString () {
  64. var mult = Object.values(this._mods)
  65. .map(function(m) { return Number.isFinite(m.mult) ? m.mult : 0; })
  66. .reduce(function(sum, add) { return sum + add; }, 0);
  67. var add = Object.values(this._mods)
  68. .map(function(m) { return Number.isFinite(m.add) ? m.add : 0; })
  69. .reduce(function(sum, add) { return sum + add; }, 0);
  70. return this.current.toFixed(2)
  71. + " [" + this.base.toFixed(2)
  72. + " x " + (mult + 1).toFixed(2)
  73. + (add >= 0 ? " + " + add.toFixed(2) : " - " + (-add).toFixed(2))
  74. + "]";
  75. }
  76.  
  77. /* SugarCube support */
  78. clone () {
  79. return Stat.create(this);
  80. }
  81.  
  82. toJSON () {
  83. return JSON.reviveWrapper('setup.Stat.create($ReviveData$)', Object.assign({}, clone(this)));
  84. }
  85. };
  86.  
  87. Stat.prototype.create = function(vals) {
  88. vals = vals || {};
  89. var result = new Stat();
  90. result._base = vals._base;
  91. result._mods = clone(vals._mods);
  92. result._current = vals._current;
  93. return result;
  94. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement