Schafkopf-Server/Sources/App/Model/Players/Player.swift
2021-12-09 11:11:17 +01:00

64 lines
1.2 KiB
Swift

import Foundation
import WebSocketKit
protocol Player: AnyObject {
var name: String { get }
var socket: WebSocket? { get set }
var playedCard: Card? { get }
var actions: [PlayerAction] { get }
var cards: [PlayableCard] { get }
}
extension Player {
// MARK: Connection
/// Indicate that the player is connected when at a table
var isConnected: Bool {
guard let socket = socket else {
return false
}
guard !socket.isClosed else {
self.socket = nil
return false
}
return true
}
func connect(using socket: WebSocket) {
_ = self.socket?.close()
self.socket = socket
}
func disconnect() -> Bool {
guard let socket = socket else {
return false
}
do {
try socket.close().wait()
} catch {
print("Failed to close socket for player: \(name): \(error)")
}
self.socket = nil
return true
}
func send(_ info: TableInfo) {
try? socket?.send(encodeJSON(info))
}
// MARK: Actions
func canPerform(_ action: PlayerAction) -> Bool {
actions.contains(action)
}
}