Schafkopf-Server/Sources/App/Model/Tables/DealingTable.swift

66 lines
2.2 KiB
Swift
Raw Normal View History

import Foundation
2021-12-18 15:08:43 +01:00
final class DealingTable: AbstractTable<DealingPlayer> {
init(table: WaitingTable) {
let cards = Dealer.dealFirstCards()
let players = table.players.map(DealingPlayer.init)
for (index, player) in players.enumerated() {
2021-12-18 15:08:43 +01:00
player.cards = cards[index]
}
2021-12-18 15:08:43 +01:00
super.init(table: table, players: players)
}
2021-12-18 15:08:43 +01:00
/// All players either doubled or didn't double
var allPlayersActed: Bool {
!players.contains { !$0.didDecide }
}
2021-12-18 15:08:43 +01:00
/// At least one player placed a bid
var hasDouble: Bool {
2021-12-21 11:16:54 +01:00
players.contains { $0.didDouble }
}
2021-12-18 15:08:43 +01:00
override func perform(action: PlayerAction, forPlayer name: PlayerName) -> (result: PlayerActionResult, table: ManageableTable?) {
guard let player = players.player(named: name) else {
print("Player \(name) unexpectedly missing from dealing table \(self.name)")
return (.tableStateInvalid, nil)
}
guard player.canPerform(action) else {
return (.tableStateInvalid, nil)
}
switch action {
case .initialDoubleCost:
return perform(double: true, forPlayer: player)
case .noDoubleCost:
return perform(double: false, forPlayer: player)
default:
return (.tableStateInvalid, nil)
}
}
2021-12-18 15:08:43 +01:00
private func perform(double: Bool, forPlayer player: DealingPlayer) -> (result: PlayerActionResult, table: ManageableTable?) {
guard !player.didDecide else {
2021-12-18 15:08:43 +01:00
return (.tableStateInvalid, nil)
}
player.didDouble = double
2021-12-21 11:16:54 +01:00
player.didDecide = true
2021-12-18 15:08:43 +01:00
guard allPlayersActed else {
return (.success, nil)
}
guard hasDouble else {
// Revert to a waiting table and switch to the next player
let table = WaitingTable(oldTableAdvancedByOne: self)
return (.success, table)
}
// Automatically adds remaining cards to the players
let table = BiddingTable(table: self)
return (.success, table)
}
2021-12-18 15:08:43 +01:00
override func cards(forPlayerAt index: Int) -> [PlayableCard] {
players[index].cards.unplayable
}
}