Roll dice (eg Asphodice) and show outcomes https://rpg.bertieb.org/dice-roller/
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

dice.ts 11 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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. export 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. * 'Cancel out' reroll dice
  229. *
  230. * @remarks
  231. *
  232. * Helper function.
  233. *
  234. * **In the context of deciding a reroll only**, the reroll dice can
  235. * 'cancel' each other out. The dice themselves remain intact for the
  236. * purposes of determining the final outcome.
  237. *
  238. * @returns Filtered dice
  239. */
  240. cancelRerollDice (resultDice: Array<number>): Array<number> {
  241. // Naive approach for now:
  242. // - count 10s and 1s
  243. // - remove all 10s and 1s from input array
  244. // - re-add 10s/1s after 'cancelling'
  245. let tens = 0;
  246. let ones = 0;
  247. // count
  248. for (let die of resultDice) {
  249. if (die === 10) {
  250. tens++;
  251. } else if (die === 1) {
  252. ones++;
  253. }
  254. }
  255. // remove any reroll dice
  256. let outputDice = resultDice.filter( die => (die != 1 && die != 10) );
  257. let balance = tens - ones;
  258. if (balance < 0) {
  259. // add balance of ones
  260. outputDice.push(...Array(Math.abs(balance)).fill(1));
  261. } else if (balance > 0) {
  262. // add balance of tens
  263. outputDice.push(...Array(Math.abs(balance)).fill(10));
  264. }
  265. return outputDice;
  266. }
  267. /**
  268. * Determines if a reroll is needed
  269. *
  270. * @remarks
  271. *
  272. * In some cases we don't reroll:
  273. * - reroll dice cancel each other out
  274. * - all are above cutoff (=> auto-success -- NB TODO crits)
  275. * - all below cutoff
  276. */
  277. rerollNeeded(resultDice: Array<number>): boolean{
  278. // 'Cancel out' matching re-roll dice
  279. let cancelledDice = this.cancelRerollDice(resultDice);
  280. // 1. if no re-rolls we can finish here
  281. if (!(cancelledDice.includes(this.passCrit) || resultDice.includes(this.failCrit))) {
  282. // results.total = results.dice.reduce((acc: number, curr: number) => acc + curr);
  283. return false;
  284. }
  285. // count successes and fails
  286. let rerollGood = countOccurrencesOfNumber(cancelledDice, this.passCrit);
  287. let rerollBad = countOccurrencesOfNumber(cancelledDice, this.failCrit);
  288. // 2. only reroll if they don't cancel each other out
  289. if (rerollGood == rerollBad) {
  290. // console.log("Good = Bad, no need to reroll");
  291. return false;
  292. // results.total = results.dice.reduce((acc: number, curr: number) => acc + curr);
  293. }
  294. // 3. If all dice are above/below cutoff we don't need to reroll
  295. if (this.allAboveCutOff(cancelledDice)) {
  296. console.log("All above cutoff, auto-success", cancelledDice);
  297. return false;
  298. } else if (this.allBelowCutOff(cancelledDice)) {
  299. console.log("All below cutoff, auto-fail", cancelledDice);
  300. return false;
  301. }
  302. // We should re-roll
  303. return true;
  304. }
  305. /**
  306. * Roll an Asphodie or Asphodice
  307. *
  308. * @param numToRoll
  309. * @returns a {@link DiceResult} with additional properties:
  310. * - reroll: boolean - whether we rerolled
  311. * - olddice: Array - original roll
  312. * - dice: Array - final outcome
  313. * - balance: number - +/- of outcomes (successes/failures)
  314. */
  315. roll (numToRoll: number): DiceResult {
  316. let results: DiceResult = { total: 0, dice: [] };
  317. // Initial roll
  318. for (let i = 0; i < numToRoll; i++) {
  319. results.dice.push(randIntMinOne(this.sides));
  320. }
  321. // Reroll?
  322. if (this.rerollNeeded(results.dice)) {
  323. // Reminder: arr1 = arr2 is a copy by reference!
  324. let olddice = results.dice.slice();
  325. let rerollGood = countOccurrencesOfNumber(olddice, this.passCrit);
  326. let rerollBad = countOccurrencesOfNumber(olddice, this.failCrit);
  327. if (rerollGood > rerollBad) {
  328. // Re-roll low (<6) dice for chance of success
  329. results.dice = this.rerollLowDice(results.dice);
  330. } else {
  331. // Re-roll high (>=6) dice for chance of failure
  332. results.dice = this.rerollHighDice(results.dice);
  333. }
  334. results.olddice = olddice;
  335. results.reroll = true;
  336. }
  337. results.balance = this.countOutcomeBalance(results.dice);
  338. results.total = results.dice.reduce((acc: number, curr: number) => acc + curr);
  339. // Finally, once we're done with rerolls etc, determine outcome
  340. results.outcome = this.checkOutcome(results.dice);
  341. return results;
  342. }
  343. }
  344. let asphodice: Asphodice = new Asphodice();
  345. let number: number = 4;
  346. for (let i = 0; i < 10; i++) {
  347. console.log("--------------------");
  348. console.log("Rolling", number, asphodice);
  349. console.log(asphodice.roll(4));
  350. }