Exit Full View

Games Cupboard / gamescupboard-server / src / main / kotlin / uk / co / nickthecoder / gamescupboard / server / commands / RollDiceCommand.kt

package uk.co.nickthecoder.gamescupboard.server.commands

import ChangeImage
import uk.co.nickthecoder.gamescupboard.common.CommandInfo
import uk.co.nickthecoder.gamescupboard.common.MultipleGridImageObject
import uk.co.nickthecoder.gamescupboard.server.ConnectedPlayer
import kotlin.random.Random

class RollDiceCommand(
    val diceName: String,
    val count: Int,
    commandName: String = "roll"
) : Command(CommandInfo(commandName, "Roll the dice")) {
    override suspend fun run(from: ConnectedPlayer, parameters: List<String>): String? {
        val game = from.game

        for (i in 0 until count) {
            val dice = game.findObjectByName("$diceName$i")
            if (dice is MultipleGridImageObject) {
                dice.imageNumber = Random.nextInt(6) + 1
                game.send(ChangeImage(dice.id, dice.imageNumber))
            }
        }

        return null
    }
}