Exit Full View

Games Cupboard / gamescupboard-server / src / main / kotlin / uk / co / nickthecoder / gamescupboard / server / commands / PeelCommand.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.random.Random

/**
 * For the game Banagrams.
 *
 * When a player has used up all their tiles, they shout "Peel!" and all other plays must take an extra tile.
 *
 * This command adds another tile to other players, and NOT the player issuing the Peel command.
 */
class PeelCommand(
    private val fromPoint: SpecialPoint,
    private val toArea: SpecialArea

) : Command(CommandInfo("peel", "Other players take 1 tile from the bunch", 0)) {

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

        val x = toArea.x + Random.nextInt(toArea.width / 2) + toArea.width / 4
        val y = toArea.y + toArea.height / 2

        game.send(ChatMessage(from.id, "Peel", null))
        for (otherPlayer in game.connectedPlayers.values) {
            if (otherPlayer.id != from.id) {
                val card = game.playingObjects().filter { fromPoint.contains(it.x, it.y) }.firstOrNull() ?: return null
                game.send(ChangePrivacy(card.id, otherPlayer.id))
                card.privateToPlayerId = otherPlayer.id

                game.send(MoveObject(card.id, x, y, ChangeZOrder.TOP))
                card.x = x
                card.y = y
            }
        }

        return null
    }
}