Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix dice roll calculation for multiple dice #180

Merged
merged 1 commit into from
Sep 6, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,17 @@ interface Expression : Parcelable {

@Parcelize
@Immutable
private data class DiceRoll(private val sides: Int) : Expression {
override fun evaluate() = Dice(sides).roll()
private data class DiceRoll(
private val count: Int,
private val sides: Int,
) : Expression {
override fun evaluate(): Int {
val dice = Dice(sides)

return (0 until count).sumOf { dice.roll() }
}
override fun isDeterministic() = false
override fun toString(): String = "d$sides"
override fun toString(): String = "${count}d$sides"
}

@Parcelize
Expand Down Expand Up @@ -148,8 +155,8 @@ private class RollExpressionGrammar(val constants: Map<String, Int>) : Grammar<E
val comma by literalToken(",")

private val diceTerm by dice use {
val (multiplier, sides) = text.split('d')
Multiplication(IntegerLiteral(multiplier.toInt()), DiceRoll(sides.toInt()))
val (count, sides) = text.split('d')
DiceRoll(count.toInt(), sides.toInt())
}

val term by diceTerm or
Expand Down
Loading