using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace MySparkApp { public class Collector { private List _sortedPlayers = null; private List _players = new List(); public Collector(List sortOrder, List players) { _sortedPlayers = sortOrder; foreach (Player player in players) { _players.Add((Player)player.Clone()); } } public Int32 Collect() { Point currLocation = new Point(0, 0); Int32 totalSubstance = 1000000; //Console.WriteLine("Collect: _players.count = " + _players.Count.ToString()); // for each player in the order of this list... for (Int32 indx = 0; indx < _sortedPlayers.Count; indx++) { // get the player object Player player = _players.Find(x => x.Name.Trim() == _sortedPlayers[indx].Trim()); player = null; foreach (Player subject in _players) { //Console.WriteLine("Collect: subject.Name = " + subject.Name + ", sortedPlayer = " + _sortedPlayers[indx]); if (subject.Name == _sortedPlayers[indx]) { player = subject; } } if (player != null) { //Console.WriteLine("Collect: player.Name = " + player.Name); // get the distance the collector has to travel Int32 timeUnits = DistanceBetweenPoints(currLocation, player.Location); // move the collector to the player currLocation = player.Location; // we have to update the substance for each player foreach (Player player2 in _players) { player2.CurrentSubstance += player2.SubstanceRate * timeUnits; } // collect the substance totalSubstance += player.CurrentSubstance; // turn of the substance rate for this player player.SubstanceRate = 0; } else { totalSubstance = 0; } } return totalSubstance; } private Int32 DistanceBetweenPoints(Point a, Point b) { if (a.X == b.X && a.Y == b.Y) { return 0; } if (a.X == b.X) { return Math.Abs(a.Y - b.Y); } if (a.Y == b.Y) { return Math.Abs(a.X - b.X); } Int32 horzSide = Math.Abs(a.X - b.X); Int32 vertSide = Math.Abs(a.Y - b.Y); double hypotenuse = Math.Sqrt((horzSide * horzSide) + (vertSide * vertSide)); return (Int32)Math.Ceiling(hypotenuse); } public static string PlayersToString(List players) { string outStr = ""; foreach (Player player in players) { if (!string.IsNullOrEmpty(outStr)) { outStr += "|"; } outStr += player.Name + "," + player.Location.X.ToString() + "," + player.Location.Y.ToString() + "," + player.SubstanceRate.ToString(); } return outStr; } public static List PlayersFromString(string inStr) { List outPlayers = new List(); string[] rows = inStr.Split(new char[] { '|' }); foreach (string row in rows) { string[] props = row.Split(new char[] { ',' }); Player player = new Player(); player.Name = props[0]; Int32 posX = 0; Int32 posY = 0; Int32 rate = 0; Int32.TryParse(props[1], out posX); Int32.TryParse(props[2], out posY); Int32.TryParse(props[3], out rate); player.Location = new Point(posX, posY); player.SubstanceRate = rate; outPlayers.Add(player); } return outPlayers; } } }