Exit Full View

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

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

import ChangePrivacy
import ChatMessage
import MoveObject
import uk.co.nickthecoder.gamescupboard.common.CommandInfo
import uk.co.nickthecoder.gamescupboard.common.SpecialArea
import uk.co.nickthecoder.gamescupboard.common.SpecialPoint
import uk.co.nickthecoder.gamescupboard.server.ConnectedPlayer
import kotlin.math.min

class TakeCommand(
    private val fromPoint: SpecialPoint,
    private val toArea: SpecialArea,
    private val spreadX: Int

) : Command(CommandInfo("take", "Take cards from the deck", 1, parameterHelp = listOf("Number of cards"))) {

    override suspend fun run(from: ConnectedPlayer, parameters: List<String>): String? {
        val count = parameters[0].toIntOrNull() ?: return "Expected an integer"
        val game = from.game

        val actualSpread = min(spreadX.toDouble(), (toArea.width - spreadX) / count.toDouble()).toInt()
        val y = toArea.y + toArea.height / 2
        val left = toArea.x + toArea.width / 2 - (spreadX * count) / 2

        game.send(ChatMessage(from.id, "Taking $count cards", null))
        val cards = game.playingObjects().filter { fromPoint.contains(it.x, it.y) }.take(count)
        for ((i, card) in cards.withIndex()) {
            game.send(ChangePrivacy(card.id, from.id))
            card.privateToPlayerId = from.id

            val x = left + i * actualSpread
            game.send(MoveObject(card.id, x, y, ChangeZOrder.TOP))
            card.x = x
            card.y = y

            // NOTE, If the card is face down (as is typical when taking a card from the deck),
            // then the card will REMAIN face down on the server, but the owning player's client
            // will turn it face up (for them only) when it receives the MoveObject message.
        }

        return null
    }
}