Exit Full View

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

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

import AddObjects
import RemoveObjects
import uk.co.nickthecoder.gamescupboard.common.CommandInfo
import uk.co.nickthecoder.gamescupboard.common.SpecialPoint
import uk.co.nickthecoder.gamescupboard.server.ConnectedPlayer
import uk.co.nickthecoder.gamescupboard.server.Game
import kotlin.random.Random

class ShuffleCommand(
    private val deck: SpecialPoint

) : Command(CommandInfo("shuffle", "Shuffle the deck"), isInitialiser = true) {

    override suspend fun run(from: ConnectedPlayer, parameters: List<String>): String? {
        val game = from.game
        shuffleCardsAtPoint(game, deck)
        return null
    }
}

suspend fun shuffleCardsAtPoint(game: Game, deck: SpecialPoint) {
    val cards = game.playingObjects().filter { deck.contains(it.x, it.y) }

    val shuffled = cards
        .map { Pair(it, Random.nextDouble()) }
        .sortedBy { it.second }
        .map { it.first }

    // Update the z order on the server
    game.remove(cards)
    game.add(shuffled)

    // Update the z order on the clients
    game.send(RemoveObjects(cards.map { it.id }))
    game.send(AddObjects(shuffled))
}