Roll dice (eg Asphodice) and show outcomes https://rpg.bertieb.org/dice-roller/
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

dice.ts 8.5 KiB

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