public override void ResolveBattle() { // Calculate amount of troops for each player Dictionary <Player, int> remainingTroops = new Dictionary <Player, int>(); foreach (Army army in Armies) { if (!remainingTroops.ContainsKey(army.SourcePlayer)) { remainingTroops.Add(army.SourcePlayer, army.NumTroops); } else { remainingTroops[army.SourcePlayer] += army.NumTroops; } } List <Player> remainingPlayers = remainingTroops.Where(x => x.Value > 0).Select(x => x.Key).ToList(); // Calculate strength of each player (weighted average of all armies of that player) Dictionary <Player, float> playerStrength = new Dictionary <Player, float>(); foreach (Player p in remainingPlayers) { Casualties.Add(p, 0); List <Army> playerArmies = Armies.Where(x => x.SourcePlayer == p).ToList(); int totalTroops = remainingTroops[p]; float totalStrength = 0; foreach (Army army in playerArmies) { totalStrength += (army.NumTroops * army.Strength); } float strength = totalStrength / totalTroops; playerStrength.Add(p, strength); //Debug.Log("Player " + p.Name + " Strength: " + strength); } // Fight until only one player has armies left while (remainingPlayers.Count > 1) { float totalStrength = 0f; foreach (Player p in remainingPlayers) { totalStrength += playerStrength[p]; } float rng = Random.Range(0, totalStrength); float tmp = 0f; int c = 0; Player winner = null; while (winner == null) { tmp += playerStrength[remainingPlayers[c]]; if (tmp >= rng) { winner = remainingPlayers[c]; } c++; } foreach (Player p in remainingPlayers) { if (p != winner) { remainingTroops[p]--; Casualties[p]++; } } remainingPlayers = remainingTroops.Where(x => x.Value > 0).Select(x => x.Key).ToList(); } // Set post-battle values Winner = remainingPlayers[0]; Losers = Players.Where(x => x != Winner).ToList(); WinnerSourceTerritory = Armies.First(x => x.SourcePlayer == Winner).SourceTerritory; WinnerTargetTerritory = Armies.First(x => x.SourcePlayer == Winner).TargetTerritory; WinnerTroopsRemaining = remainingTroops[Winner]; }
/// <summary> /// Add a certain amount of troops to a territory /// </summary> public void AddTroops(Territory t, int troops) { t.AddTroops(troops); }