From f97604e3bfc5dc4232d8a807baee5022d28c89e4 Mon Sep 17 00:00:00 2001 From: Christoph Hagen Date: Thu, 23 Dec 2021 11:16:29 +0100 Subject: [PATCH] Delete table when empty --- Sources/App/Management/TableManagement.swift | 9 +++++++-- Sources/App/Model/Tables/WaitingTable.swift | 7 +++++-- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/Sources/App/Management/TableManagement.swift b/Sources/App/Management/TableManagement.swift index f14266b..6de7c25 100644 --- a/Sources/App/Management/TableManagement.swift +++ b/Sources/App/Management/TableManagement.swift @@ -110,11 +110,16 @@ final class TableManagement { guard let oldTable = currentTable(for: player.name) else { return database.eventLoop.makeSucceededVoidFuture() } + player.$table.id = nil + guard let table = WaitingTable(oldTable: oldTable, removing: player.name) else { + tables[oldTable.id] = nil + return Table.query(on: database).filter(\.$id == oldTable.id).delete().flatMap { + player.update(on: database) + } + } /// `player.canStartGame` is automatically set to false, because table is not full - let table = WaitingTable(oldTable: oldTable, removing: player.name) tables[table.id] = table table.sendUpdateToAllPlayers() - player.$table.id = nil // TODO: Update points for all players return player.update(on: database) } diff --git a/Sources/App/Model/Tables/WaitingTable.swift b/Sources/App/Model/Tables/WaitingTable.swift index 5d8ec4e..2be99dd 100644 --- a/Sources/App/Model/Tables/WaitingTable.swift +++ b/Sources/App/Model/Tables/WaitingTable.swift @@ -39,7 +39,7 @@ final class WaitingTable: AbstractTable { - Parameter oldTable: The table to convert - Parameter player: The name of the player to remove from the table. */ - init(oldTable: ManageableTable, removing player: PlayerName) { + init?(oldTable: ManageableTable, removing player: PlayerName) { // TODO: End game and distribute points let players = oldTable.allPlayers .filter { @@ -50,6 +50,9 @@ final class WaitingTable: AbstractTable { return false } .map { WaitingPlayer(name: $0.name, points: $0.totalPoints, socket: $0.socket) } + guard !players.isEmpty else { + return nil + } players.first!.isNextActor = true super.init(table: oldTable, players: players) } @@ -58,7 +61,7 @@ final class WaitingTable: AbstractTable { Convert another table to a waiting table. This is needed when a player leaves an active table. - - Parameter oldTable: The table to convert + - Parameter table: The table to convert */ init(oldTableAdvancedByOne table: ManageableTable) { let players = table.allPlayers