From eafcb814cdf29246f9836a16c2d90fc3bf434320 Mon Sep 17 00:00:00 2001 From: phosit Date: Mon, 30 Dec 2024 17:57:48 +0100 Subject: [PATCH] Simplify playerassignments code Deduplicate a check by moving it to isSlotAvailable. Based on a patch by @elexis. --- .../PlayerAssignmentsController.js | 44 +++++++++---------- 1 file changed, 20 insertions(+), 24 deletions(-) diff --git a/binaries/data/mods/public/gui/gamesetup/Controllers/PlayerAssignmentsController.js b/binaries/data/mods/public/gui/gamesetup/Controllers/PlayerAssignmentsController.js index 264bda24b8..8f07c2515c 100644 --- a/binaries/data/mods/public/gui/gamesetup/Controllers/PlayerAssignmentsController.js +++ b/binaries/data/mods/public/gui/gamesetup/Controllers/PlayerAssignmentsController.js @@ -109,37 +109,33 @@ class PlayerAssignmentsController return; } - // Find a player slot that no other player is assigned to. - const possibleSlots = [...Array(g_GameSettings.playerCount.nbPlayers).keys()].map(i => i + 1); + const slot = this.findAssignmentSlot(newGUID, newAssignments); - let slot; - const newName = newAssignments[newGUID].name; - // First check if we know them and try to give them their old assignment back. - if (this.lastAssigned[newName] > 0 && this.lastAssigned[newName] <= g_GameSettings.playerCount.nbPlayers) - { - let free = true; - for (const guid in newAssignments) - if (newAssignments[guid].player === this.lastAssigned[newName]) - { - free = false; - break; - } - if (free) - slot = this.lastAssigned[newName]; - } - if (!slot) - slot = possibleSlots.find(i => { - for (const guid in newAssignments) - if (newAssignments[guid].player == i) - return false; - return true; - }); if (slot === undefined) return; this.assignClient(newGUID, slot); } + findAssignmentSlot(newGUID, newAssignments) + { + const newAssignmentsArray = Object.values(newAssignments); + const isSlotAvailable = slot => newAssignmentsArray.every(elem => elem.player !== slot); + + const newName = newAssignments[newGUID].name; + // First check if we know them and try to give them their old assignment back. + if (this.lastAssigned[newName] > 0 && + this.lastAssigned[newName] <= g_GameSettings.playerCount.nbPlayers && + isSlotAvailable(this.lastAssigned[newName])) + { + return this.lastAssigned[newName]; + } + + // If we can't restore the slot, assign the client to the first free slot. + return Array.from(Array(g_GameSettings.playerCount.nbPlayers).keys(), i => i + 1).find( + isSlotAvailable); + } + /** * To be called when g_PlayerAssignments is modified. */