dice.js 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. const diceRegex = () => /\b(\d*)[dD](\d+)\b(?:\s?([+-])\s?(\d+))?/g
  2. const rerollRegex = () => /\b(reroll|re-roll)\s+((?:(?:\S*|\d+s|\d+'s|\d+)\s*)+)/
  3. const numberRegex = () => /\b(one|two|three|four|five|six|seven|eight|nine|ten|ones|twos|threes|fours|fives|sixes|sevens|eights|nines|tens|one's|two's|three's|four's|five's|seven's|eight's|nine's|ten's|\d+)\b/gi
  4. const advRegex = () => /\b(disadvantage|advantage)\b/i
  5. const percentRegex = () => /\b(percentile|percentiles|percent)\b/i
  6. const dicebotRegex = () => /\b(dicebot|dice bot)\b/i
  7. const unicoder = require('./unicoder')
  8. const d6 = {
  9. stringify: n => unicoder.codesets.dice[n],
  10. total: (ns, bonus) => ns.reduce((a, b) => a + b, bonus).toString()
  11. }
  12. const coin = {
  13. stringify: (n, i, total) => `${n === 1 ? unicoder.codesets.circles.red : n === 2 ? unicoder.codesets.circles.blue : unicoder.codesets.circles.black}${total === 1 ? (n === 1 ? ' Heads' : n === 2 ? ' Tails' : ' Sides') : ''}`,
  14. total: ns => {
  15. const heads = ns.filter(x => x === 1).length
  16. const tails = ns.filter(x => x === 2).length
  17. if (heads === 1 && tails === 0) return 'Heads'
  18. if (heads === 0 && tails === 1) return 'Tails'
  19. if (heads === 0 && tails > 0) return `${tails} Tails and no Heads`
  20. if (heads > 0 && tails === 0) return `${heads} Heads and no Tails`
  21. if (heads > 0 && tails > 0) return `${heads} Heads and ${tails} Tails`
  22. return 'The coin disappears'
  23. }
  24. }
  25. const d10 = {
  26. stringify: (n, i, total, { percent = false } = {}) => {
  27. if (total === 2 && percent) {
  28. if (i === 0) {
  29. return n === 10 ? '00' : `${n}0`
  30. } else {
  31. return n === 10 ? '0' : n.toString()
  32. }
  33. } else {
  34. return unicoder.codesets.negRound[n === 10 ? '0' : n.toString()]
  35. }
  36. },
  37. total: (ns, bonus, { percent = false } = {}) => {
  38. if (ns.length === 2 & percent) {
  39. if (ns[0] === 0 && ns[1] === 0) return '100'
  40. return ((ns[0] === 10 ? 0 : ns[0]) * 10 + (ns[1] % 10)).toString()
  41. }
  42. return ns.reduce((a, b) => a + b, bonus).toString()
  43. },
  44. bonusText: (x) => {
  45. const {percent = false, values = []} = x || {}
  46. if (values.length === 2 && !percent) return '_Did you mean "percentile"?_'
  47. }
  48. }
  49. const d20 = {
  50. stringify: n => unicoder.codesets.negRound[n],
  51. total: (ns, bonus) => ns.reduce((a, b) => a + b, bonus).toString()
  52. }
  53. const ascii = {
  54. stringify: n => n.toString(),
  55. total: (ns, bonus) => ns.reduce((a, b) => a + b, bonus).toString()
  56. }
  57. class Roll {
  58. constructor(roll) {
  59. if (roll) Object.assign(this, roll)
  60. }
  61. value() {
  62. return this.values.reduce((a, b) => a + b, this.bonus || 0)
  63. }
  64. toString() {
  65. let str = this.values.map((val, i) => this.formatter && this.formatter.stringify ? this.formatter.stringify(val, i, this.values.length, this) : `[${val}]`).join(' + ')
  66. if (this.bonus < 0) {
  67. str += ` - ${Math.abs(this.bonus)}`
  68. } else if (this.bonus > 0) {
  69. str += ` + ${this.bonus}`
  70. }
  71. if (this.values.length > 1 || this.bonus) {
  72. str += ` = ${this.formatter && this.formatter.total ? this.formatter.total(this.values, this.bonus || 0, this) : this.value()}`
  73. }
  74. if (this.rerolls === 1) {
  75. str += ` with 1 reroll`
  76. } else if (this.rerolls > 1) {
  77. str += ` with ${this.rerolls} rerolls`
  78. }
  79. return str
  80. }
  81. }
  82. class BadRoll extends Roll {
  83. constructor(text) {
  84. super({text})
  85. }
  86. toString() {
  87. return this.text
  88. }
  89. }
  90. const random = (rng, n) => Math.floor(rng() * n) + 1
  91. class Dice {
  92. constructor(dice) {
  93. if (dice) Object.assign(this, dice)
  94. if (!this.formatter) {
  95. if (this.sides === 2) this.formatter = coin
  96. else if (this.sides === 6) this.formatter = d6
  97. else if (this.sides === 10) this.formatter = d10
  98. else if (this.sides <= 20) this.formatter = d20
  99. else this.formatter = ascii
  100. }
  101. if (!this.rng) this.rng = () => Math.random()
  102. }
  103. roll() {
  104. if (this.count > 100) return new BadRoll(`I lost count rolling ${this}`)
  105. if (this.sides > 256) return new BadRoll(`The faces are too small to read on ${this}`)
  106. if (this.count === 0) return new BadRoll(`I finished before I started rolling ${this}`)
  107. if (this.sides === 0) return new BadRoll(`I lost my grip on ${this}`)
  108. if (this.sides === 1) return new BadRoll(`The mobius ${this} never stopped rolling`)
  109. if (this.bonusSign === '-' && this.bonus > this.sides) return new BadRoll(`It doesn't seem fair to roll ${this}`)
  110. let values = []
  111. for (let i = 0; i < this.count; i++) {
  112. if (this.modifier === 'advantage') {
  113. values.push(Math.max(random(this.rng, this.sides), random(this.rng, this.sides)))
  114. } else if (this.modifier === 'disadvantage') {
  115. values.push(Math.min(random(this.rng, this.sides), random(this.rng, this.sides)))
  116. } else {
  117. values.push(random(this.rng, this.sides))
  118. }
  119. }
  120. let bonus = 0
  121. switch (this.bonusSign) {
  122. case '-': bonus = -this.bonus; break
  123. case '+': bonus = this.bonus; break
  124. }
  125. let rerolls = 0
  126. for (let i = 0; i < 10; i++) {
  127. let foundAny = false
  128. for (let d = 0; d < values.length; d++) {
  129. const v = values[d]
  130. if (this.rerollNumbers && this.rerollNumbers.includes(v)) {
  131. values[d] = random(this.rng, this.sides)
  132. foundAny = true
  133. rerolls++
  134. }
  135. }
  136. if (!foundAny) break
  137. }
  138. return new Roll({
  139. values,
  140. bonus,
  141. rerolls,
  142. percent: this.percent,
  143. formatter: this.formatter
  144. })
  145. }
  146. toString() {
  147. let str =
  148. this.sides === 2
  149. ? (
  150. this.count === 1 ? 'a coin' : `${this.count} coins`
  151. )
  152. : (this.count === 2 && this.percent)
  153. ? 'percentile dice'
  154. :`${this.count}d${this.sides}`
  155. if (this.bonusSign) {
  156. str += this.bonusSign + this.bonus
  157. }
  158. if (this.modifier) {
  159. str += ` with ${this.modifier}`
  160. }
  161. if (this.rerollNumbers && this.rerollNumbers.length) {
  162. if (this.rerollNumbers.length === 1) {
  163. str += ` and reroll ${this.rerollNumbers[0]}'s`
  164. } else {
  165. str += ` and reroll ${this.rerollNumbers.slice(0, this.rerollNumbers.length - 1).join(`'s, `)}'s, and ${this.rerollNumbers[this.rerollNumbers.length - 1]}'s`
  166. }
  167. }
  168. return str
  169. }
  170. }
  171. Dice.parse = (str, opts) => {
  172. const rrRegex = rerollRegex()
  173. const rerolls = []
  174. const reroll = rrRegex.exec(str)
  175. const rerollNumbers = []
  176. if (reroll) {
  177. const nRegex = numberRegex()
  178. while (number = nRegex.exec(str)) {
  179. switch (number[1]) {
  180. case 'ones':
  181. case 'one':
  182. rerollNumbers.push(1)
  183. break
  184. case 'twos':
  185. case 'two':
  186. rerollNumbers.push(2)
  187. break
  188. case 'threes':
  189. case 'three':
  190. rerollNumbers.push(3)
  191. break
  192. case 'fours':
  193. case 'four':
  194. rerollNumbers.push(4)
  195. break
  196. case 'fives':
  197. case 'five':
  198. rerollNumbers.push(5)
  199. break
  200. case 'sixes':
  201. case 'six':
  202. rerollNumbers.push(6)
  203. break
  204. case 'sevens':
  205. case 'seven':
  206. rerollNumbers.push(7)
  207. break
  208. case 'eights':
  209. case 'eight':
  210. rerollNumbers.push(8)
  211. break
  212. case 'nines':
  213. case 'nine':
  214. rerollNumbers.push(9)
  215. break
  216. case 'tens':
  217. case 'ten':
  218. rerollNumbers.push(10)
  219. break
  220. default:
  221. const n = parseFloat(number)
  222. if (!isNaN(n)) {
  223. rerollNumbers.push(n)
  224. }
  225. }
  226. }
  227. }
  228. const aRegex = advRegex()
  229. const ad = aRegex.exec(str)
  230. const dicebot = dicebotRegex().test(str)
  231. const modifier = ad ? (
  232. ad[1].toLowerCase()[0] === 'a' ? 'advantage' : 'disadvantage'
  233. ) : null
  234. const percent = percentRegex().test(str)
  235. const regex = diceRegex()
  236. const ret = []
  237. let dice
  238. if (percent) {
  239. ret.push(new Dice({
  240. count: 2,
  241. sides: 10,
  242. percent: true
  243. }))
  244. }
  245. while (dice = regex.exec(str)) {
  246. ret.push(new Dice({
  247. match: dice,
  248. count: dice[1] === '' ? 1 : parseFloat(dice[1]),
  249. sides: parseFloat(dice[2]),
  250. bonusSign: dice[3] || null,
  251. bonus: dice[4] === undefined ? null : parseFloat(dice[4]),
  252. rerollNumbers,
  253. modifier,
  254. percent,
  255. dicebot,
  256. rng: opts && opts.rng
  257. }))
  258. }
  259. return ret
  260. }
  261. Dice.chat = (chat, opts) => {
  262. const dice = Dice.parse(chat, opts)
  263. if (dice.length) {
  264. const diceStrings = dice.map(x => x.toString())
  265. if (diceStrings.length > 1) {
  266. diceStrings[diceStrings.length - 1] = `and ${diceStrings[diceStrings.length - 1]}`
  267. }
  268. const isCoin = dice.length === 1 && dice[0].sides === 2
  269. const rollingString = `${isCoin ? 'Flipping' : 'Rolling'} ${diceStrings.join(', ')}...`
  270. const rolls = dice.map(die => die.roll())
  271. const rollsStrings = rolls.map(roll => roll.toString())
  272. const bonusString = rolls
  273. .filter(x => x.formatter && x.formatter.bonusText)
  274. .map(x => x.formatter.bonusText(x))
  275. .filter(x => x)
  276. .map(x => '\n' + x)
  277. .join('')
  278. return `${rollingString} ${rollsStrings.join(', ')}.${bonusString}`
  279. }
  280. }
  281. module.exports = {
  282. Dice,
  283. Roll,
  284. diceRegex,
  285. rerollRegex,
  286. advRegex
  287. }