Roll dice (eg Asphodice) and show outcomes https://rpg.bertieb.org/dice-roller/
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 

387 строки
10 KiB

  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. export 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. return false;
  283. }
  284. // count successes and fails
  285. let rerollGood = countOccurrencesOfNumber(cancelledDice, this.passCrit);
  286. let rerollBad = countOccurrencesOfNumber(cancelledDice, this.failCrit);
  287. // 2. only reroll if they don't cancel each other out
  288. if (rerollGood == rerollBad) {
  289. return false;
  290. }
  291. // 3. If all dice are above/below cutoff we don't need to reroll
  292. if (this.allAboveCutOff(cancelledDice) || this.allBelowCutOff(cancelledDice)) {
  293. return false;
  294. }
  295. // We should re-roll
  296. return true;
  297. }
  298. /**
  299. * Roll an Asphodie or Asphodice
  300. *
  301. * @param numToRoll
  302. * @returns a {@link DiceResult} with additional properties:
  303. * - reroll: boolean - whether we rerolled
  304. * - olddice: Array - original roll
  305. * - dice: Array - final outcome
  306. * - balance: number - +/- of outcomes (successes/failures)
  307. */
  308. roll (numToRoll: number): DiceResult {
  309. let results: DiceResult = { total: 0, dice: [] };
  310. // Initial roll
  311. for (let i = 0; i < numToRoll; i++) {
  312. results.dice.push(randIntMinOne(this.sides));
  313. }
  314. // Reroll?
  315. if (this.rerollNeeded(results.dice)) {
  316. // Reminder: arr1 = arr2 is a copy by reference!
  317. let olddice = results.dice.slice();
  318. let rerollGood = countOccurrencesOfNumber(olddice, this.passCrit);
  319. let rerollBad = countOccurrencesOfNumber(olddice, this.failCrit);
  320. if (rerollGood > rerollBad) {
  321. // Re-roll low (<6) dice for chance of success
  322. results.dice = this.rerollLowDice(results.dice);
  323. } else {
  324. // Re-roll high (>=6) dice for chance of failure
  325. results.dice = this.rerollHighDice(results.dice);
  326. }
  327. results.olddice = olddice;
  328. results.reroll = true;
  329. }
  330. results.balance = this.countOutcomeBalance(results.dice);
  331. results.total = results.dice.reduce((acc: number, curr: number) => acc + curr);
  332. // Finally, once we're done with rerolls etc, determine outcome
  333. results.outcome = this.checkOutcome(results.dice);
  334. return results;
  335. }
  336. }
  337. let asphodice: Asphodice = new Asphodice();
  338. let number: number = 4;
  339. for (let i = 0; i < 10; i++) {
  340. console.log("--------------------");
  341. console.log("Rolling", number, asphodice);
  342. console.log(asphodice.roll(4));
  343. }