Roll dice (eg Asphodice) and show outcomes https://rpg.bertieb.org/dice-roller/
Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

dice.ts 9.6 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. const util = require('util');
  2. /**
  3. * Counts the occurrences of a number in an array of numbers
  4. *
  5. * @param inputArray - array of numbers
  6. * @param checkNumber - number to count occurrences of
  7. * @returns number of occurrences
  8. *
  9. */
  10. function countOccurrencesOfNumber(inputArray: Array<number>, checkNumber: number): number {
  11. return inputArray.filter(c => c === checkNumber).length;
  12. }
  13. /**
  14. * Generate a random integer between *1* and `max` (inclusive)
  15. *
  16. * @param max - upper bound of random integer to generate
  17. * @returns random integer
  18. */
  19. function randIntMinOne(max: number): number {
  20. return (1 + Math.floor(Math.random() * Math.floor(max)));
  21. }
  22. interface Dice {
  23. readonly sides: number;
  24. readonly type: string;
  25. }
  26. enum Outcomes {
  27. Success = "Success",
  28. Fail = "Failure",
  29. CritSuccess = "Critical Success",
  30. CritFail = "Critical Failure",
  31. Other = "Something Else"
  32. }
  33. interface DiceResult {
  34. total: number;
  35. dice: Array<number>;
  36. olddice?: Array<number>;
  37. reroll?: boolean;
  38. outcome?: Outcomes;
  39. balance?: number;
  40. }
  41. interface ItemCount {
  42. item: string | number | Outcomes;
  43. count: number;
  44. }
  45. declare let ItemCountSet: Array<ItemCount>;
  46. /**
  47. * Simple d10, implements `roll()`
  48. */
  49. class D10 implements Dice {
  50. sides: number = 10;
  51. type: string = "d10"
  52. roll(numberToRoll: number): DiceResult {
  53. let results: DiceResult = { total: 0, dice: [] };
  54. for (let i = 0; i < numberToRoll; i++) {
  55. results.dice.push(randIntMinOne(this.sides));
  56. }
  57. results.total = results.dice.reduce((acc: number, curr: number) => acc + curr);
  58. return results;
  59. }
  60. [util.inspect.custom](): string {
  61. return this.type;
  62. }
  63. /**
  64. * Roll a specified number of dice
  65. *
  66. * @param numberToRoll - integer number of dice to roll
  67. * @returns DiceResult: .total and .dice (individual dice)
  68. *
  69. * @example Roll 4d10
  70. *
  71. * ```
  72. * D10.roll(4)
  73. * { total: 16, dice [ 3, 5, 6, 2] }
  74. *
  75. */
  76. }
  77. class Asphodice extends D10 {
  78. readonly type: string = "asphodice";
  79. readonly passCrit: number = 10;
  80. readonly failCrit: number = 1;
  81. readonly successCutOff: number = 6; // this or larger
  82. /**
  83. * Re-roll the high dice (ie >= 6) for a chance of failure
  84. * happens on eg 1
  85. *
  86. * @remarks
  87. * Basically we want to remove a die from the original result,
  88. * as long as that die isn't a 10, and is above the
  89. * cutoff. So we filter to get rerollCandidates, find the
  90. * highest value and get the index of that value in the
  91. * original results. We use that to splice() out (remove) that
  92. * value and push the rerolled dice onto the modified array
  93. *
  94. * @param rerollDice
  95. * @returns rerollOutcome
  96. *
  97. * @example Re-roll High Dice on 1
  98. * ```
  99. * rerollHighDice([8, 1, 1, 4, 7, 10]);
  100. * [ 1, 1, 4, 7, 10, 6]
  101. * ```
  102. *
  103. * ## Explanation
  104. *
  105. * - first filter dice to be not 10 and >= 6 (see {@link Asphodice.successCutOff})
  106. * - rerollCandidates are [8, 7]
  107. * - max([8, 7] = 8
  108. * - indexOf(8) = 0
  109. * - rerollResult = 6 (see {@link randIntMinOne()})
  110. * - `splice()` replaced dice out of array = [ 1, 1, 4, 7, 10 ]
  111. * - `push()` new dice = [ 1, 1, 4, 7, 10, 6]
  112. */
  113. rerollHighDice (rerollDice: Array<number>): Array<number> {
  114. let rerollCandidates: Array<number> = rerollDice.filter(die => (die < 10 && die >= this.successCutOff));
  115. let maxValue: number = Math.max(...rerollCandidates);
  116. let maxIndex = rerollDice.indexOf(maxValue);
  117. let rerollResult: number = randIntMinOne(this.sides);
  118. rerollDice.splice(maxIndex, 1);
  119. rerollDice.push(rerollResult);
  120. return rerollDice
  121. }
  122. /**
  123. * Re-roll low dice (ie < 6) for chance of success (ie getting >= 6)
  124. *
  125. * @remarks
  126. *
  127. * Generally happens on a 10.
  128. *
  129. * @see {@link Asphodice.rerollHighDice} for a fuller explanation
  130. * for what process in opposite direction
  131. */
  132. rerollLowDice (rerollDice: Array<number>): Array<number> {
  133. let rerollCandidates: Array<number> = rerollDice.filter(die => (die > 1 && die < this.successCutOff));
  134. let minValue: number = Math.min(...rerollCandidates);
  135. let minIndex = rerollDice.indexOf(minValue);
  136. let rerollResult: number = randIntMinOne(this.sides);
  137. rerollDice.splice(minIndex, 1);
  138. rerollDice.push(rerollResult);
  139. return rerollDice
  140. }
  141. /**
  142. * Used to determine if all dice are above Asphodice.successCutOff
  143. *
  144. * @param checkDice - Array of Dice to test
  145. *
  146. * @see {@link Asphodice.roll} where it is used to determine if
  147. * a re-roll can be skipped
  148. *
  149. * @see {@link allBelowCutOff} also.
  150. */
  151. allAboveCutOff (checkDice: Array<number>): boolean {
  152. // if filtering those *below* cutoff results in empty set
  153. // then all must be above cutoff
  154. return ((checkDice.filter(die => die < this.successCutOff).length == 0));
  155. }
  156. /**
  157. * Used to determine if all dice are below Asphodice.successCutOff
  158. *
  159. * @param checkDice - Array of Dice to test
  160. *
  161. * @see {@link Asphodice.roll} where it is used to determine if
  162. * a re-roll can be skipped
  163. *
  164. * @see {@link allAboveCutOff} also.
  165. */
  166. allBelowCutOff (checkDice: Array<number>): boolean {
  167. // if filtering those *above or equal to* cutoff results in empty set
  168. // then all must be below cutoff
  169. return ((checkDice.filter(die => die >= this.successCutOff).length == 0));
  170. }
  171. /**
  172. * Determine balance of outcomes - ie successes minus failures
  173. *
  174. * @remarks
  175. *
  176. * Success = 1, failure = -1
  177. *
  178. * Particularly for Asphodice, we aren't terribly concerned with the
  179. * numeric sum total of the dice values, we are more concerned with
  180. * the overall outcome (see {@link Outcomes}) and for narrative purposes
  181. * perhaps the balance of outcomes; for example, 1 success may be
  182. * narrated differently than 4 successes.
  183. *
  184. * **Special note**: This ignores crits! **End special note**
  185. *
  186. * TODO: Special consideration of a single die roll (?)
  187. *
  188. * @param resultDice - the final dice after any re-rolls
  189. * @returns Single positive/negative number with balance of roll outcomes
  190. *
  191. * @example Count Outcomes of 5 Dice
  192. * ```
  193. * countOutcomeBalance([ 7, 4, 4, 9, 1 ])
  194. * -1
  195. * ```
  196. *
  197. * - 7 and 9 are above successCutOff → +2
  198. * - 4, 4, 1 are below successCutOff → -3
  199. */
  200. countOutcomeBalance (resultDice: Array<number>): number{
  201. // fun with ternary operators
  202. return resultDice.reduce(
  203. (acc: number, curr: number) =>
  204. { return (curr < this.successCutOff) ? acc - 1 : acc + 1 },
  205. 0);
  206. // PS also good practice to supply initialValue (0)
  207. }
  208. /**
  209. * Determine and return outcome of roll
  210. *
  211. * @remarks
  212. *
  213. * Determines outcome as in "Success", "Failure", etc. Assumes that `resultDice` is
  214. * the 'final' result after any rerolls.
  215. *
  216. * @see {@link:countOutcomeBalance}
  217. */
  218. checkOutcome (resultDice: Array<number>): Outcomes{
  219. // Note: currently, one success = Success, regardless of number of failures
  220. // TODO: Critical failures, once decided with Mao
  221. if (this.allBelowCutOff(resultDice)) {
  222. return Outcomes.Fail;
  223. } else {
  224. return Outcomes.Success;
  225. }
  226. }
  227. /**
  228. * Roll an Asphodie or Asphodice
  229. *
  230. * @param numToRoll
  231. * @returns a {@link DiceResult} with additional properties:
  232. * - reroll: boolean - whether we rerolled
  233. * - olddice: Array - original roll
  234. * - dice: Array - final outcome
  235. * - balance: number - +/- of outcomes (successes/failures)
  236. */
  237. /**
  238. * Determines if a reroll is needed
  239. *
  240. * @remarks
  241. *
  242. * In some cases we don't reroll:
  243. * - reroll dice cancel each other out
  244. * - all are above cutoff (=> auto-success -- NB TODO crits)
  245. * - all below cutoff
  246. */
  247. rerollNeeded(resultDice: Array<number>): boolean{
  248. // 1. if no re-rolls we can finish here
  249. if (!(resultDice.includes(this.passCrit) || resultDice.includes(this.failCrit))) {
  250. // results.total = results.dice.reduce((acc: number, curr: number) => acc + curr);
  251. return false;
  252. }
  253. // count successes and fails
  254. let rerollGood = countOccurrencesOfNumber(resultDice, this.passCrit);
  255. let rerollBad = countOccurrencesOfNumber(resultDice, this.failCrit);
  256. // 2. only reroll if they don't cancel each other out
  257. if (rerollGood == rerollBad) {
  258. // console.log("Good = Bad, no need to reroll");
  259. return false;
  260. // results.total = results.dice.reduce((acc: number, curr: number) => acc + curr);
  261. }
  262. // 3. If all dice are above/below cutoff we don't need to reroll
  263. if (this.allAboveCutOff(resultDice)) {
  264. console.log("All above cutoff, auto-success", resultDice);
  265. return false;
  266. } else if (this.allBelowCutOff(resultDice)) {
  267. console.log("All below cutoff, auto-fail", resultDice);
  268. return false;
  269. }
  270. // We should re-roll
  271. return true;
  272. }
  273. roll (numToRoll: number): DiceResult {
  274. let results: DiceResult = { total: 0, dice: [] };
  275. // Initial roll
  276. for (let i = 0; i < numToRoll; i++) {
  277. results.dice.push(randIntMinOne(this.sides));
  278. }
  279. // Reroll?
  280. if (this.rerollNeeded(results.dice)) {
  281. // Reminder: arr1 = arr2 is a copy by reference!
  282. let olddice = results.dice.slice();
  283. let rerollGood = countOccurrencesOfNumber(olddice, this.passCrit);
  284. let rerollBad = countOccurrencesOfNumber(olddice, this.failCrit);
  285. if (rerollGood > rerollBad) {
  286. // Re-roll low (<6) dice for chance of success
  287. results.dice = this.rerollLowDice(results.dice);
  288. } else {
  289. // Re-roll high (>=6) dice for chance of failure
  290. results.dice = this.rerollHighDice(results.dice);
  291. }
  292. results.olddice = olddice;
  293. results.reroll = true;
  294. }
  295. results.balance = this.countOutcomeBalance(results.dice);
  296. results.total = results.dice.reduce((acc: number, curr: number) => acc + curr);
  297. // Finally, once we're done with rerolls etc, determine outcome
  298. results.outcome = this.checkOutcome(results.dice);
  299. return results;
  300. }
  301. }
  302. let asphodice: Asphodice = new Asphodice();
  303. let number: number = 4;
  304. for (let i = 0; i < 10; i++) {
  305. console.log("--------------------");
  306. console.log("Rolling", number, asphodice);
  307. console.log(asphodice.roll(4));
  308. }