Schafkopf-Server/Sources/App/Model/OldTable.swift

578 lines
18 KiB
Swift
Raw Normal View History

2021-12-03 18:03:29 +01:00
import Foundation
import WebSocketKit
private extension Int {
mutating func advanceInTable() {
self = (self + 1) % maximumPlayersPerTable
}
}
2021-12-09 11:10:20 +01:00
final class OldTable {
2021-12-03 18:03:29 +01:00
let id: TableId
let name: TableName
let isPublic: Bool
2021-12-09 11:10:20 +01:00
var players: [OldPlayer] = []
2021-12-03 18:03:29 +01:00
var phase: GamePhase = .waitingForPlayers
var gameType: GameType? = nil
2021-12-09 11:10:20 +01:00
var minimumPlayableGame: GameType.GameClass = .none
2021-12-03 18:03:29 +01:00
/// Indicates if any player doubled during the current round, extending it to the next round
var didDoubleInCurrentRound = false
/// Indicates that all players acted after the first four cards
var allPlayersFinishedDoubling: Bool {
!players.contains { $0.didDoubleAfterFourCards == nil }
}
2021-12-06 11:43:30 +01:00
/// At least one double exists after all players acted on their first cards
var initialDoubleExists: Bool {
players.contains { $0.didDoubleAfterFourCards == true }
}
2021-12-06 11:43:30 +01:00
var weddingOfferExists: Bool {
players.contains { $0.offersWedding }
}
var weddingAcceptExists: Bool {
players.contains { $0.wouldAcceptWedding }
}
var hasAuctionWinner: Bool {
numberOfRemainingBidders == 1
}
var numberOfRemainingBidders: Int {
players.filter { $0.isStillBidding }.count
}
2021-12-09 11:10:20 +01:00
var auctionWinner: OldPlayer {
2021-12-06 11:43:30 +01:00
players.first { $0.isStillBidding }!
}
var hasCompletedTrick: Bool {
!players.contains { $0.playedCard == nil }
}
var completedTrick: Trick? {
let trick = players.compactMap { $0.playedCard }
guard trick.count == maximumPlayersPerTable else {
return nil
}
return trick
}
var currentTrick: [Card] {
players.compactMap { $0.playedCard }
}
2021-12-07 09:09:51 +01:00
var didFinishGame: Bool {
!players.contains { !$0.handCards.isEmpty }
}
2021-12-03 18:03:29 +01:00
init(id: TableId, name: TableName, isPublic: Bool) {
self.id = id
self.name = name
self.isPublic = isPublic
}
init(newTable name: TableName, isPublic: Bool) {
self.id = .newToken()
self.name = name
self.isPublic = isPublic
}
func add(player: PlayerName) -> Bool {
guard !isFull else {
return false
}
2021-12-09 11:10:20 +01:00
let player = OldPlayer(name: player)
2021-12-03 18:03:29 +01:00
players.append(player)
if isFull {
prepareTableForFirstGame()
}
sendUpdateToAllPlayers()
return true
}
func contains(player: PlayerName) -> Bool {
players.contains { $0.name == player }
}
2021-12-06 11:43:30 +01:00
/// The player to play the first card of the current game
2021-12-09 11:10:20 +01:00
var firstPlayer: OldPlayer {
2021-12-06 11:43:30 +01:00
players.first { $0.playsFirstCard }!
}
2021-12-03 18:03:29 +01:00
2021-12-09 11:10:20 +01:00
func select(player: PlayerName) -> OldPlayer? {
2021-12-03 18:03:29 +01:00
players.first { $0.name == player }
}
2021-12-07 09:09:51 +01:00
var indexOfTrickStarter: Int {
players.firstIndex { $0.startedCurrentTrick }!
}
2021-12-03 18:03:29 +01:00
2021-12-09 11:10:20 +01:00
func player(at index: Int) -> OldPlayer? {
2021-12-03 18:03:29 +01:00
guard index < players.count else {
return nil
}
return players[index]
}
2021-12-06 11:43:30 +01:00
2021-12-09 11:10:20 +01:00
func index(of player: OldPlayer) -> Int {
2021-12-06 11:43:30 +01:00
players.firstIndex(of: player)!
}
2021-12-09 11:10:20 +01:00
func nextPlayer(after player: OldPlayer) -> OldPlayer {
2021-12-06 11:43:30 +01:00
let i = index(of: player)
let newIndex = (i + 1) % maximumPlayersPerTable
return players[newIndex]
}
2021-12-09 11:10:20 +01:00
func nextBidder(after player: OldPlayer) -> OldPlayer {
2021-12-06 11:43:30 +01:00
// Find next player to place bid
let index = index(of: player)
for i in 1..<4 {
let player = players[(index + i) % 4]
guard player.isStillBidding, !player.offersWedding else {
2021-12-06 11:43:30 +01:00
continue
}
return player
}
return player
}
2021-12-09 11:10:20 +01:00
func availableGames(forPlayerAt index: Int) -> [GameType] {
return []
}
2021-12-03 18:03:29 +01:00
func remove(player: PlayerName) {
guard let index = players.firstIndex(where: { $0.name == player }) else {
2021-12-03 18:03:29 +01:00
return
}
let removedPlayer = players[index]
if removedPlayer.playsFirstCard {
players[(index + 1) % players.count].playsFirstCard = true
}
players.remove(at: index)
2021-12-03 18:03:29 +01:00
reset()
}
func connect(player name: PlayerName, using socket: WebSocket) -> Bool {
guard let player = select(player: name) else {
return false
}
player.connect(using: socket)
sendUpdateToAllPlayers()
return true
}
func disconnect(player name: PlayerName) {
guard let player = select(player: name) else {
return
}
guard player.disconnect() else {
return
}
sendUpdateToAllPlayers()
return
}
private func prepareTableForFirstGame() {
2021-12-06 11:43:30 +01:00
phase = .waitingForPlayers
gameType = nil
2021-12-09 11:10:20 +01:00
minimumPlayableGame = .none // Not relevant in this phase
2021-12-06 11:43:30 +01:00
didDoubleInCurrentRound = false // Not relevant in this phase
2021-12-03 18:03:29 +01:00
let index = players.firstIndex { $0.playsFirstCard } ?? 0
for i in 0..<maximumPlayersPerTable {
players[i].prepareForNewGame(isFirstPlayer: i == index)
2021-12-03 18:03:29 +01:00
}
}
private func sendUpdateToAllPlayers() {
2021-12-09 11:10:20 +01:00
2021-12-03 18:03:29 +01:00
}
// MARK: Player actions
2021-12-06 11:43:30 +01:00
func play(card: Card, player name: PlayerName) -> PlayCardResult {
let player = select(player: name)!
if phase == .selectWeddingCard {
return selectedCardForWedding(card: card, player: player)
}
2021-12-07 09:09:51 +01:00
guard let game = gameType, player.hasPlayable(card: card) else {
// Player only has playable cards when it is active
2021-12-06 11:43:30 +01:00
return .invalidCard
}
2021-12-07 09:09:51 +01:00
if hasCompletedTrick {
// Hide cards from last trick when next card is played
players.forEach { $0.clearLastTrick() }
}
2021-12-06 11:43:30 +01:00
player.play(card: card)
if let completedTrick = completedTrick {
didFinish(trick: completedTrick, in: game)
2021-12-07 09:09:51 +01:00
// Update cards for empty trick
players.forEach { $0.setPlayableCards(forCurrentTrick: [], in: game) }
2021-12-06 11:43:30 +01:00
} else {
let next = nextPlayer(after: player)
next.isNextActor = true
player.isNextActor = false
2021-12-07 09:09:51 +01:00
// Update cards for empty trick
players.forEach { $0.setPlayableCards(forCurrentTrick: currentTrick, in: game) }
}
if didFinishGame {
finishedGame()
2021-12-06 11:43:30 +01:00
}
sendUpdateToAllPlayers()
2021-12-06 11:43:30 +01:00
return .success
}
2021-12-07 09:09:51 +01:00
private func finishedGame() {
phase = .gameFinished
players.forEach { $0.didFinishGame() }
guard didFinishGame else {
// Either no doubles or bids
return
2021-12-06 11:43:30 +01:00
}
2021-12-07 09:09:51 +01:00
// TODO: Calculate winner, points, cost
2021-12-06 11:43:30 +01:00
}
func didFinish(trick: Trick, in game: GameType) {
// If trick is completed, calculate winner
2021-12-07 09:09:51 +01:00
let startIndex = indexOfTrickStarter
let rotated = trick.rotated(toStartAt: startIndex)
let index = rotated.highCardIndex(forGame: game)
print("Winner \(index) for \(rotated)")
let winner = players[(startIndex + index) % 4]
2021-12-06 11:43:30 +01:00
players.forEach {
2021-12-07 09:09:51 +01:00
$0.didFinish(trick: trick,
winner: winner == $0,
canDoubleInNextRound: didDoubleInCurrentRound)
}
if game == .bettel && winner.isGameLeader {
// A bettel is lost if a single trick is won by the leader
finishedGame()
return
2021-12-06 11:43:30 +01:00
}
didDoubleInCurrentRound = false
}
2021-12-03 18:03:29 +01:00
2021-12-09 11:10:20 +01:00
func perform(action: PlayerAction, forPlayer player: PlayerName) -> PlayerActionResult {
2021-12-06 11:43:30 +01:00
let player = select(player: player)!
guard player.canPerform(action) else {
2021-12-09 11:18:26 +01:00
print("Player \(player) wants to \(action.id), but only allowed: \(player.actions)")
2021-12-06 11:43:30 +01:00
return .tableStateInvalid
}
2021-12-03 18:03:29 +01:00
defer { sendUpdateToAllPlayers() }
switch action {
case .deal:
return dealInitialCards()
case .initialDoubleCost:
return perform(double: true, forPlayer: player)
case .noDoubleCost:
return perform(double: false, forPlayer: player)
case .offerWedding:
2021-12-06 11:43:30 +01:00
return performWeddingCall(forPlayer: player)
2021-12-03 18:03:29 +01:00
case .acceptWedding:
2021-12-06 11:43:30 +01:00
return handleWeddingAccept(forPlayer: player)
2021-12-03 18:03:29 +01:00
case .increaseOrMatchGame:
2021-12-06 11:43:30 +01:00
return performBidIncrease(forPlayer: player)
2021-12-03 18:03:29 +01:00
case .withdrawFromAuction:
2021-12-06 11:43:30 +01:00
return performWithdrawl(forPlayer: player)
2021-12-03 18:03:29 +01:00
case .doubleDuringGame:
2021-12-06 11:43:30 +01:00
return performDoubleDuringGame(forPlayer: player)
2021-12-03 18:03:29 +01:00
}
}
private func dealInitialCards() -> PlayerActionResult {
guard isFull else {
return .tableNotFull
}
2021-12-07 09:09:51 +01:00
guard phase == .waitingForPlayers || phase == .gameFinished else {
2021-12-03 18:03:29 +01:00
return .tableStateInvalid
}
2021-12-07 09:09:51 +01:00
if phase == .gameFinished {
prepareForNextGame()
}
2021-12-03 18:03:29 +01:00
let cards = Dealer.dealFirstCards()
for (index, player) in players.enumerated() {
player.assignFirstCards(cards[index])
}
2021-12-06 11:43:30 +01:00
phase = .collectingDoubles
gameType = nil
2021-12-03 18:03:29 +01:00
return .success
}
2021-12-09 11:10:20 +01:00
func perform(double: Bool, forPlayer player: OldPlayer) -> PlayerActionResult {
2021-12-03 18:03:29 +01:00
player.didDouble(double)
guard allPlayersFinishedDoubling else {
return .success
}
2021-12-07 09:09:51 +01:00
if initialDoubleExists {
dealAdditionalCards()
} else {
finishedGame()
2021-12-03 18:03:29 +01:00
}
return .success
}
private func dealAdditionalCards() {
let cards = Dealer.dealRemainingCards(of: players.map { $0.rawCards })
for (index, player) in players.enumerated() {
player.assignRemainingCards(cards[index])
}
2021-12-06 11:43:30 +01:00
players.forEach { $0.startAuction() }
2021-12-09 11:10:20 +01:00
minimumPlayableGame = .none
phase = .bidding
2021-12-06 11:43:30 +01:00
}
2021-12-09 11:10:20 +01:00
private func performWeddingCall(forPlayer player: OldPlayer) -> PlayerActionResult {
2021-12-06 11:43:30 +01:00
guard phase == .bidding else {
print("Invalid phase \(phase) for wedding call")
2021-12-06 11:43:30 +01:00
return .tableStateInvalid
}
2021-12-09 11:10:20 +01:00
guard minimumPlayableGame.allowsWedding else {
print("Invalid minimum game \(minimumPlayableGame) for wedding call")
2021-12-06 11:43:30 +01:00
return .tableStateInvalid
}
2021-12-07 09:09:51 +01:00
guard player.canOfferWedding else {
print("Player does not offer wedding")
2021-12-06 11:43:30 +01:00
return .tableStateInvalid
}
guard !weddingOfferExists else {
// Only one wedding allowed at the table
print("Already one wedding at table")
2021-12-06 11:43:30 +01:00
return .tableStateInvalid
}
// Only allow wedding acceptance or outbidding
players.forEach { $0.weddingOfferExists() }
player.offerWedding()
firstPlayer.hasWeddingOffer()
minimumPlayableGame = .bettel
2021-12-03 18:03:29 +01:00
return .success
}
2021-12-06 11:43:30 +01:00
2021-12-09 11:10:20 +01:00
private func performBidIncrease(forPlayer player: OldPlayer) -> PlayerActionResult {
2021-12-06 11:43:30 +01:00
guard phase == .bidding else {
return .tableStateInvalid
}
if weddingOfferExists {
// Anyone except the offerer can outbid a wedding
return handleWeddingOutbid(forPlayer: player)
}
guard player.isNextActor else {
return .tableStateInvalid
}
2021-12-09 11:10:20 +01:00
// TODO: Check if new player sits before old player
// then don't increase game
minimumPlayableGame.increase()
if !minimumPlayableGame.allowsWedding {
// Remove wedding offers
players.forEach { $0.weddingOutbid() }
2021-12-06 11:43:30 +01:00
}
2021-12-09 11:10:20 +01:00
#warning("Fix bidding")
// TODO: Remove highest bidder from old player
2021-12-06 11:43:30 +01:00
player.didPerformBid()
2021-12-09 11:10:20 +01:00
2021-12-07 09:09:51 +01:00
if numberOfRemainingBidders == 1 {
selectGame(player: player)
2021-12-09 11:10:20 +01:00
return .success
2021-12-07 09:09:51 +01:00
}
2021-12-06 11:43:30 +01:00
// Find next player to place bid
2021-12-07 09:09:51 +01:00
nextBidder(after: player).requiresBid(hasWedding: false)
2021-12-06 11:43:30 +01:00
return .success
2021-12-03 18:03:29 +01:00
}
2021-12-06 11:43:30 +01:00
2021-12-09 11:10:20 +01:00
private func handleWeddingOutbid(forPlayer player: OldPlayer) -> PlayerActionResult {
2021-12-06 11:43:30 +01:00
if player.offersWedding {
// A player offering a wedding can't outbid itself
return .tableStateInvalid
}
players.forEach { $0.weddingOutbid() }
2021-12-09 11:10:20 +01:00
nextBidder(after: player).requiresBid(hasWedding: false)
2021-12-06 11:43:30 +01:00
return .success
}
2021-12-09 11:10:20 +01:00
private func handleWeddingAccept(forPlayer player: OldPlayer) -> PlayerActionResult {
2021-12-06 11:43:30 +01:00
guard phase == .bidding else {
return .tableStateInvalid
}
2021-12-09 11:10:20 +01:00
guard minimumPlayableGame.allowsWedding else {
2021-12-06 11:43:30 +01:00
return .tableStateInvalid
}
guard weddingOfferExists else {
return .tableStateInvalid
}
guard player.isNextActor else {
return .tableStateInvalid
}
guard !player.offersWedding else {
return .tableStateInvalid
}
guard !weddingAcceptExists else {
return .tableStateInvalid
}
if hasAuctionWinner {
selectedWedding(player: player)
return .success
}
minimumPlayableGame = .bettel
players.forEach {
$0.weddingAccepted()
}
player.acceptWedding()
2021-12-07 09:09:51 +01:00
nextBidder(after: player).requiresBid(hasWedding: false)
2021-12-06 11:43:30 +01:00
return .success
}
2021-12-09 11:10:20 +01:00
private func selectedWedding(player: OldPlayer) {
minimumPlayableGame = .none
2021-12-06 11:43:30 +01:00
gameType = .hochzeit
phase = .selectWeddingCard
players.forEach { $0.auctionEnded() }
player.mustSelectWeddingCard()
}
2021-12-09 11:10:20 +01:00
private func selectedCardForWedding(card: Card, player: OldPlayer) -> PlayCardResult {
2021-12-06 11:43:30 +01:00
guard player.isNextActor,
player.wouldAcceptWedding,
weddingOfferExists else {
2021-12-09 11:10:20 +01:00
return .tableStateInvalid
2021-12-06 11:43:30 +01:00
}
guard !card.isTrump(in: .hochzeit),
player.has(card: card) else {
return .invalidCard
}
// Swap the cards
let offerer = players.first { $0.offersWedding }!
let offeredCard = offerer.replaceWeddingCard(with: card)
player.replace(card: card, with: offeredCard)
// Start the game
gameType = .hochzeit
players.forEach { $0.start(game: .hochzeit) }
2021-12-06 11:43:30 +01:00
player.switchLeadership()
offerer.switchLeadership()
return .success
}
2021-12-09 11:10:20 +01:00
private func performWithdrawl(forPlayer player: OldPlayer) -> PlayerActionResult {
2021-12-06 11:43:30 +01:00
guard phase == .bidding,
player.isNextActor,
player.isStillBidding else {
return .tableStateInvalid
}
player.withdrawFromBidding()
switch numberOfRemainingBidders {
case 1:
2021-12-09 11:10:20 +01:00
if minimumPlayableGame != .none {
2021-12-07 09:09:51 +01:00
// Will only be called when at least one player placed a bid
selectGame(player: auctionWinner)
return .success
}
2021-12-06 11:43:30 +01:00
case 0:
// All players withdrawn, deal new cards
2021-12-07 09:09:51 +01:00
finishedGame()
return .success
2021-12-06 11:43:30 +01:00
default:
2021-12-07 09:09:51 +01:00
break
2021-12-06 11:43:30 +01:00
}
2021-12-07 09:09:51 +01:00
nextBidder(after: player).requiresBid(hasWedding: weddingOfferExists)
2021-12-06 11:43:30 +01:00
return .success
}
2021-12-07 09:09:51 +01:00
private func prepareForNextGame() {
let first = firstPlayer
let newPlayer = self.nextBidder(after: first)
first.playsFirstCard = false
newPlayer.playsFirstCard = true
2021-12-07 09:09:51 +01:00
print("Made \(newPlayer.name) to new starter")
prepareTableForFirstGame()
}
2021-12-09 11:10:20 +01:00
private func selectGame(player: OldPlayer) {
2021-12-06 11:43:30 +01:00
gameType = nil
phase = .selectGame
players.forEach { $0.auctionEnded() }
player.mustSelectGame()
}
func select(game: GameType, player: PlayerName) -> PlayerActionResult {
let player = select(player: player)!
guard phase == .selectGame, player.selectsGame, game != .hochzeit else {
return .tableStateInvalid
}
2021-12-09 11:10:20 +01:00
guard game.gameClass >= minimumPlayableGame else {
return .tableStateInvalid
}
defer { sendUpdateToAllPlayers() }
guard let suit = game.calledSuit else {
phase = .playing
gameType = game
2021-12-09 11:10:20 +01:00
minimumPlayableGame = .none
players.forEach { $0.start(game: game) }
player.switchLeadership()
return .success
}
guard player.canPlay(game: game) else {
return .tableStateInvalid
}
phase = .playing
gameType = game
2021-12-09 11:10:20 +01:00
minimumPlayableGame = .none
players.forEach { $0.start(game: game) }
player.switchLeadership()
// Find called player
let ace = Card(suit, .ass)
players.first { $0.rawCards.contains(ace) }!.switchLeadership()
return .success
}
2021-12-09 11:10:20 +01:00
private func performDoubleDuringGame(forPlayer player: OldPlayer) -> PlayerActionResult {
guard phase == .playing, !player.isGameLeader else {
return .tableStateInvalid
}
2021-12-06 11:43:30 +01:00
player.numberOfRaises += 1
players.forEach { $0.switchLeadership() }
2021-12-07 09:09:51 +01:00
didDoubleInCurrentRound = true
2021-12-06 11:43:30 +01:00
return .success
}
2021-12-03 18:03:29 +01:00
private func reset() {
phase = .waitingForPlayers
gameType = nil
2021-12-09 11:10:20 +01:00
minimumPlayableGame = .none
for player in players {
player.prepareForNewGame(isFirstPlayer: player.playsFirstCard)
}
2021-12-03 18:03:29 +01:00
}
}
2021-12-09 11:10:20 +01:00
extension OldTable {
2021-12-03 18:03:29 +01:00
var isFull: Bool {
players.count == maximumPlayersPerTable
}
var publicInfo: PublicTableInfo {
.init(id: id, name: name, players: playerNames)
}
var playerNames: [PlayerName] {
players.map { $0.name }
}
2021-12-09 11:10:20 +01:00
2021-12-03 18:03:29 +01:00
}