package uk.co.nickthecoder.gamescupboard.server
import Message
import PlayerJoined
import PlayerLeft
import io.ktor.websocket.*
import uk.co.nickthecoder.gamescupboard.common.GameObject
import uk.co.nickthecoder.gamescupboard.common.Player
/**
* The data held on the server about a single player or spectator.
*/
class ConnectedPlayer(
val session: WebSocketSession,
val game: Game,
preferredSeatNumber: Int,
wantsToBeASpectator: Boolean
) {
val player: Player
val id: Int get() = player.id
/**
* If a player's connection drops while they are dragging, we need to "end" the dragging
* process from the server end. So we need to keep track of it.
*/
var draggingObject: GameObject? = null
init {
var isSpectator = wantsToBeASpectator
val id = if (wantsToBeASpectator) {
game.generatePlayerIdForSpectator()
} else {
try {
game.generatePlayerIdFromPreferredSeatNumber(preferredSeatNumber)
} catch (e: Exception) {
// There were no seats available, so force them to be a spectator
isSpectator = true
game.generatePlayerIdForSpectator()
}
}
val name = if (isSpectator) "Spectator#$id" else "Player$id"
player = Player(id, name, game.gameVariation.playerColor(id, isSpectator), isSpectator)
}
val isSpectator: Boolean get() = player.isSpectator
fun joinedMessage() = PlayerJoined(player)
fun leftMessage() = PlayerLeft(id)
/**
* Send the message to all other players APART from this one.
* This is commonly used when this player sends a message to the server, and
* it is then "forwarded" to all other players.
*/
suspend fun sendToOthers(frameText: String) {
game.sendToOthers(id, frameText)
}
suspend fun sendToOthers(message: Message) {
game.sendToOthers(id, message)
}
suspend fun send(message: Message) {
session.send(message)
}
}