public void Breed() { breedingPartners.Clear(); members .Where(member => member.IsOfReproductionAge) .ForEach(member => breedingPartners.Add(member)); // То же самое, что toList(), но не срёт в память. А у нас GC на секундочку, 17% производительности жрёт на момент когда я до этого места дорвался. while (breedingPartners.Count > 1) { // breedingPartners.Remove(PartnerA) адски тяжёлая операция, потому что во-первых, надо этот элемент теперь в списке найти за линейное время. А потом ещё раз за линейное время сдвингуть все элементы, которые в списке идёт после него, между тем порядок в данном случае для нас абсолютно не важен. Одно только это место жрало 13% производительности когда я до него добрался. int index = randomizer.Next(breedingPartners.Count); int last = breedingPartners.Count - 1; Tribesman PartnerA = breedingPartners[index]; breedingPartners[index] = breedingPartners[last]; breedingPartners.RemoveAt(last); index = randomizer.Next(breedingPartners.Count); last = breedingPartners.Count - 1; Tribesman PartnerB = breedingPartners[index]; breedingPartners[index] = breedingPartners[last]; breedingPartners.RemoveAt(last); Tribesman child = Tribesman.Breed(randomizer, PartnerA, PartnerB, _memesCache); if (child != null) { PartnerA.childrenCount++; PartnerB.childrenCount++; this.AcceptMember(child); } } }
public void MemeUsed(Tribesman member, Meme e) { if (memesUsedThisYearHash.Add(e)) { memesUsedThisYear.AddToSortedList(e); } }
public void ReportInvented(Tribesman tribesman) { Report("Was invented by " + tribesman.Name); lock (staticLocker) { numInstances++; knownBy = 1; maxKnowBy = 1; totalKnowBy = 1; maxKnownByYear = World.Year; } }
public void AttemptCulturalExchangeWith(Tribe tribeTo) { Tribesman man = members[randomizer.Next(members.Count)]; { Tribesman student; student = members[randomizer.Next(members.Count)]; while (student == man) // this cycle is just to make sure he's not trying to teach himself { student = members[randomizer.Next(members.Count)]; } man.TryToTeach(student, true); } }
private string Add(Session session, string[] parms) { bool help = false; string playerName = string.Empty; string tribeName = string.Empty; try { var p = new OptionSet { { "?|help|h", v => help = true }, { "tribe=", v => tribeName = v.TrimMatchingQuotes() }, { "player=", v => playerName = v.TrimMatchingQuotes() }, }; p.Parse(parms); } catch (Exception) { help = true; } if (help || string.IsNullOrEmpty(playerName) || string.IsNullOrEmpty(tribeName)) { return("TribesmanAdd --tribe=tribe_name --player=player_name"); } uint playerId; if (!world.FindPlayerId(playerName, out playerId)) { return("Player not found"); } uint tribeId; if (!tribeManager.FindTribeId(tribeName, out tribeId)) { return("Tribe not found"); } Dictionary <uint, IPlayer> players; locker.Lock(out players, playerId, tribeId).Do(() => { ITribe tribe = players[tribeId].Tribesman.Tribe; var tribesman = new Tribesman(tribe, players[playerId], tribe.DefaultRank); tribe.AddTribesman(tribesman, true); }); return("OK"); }
public Tribe Split() { if (members.Count <= WorldProperties.SplitTribeIfBiggerThen) { return(null); } Tribe newTribe = new Tribe(randomizer.Next(int.MaxValue)); for (int i = 0; i < members.Count * WorldProperties.SplitTribeRatio; i++) { Tribesman member = members[randomizer.Next(members.Count)]; MemberLeaves(member); newTribe.AcceptMember(member); } return(newTribe); }
public void AcceptMember(Tribesman member) { member.MyTribe = this; member.TribeMemberId = nextFreeMemberId++; member.SetRandomizer(randomizer); members.Add(member); member.ReportJoiningTribe(this); if (keepsLog && !logTribesmenList.Contains(member)) { if (logTribesmenList.Count > 0) { logMembers.Append(", "); } logMembers.Append(member.GetJSONString()); logTribesmenList.Add(member); } }
public void Die() { for (var i = members.Count - 1; i >= 0; --i) { Tribesman man = members[i]; if (man.WantsToDie()) { MemberDie(man); } } if (members.Count == 1) { members[0].DieOfLonliness(); MemberDie(members[0]); } }
public void ReportTeaching(Tribesman student, Tribesman teacher) { if (teacher != null) { Report(string.Format("Was transferred from {0} to {1}.", teacher.Name, student.Name)); } else { Report(string.Format("Was learnt by {0} by watching others use it.", student.Name)); } lock (staticLocker) { knownBy++; totalKnowBy++; } if (knownBy > maxKnowBy) { maxKnowBy = knownBy; maxKnownByYear = World.Year; } }
public void ReportForgotten(Tribesman tribesman) { Report("Was forgotten by " + tribesman.Name); lock (staticLocker) { knownBy--; } if (knownBy == 0) { lock (staticLocker) { numInstances--; } if (WorldProperties.CollectMemesSuccess > .5f && tribesman.randomizer.Chance(WorldProperties.ChanceToCollectMemesSuccess)) { ReportDetaliedStatistic(); } } if (knownBy < 0) { throw new IndexOutOfRangeException("The meme is known by a negative amount of tribesmen."); } }
public void Confirm(Session session, Packet packet) { bool isAccepting; try { isAccepting = packet.GetByte() != 0; } catch (Exception) { ReplyError(session, packet, Error.Unexpected); return; } ITribe tribe = null; locker.Lock(session.Player).Do(() => { if (session.Player.TribeRequest == 0) { ReplyError(session, packet, Error.TribesmanNoRequest); return; } var tribeRequestId = session.Player.TribeRequest; session.Player.TribeRequest = 0; dbManager.Save(session.Player); if (!isAccepting) { ReplySuccess(session, packet); return; } if (!world.TryGetObjects(tribeRequestId, out tribe)) { ReplyError(session, packet, Error.TribeNotFound); } }); if (tribe == null) { return; } locker.Lock(session.Player, tribe).Do(() => { if (tribe == null) { ReplyError(session, packet, Error.Unexpected); return; } var tribesman = new Tribesman(tribe, session.Player, tribe.DefaultRank); var error = tribe.AddTribesman(tribesman); if (error != Error.Ok) { ReplyError(session, packet, error); return; } var reply = new Packet(packet); reply.AddInt32(tribeManager.GetIncomingList(tribe).Count()); reply.AddInt16(tribe.AssignmentCount); PacketHelper.AddTribeRanksToPacket(tribe, reply); session.Write(reply); }); }
public static void Initialize(Dispatcher d, int randomSeed) { WorldProperties.ResetFeatureDescriptions(); randomizer = new Random(randomSeed); StatisticsCollector.Reset(); Meme.ClearMemePool(); tribes.Clear(); GC.Collect(); GC.WaitForPendingFinalizers(); if (!string.IsNullOrWhiteSpace(baseFolder)) { logFolder = Path.Combine(baseFolder, DateTime.Now.ToString("yyyyMMdd_HHmmss")); } else { baseFolder = Properties.Settings.Default.LogBaseFolder; if (string.IsNullOrWhiteSpace(baseFolder)) { logFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Tribe Sim Results", DateTime.Now.ToString("yyyyMMdd_HHmmss")); } else { logFolder = Path.Combine(baseFolder, DateTime.Now.ToString("yyyyMMdd_HHmmss")); } } Directory.CreateDirectory(logFolder); tribesLogFolder = Path.Combine(logFolder, "Tribes"); memesLogFolder = Path.Combine(logFolder, "Memes"); tribesmanLogFolder = Path.Combine(logFolder, "Tribesmen"); simDataFolder = Path.Combine(logFolder, "Results"); Directory.CreateDirectory(tribesmanLogFolder); Directory.CreateDirectory(tribesLogFolder); Directory.CreateDirectory(memesLogFolder); if (WorldProperties.CollectFilesData > 0.5) { Directory.CreateDirectory(simDataFolder); } Year = 0; int i; for (i = 0; i < WorldProperties.StartingNumberOfTribes; i++) { Tribe t = new Tribe(randomizer.Next(int.MaxValue)); int numberOfTribesmen = (int)Math.Round(randomizer.NormalRandom(WorldProperties.StartingTribePopulationMean, WorldProperties.StartingTribePopulationStdDev)); for (int ii = 0; ii < numberOfTribesmen; ii++) { Tribesman man = Tribesman.GenerateTribesmanFromAStartingSet(randomizer); t.AcceptMember(man); } tribes.Add(t); } int maxReproductionAge = 5000; // Это сломатся если у нас появятся сверхдолгожители if (WorldProperties.MaximumBreedingAge > 0) { maxReproductionAge = (int)WorldProperties.MaximumBreedingAge + 1; } Tribesman.reproductionCostIncrease = new double[maxReproductionAge]; i = 0; for (; i < WorldProperties.BreedingCostsIncreaseAge; i++) { Tribesman.reproductionCostIncrease[i] = 0; } for (; i < maxReproductionAge; i++) { Tribesman.reproductionCostIncrease[i] = (i - WorldProperties.BreedingCostsIncreaseAge) * WorldProperties.BreedingCostsIncreaseCoefficient; } ReportEndOfYearStatistics(); d.Invoke(new Action(delegate() { StatisticsCollector.ConsolidateNewYear(); })); Tribesman.UseGompertzAgeing = WorldProperties.UseGompertzAgeing > 0.5; }
public void MemberDie(Tribesman member) { member.Release(); MemberLeaves(member); }
public void MemberLeaves(Tribesman member) { member.MyTribe = null; members.Remove(member); }