Merge pull request 'caps the number of allowed dice' (#39) from limit-number-of-diece into main
All checks were successful
CI / deploy (push) Successful in 6m6s

Reviewed-on: #39
This commit is contained in:
arindy 2025-02-22 14:09:17 +01:00
commit 741276e477
2 changed files with 24 additions and 6 deletions

View File

@ -42,6 +42,8 @@ services:
restart: always
ports:
- "8080:8080"
environment:
DICE_LIMIT: 30 # OPTIONAL: amount of dice allowed to roll (default: 30)
```
Run the container with:
```bash

View File

@ -14,12 +14,19 @@ import jakarta.ws.rs.sse.OutboundSseEvent
import jakarta.ws.rs.sse.Sse
import jakarta.ws.rs.sse.SseBroadcaster
import jakarta.ws.rs.sse.SseEventSink
import org.eclipse.microprofile.config.inject.ConfigProperty
import java.util.Optional
import java.util.UUID
private const val LIMIT = 30
@Path("/dice/{id}")
@ApplicationScoped
final class DiceResource(@Context val sse: Sse) {
@ConfigProperty(name = "dice.limit")
private lateinit var diceLimit: Optional<Int>
private var eventBuilder: OutboundSseEvent.Builder = sse.newEventBuilder()
private var sseBroadcasters: MutableMap<String, SseBroadcaster> = HashMap()
@ -30,15 +37,24 @@ final class DiceResource(@Context val sse: Sse) {
data.user = id.split(":")[1]
val results = ArrayList<Results>()
var numberOfDice = 0
data.command.split(" ", "&", "and").filter { it.isNotEmpty() }.map { it.trim() }.toTypedArray<String>().forEach { command ->
val dice = command.split("d")
val result = IntArray(dice[0].toInt())
val sides = dice[1].split("+", "-")
val modifier = if (dice[1].contains("+")) sides[1].toInt() else if (dice[1].contains("+")) -1 * sides[1].toInt() else 0
repeat(dice[0].toInt()) { index ->
result[index] = (Math.random() * sides[0].toInt() + 1).toInt()
var amount = dice[0].toInt()
val limit = diceLimit.orElse(LIMIT)
if (limit < numberOfDice + amount) {
amount = limit - numberOfDice
}
numberOfDice += amount
if (amount > 0) {
val result = IntArray(amount)
val sides = dice[1].split("+", "-")
val modifier = if (dice[1].contains("+")) sides[1].toInt() else if (dice[1].contains("+")) -1 * sides[1].toInt() else 0
repeat(amount) { index ->
result[index] = (Math.random() * sides[0].toInt() + 1).toInt()
}
results.add(Results(sides[0].toInt(), modifier, result.sum() + modifier, result.map { Roll(it) }.toTypedArray()))
}
results.add(Results(sides[0].toInt(), modifier, result.sum() + modifier, result.map { Roll(it) }.toTypedArray()))
}
val map = results.map { r ->
"${r.rolls.size}d${r.sides}@${