import { Player , PlayerId } from '../../Player' ; import { Game } from '../../Game' ; import { NeutralPlayer } from '../Turmoil' ; export abstract class Party { public partyLeader : undefined | PlayerId | NeutralPlayer = undefined ; public delegates : Array < PlayerId | NeutralPlayer > = [ ] ; public sendDelegate ( playerId , game ) { this . delegates . push ( playerId ) ; this . checkPartyLeader ( playerId , game ) ; } public removeDelegate ( playerId , game ) { this . delegates . splice ( this . delegates . indexOf ( playerId ) , 1 ) ; this . checkPartyLeader ( playerId , game ) ; } public checkPartyLeader ( newPlayer , game ) { if ( this . partyLeader ) { if ( game ) { const sortedPlayers = [ ... this . getPresentPlayers ( ) ] . sort ( ( p1 , p2 ) => this . getDelegates ( p2 ) - this . getDelegates ( p1 ) ) ; const max = this . getDelegates ( sortedPlayers [ 0 ] ) ; if ( this . getDelegates ( this . partyLeader ) !== max ) { let currentIndex = 0 ; if ( this . partyLeader === 'NEUTRAL' ) { currentIndex = game . getPlayers ( ) . indexOf ( game . getPlayerById ( game . activePlayer ) ) ; } else { currentIndex = game . getPlayers ( ) . indexOf ( game . getPlayerById ( this . partyLeader ) ) ; } let playersToCheck = [ ] ; if ( game . getPlayers ( ) . length === 1 || currentIndex === 0 ) { playersToCheck = game . getPlayers ( ) ; } else if ( currentIndex === game . getPlayers ( ) . length - 1 ) { playersToCheck = game . getPlayers ( ) . slice ( 0 , currentIndex ) ; playersToCheck . unshift ( game . getPlayers ( ) [ currentIndex ] ) ; } else { const left = game . getPlayers ( ) . slice ( 0 , currentIndex ) ; const right = game . getPlayers ( ) . slice ( currentIndex ) ; playersToCheck = right . concat ( left ) ; } playersToCheck . push ( 'NEUTRAL' ) ; playersToCheck . some ( ( nextPlayer ) => { let nextPlayerId = '' ; if ( nextPlayer === 'NEUTRAL' ) { nextPlayerId = 'NEUTRAL' ; } else { nextPlayerId = nextPlayer . id ; } if ( this . getDelegates ( nextPlayerId ) === max ) { this . partyLeader = nextPlayerId ; return true ; } return false ; } ) ; } } } else { this . partyLeader = newPlayer ; } } public getPresentPlayers ( ) { return Array . from ( new Set ( this . delegates ) ) ; } public getDelegates ( player ) { const delegates = this . delegates . filter ( ( p ) => p === player ) . length ; return delegates ; } }