예제 #1
0
        public static StarMap initializeNewMap()
        {
            Console.WriteLine("Map Init Started");
            StarMap map = new StarMap();

            map.systems = new List <System>();
            foreach (string filePaths in Directory.GetFiles(systemDataFilePath))
            {
                string  originalJson    = File.ReadAllText(filePaths);
                JObject originalJObject = JObject.Parse(originalJson);
                Faction owner           = (Faction)Enum.Parse(typeof(Faction), (string)originalJObject["Owner"]);

                FactionControl ownerControl = new FactionControl();
                ownerControl.faction = owner;
                if (owner != Faction.NoFaction)
                {
                    ownerControl.percentage = 100;
                }
                else
                {
                    ownerControl.percentage = 0;
                }

                System system = new System();
                system.controlList = new List <FactionControl>();
                system.name        = (string)originalJObject["Description"]["Name"];
                system.controlList.Add(ownerControl);

                map.systems.Add(system);
            }
            return(map);
        }
예제 #2
0
        public System GetSystem(string name)
        {
            WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin", "*");
            StarMap map = Helper.LoadCurrentMap();

            return(map.FindSystemByName(name));;
        }
예제 #3
0
        public string ResetStarMap()
        {
            Logger.LogLine("Init new Map");
            StarMap map = Helper.initializeNewMap();

            Holder.currentMap = map;
            Console.WriteLine("Save new Map");
            Helper.SaveCurrentMap(map);
            Console.WriteLine("Map reset Sucessfull");
            return("Reset Sucessfull");
        }
예제 #4
0
 public static void SaveCurrentMap(StarMap map)
 {
     (new FileInfo(currentMapFilePath)).Directory.Create();
     using (StreamWriter writer = new StreamWriter(currentMapFilePath, false)) {
         string json = JsonConvert.SerializeObject(map);
         writer.Write(json);
     }
     Console.WriteLine("Map Saved");
     if (Holder.lastBackup.AddHours(Helper.LoadSettings().HoursPerBackup) < DateTime.UtcNow)
     {
         using (StreamWriter writer = new StreamWriter(backupMapFilePath + DateTime.UtcNow.ToString("yyyy-dd-M--HH-mm-ss") + ".json", false)) {
             string json = JsonConvert.SerializeObject(map);
             writer.Write(json);
         }
         Holder.lastBackup = DateTime.UtcNow;
     }
 }
예제 #5
0
        public static StarMap LoadCurrentMap()
        {
            if (Holder.currentMap == null)
            {
                if (File.Exists(currentMapFilePath))
                {
                    using (StreamReader r = new StreamReader(currentMapFilePath)) {
                        string json = r.ReadToEnd();
                        Holder.currentMap = JsonConvert.DeserializeObject <StarMap>(json);
                    }
                }
                else
                {
                    Holder.currentMap = initializeNewMap();
                }
            }
            StarMap result = Holder.currentMap;

            return(result);
        }
예제 #6
0
        public override System PostMissionResult(MissionResult mresult, string companyName)
        {
            lock (_missionResultLock) {
                try {
                    // TODO: Update connection data in a cleaner fashion
                    string   ip         = Helper.MapRequestIP();
                    string   hashedIP   = String.Format("{0:X}", ip.GetHashCode());
                    DateTime reportTime = DateTime.UtcNow;
                    // TODO: For now, use the IP as the playerId. In the future, GUID
                    Helper.RecordPlayerActivity(mresult, ip, companyName, reportTime);
                    int realDifficulty = 0;
                    // Check to see if the post is suspicious
                    if (Helper.LoadSettings().HardCodedDifficulty != 0)
                    {
                        realDifficulty = Helper.LoadSettings().HardCodedDifficulty;
                    }
                    else
                    {
                        realDifficulty = Math.Min(10, mresult.difficulty);
                    }
                    int realPlanets = Math.Min(Helper.LoadSettings().MaxPlanetSupport, mresult.planetSupport);
                    int realRep     = Math.Min(Helper.LoadSettings().MaxRep, mresult.awardedRep);
                    if ((Helper.LoadSettings().HalfSkullPercentageForWin *realDifficulty) + realRep + realPlanets > 50)
                    {
                        logger.Info("Suspicious result reported. See console.log for details.");
                        logger.Debug($"Suspicous result for IP:({ip})" +
                                     $" normalized difficulty:({realDifficulty}) planetSupport:({realPlanets}) reptuation:({realRep})" +
                                     $" for employer:({mresult.employer}) vs target:({mresult.target}) on system: ({mresult.systemName})" +
                                     $" with result:({mresult.result})"
                                     );
                    }
                    HistoryResult hresult = new HistoryResult {
                        date = reportTime
                    };

                    logger.Info($"New Mission Result for ({companyName}) on ({mresult.systemName})");
                    logger.Debug($"New MissionResult - ({companyName}) fought for ({mresult.employer}) against ({mresult.target})" +
                                 $" on ({mresult.systemName}) and achieved ({mresult.result})");

                    StarMap builtMap = StarMapStateManager.Build();
                    System  system   = builtMap.FindSystemByName(mresult.systemName);

                    FactionControl oldOwnerControl = system.FindHighestControl();
                    Faction        oldOwner        = Faction.INVALID_UNSET;
                    if (oldOwnerControl != null)
                    {
                        oldOwner = oldOwnerControl.faction;
                    }
                    FactionControl employerControl = system.FindFactionControlByFaction(mresult.employer);
                    FactionControl targetControl   = system.FindFactionControlByFaction(mresult.target);
                    logger.Debug($"Real rep - ({realRep}) and real planets ({realPlanets})");

                    if (mresult.result == BattleTech.MissionResult.Victory)
                    {
                        int gain       = (Helper.LoadSettings().HalfSkullPercentageForWin *realDifficulty) + realRep + realPlanets;
                        int realChange = 0;
                        if (employerControl.percentage >= Helper.LoadSettings().LowerFortBorder&&
                            employerControl.percentage <= Helper.LoadSettings().UpperFortBorder)
                        {
                            logger.Debug("Fort Rules");
                            realChange = Math.Min(
                                Math.Abs(employerControl.percentage - Helper.LoadSettings().UpperFortBorder),
                                Math.Max(1, (int)Math.Round(gain * Helper.LoadSettings().FortPercentage))
                                );
                        }
                        else
                        {
                            realChange = Math.Min(
                                Math.Abs(employerControl.percentage - Helper.LoadSettings().LowerFortBorder),
                                Math.Max(1, gain)
                                );
                        }
                        hresult.winner       = employerControl.faction;
                        hresult.loser        = targetControl.faction;
                        hresult.pointsTraded = realChange;
                        logger.Debug($"Victory for ({hresult.winner}) over ({hresult.loser})");
                        int fortLoss = 0;
                        while (targetControl.percentage > Helper.LoadSettings().LowerFortBorder&& realChange > 0)
                        {
                            targetControl.percentage--;
                            realChange--;
                            fortLoss++;
                        }
                        if (fortLoss > 0)
                        {
                            logger.Debug($"Fortification of ({hresult.loser}) lost {fortLoss} points.");
                        }
                        if (realChange > 0)
                        {
                            targetControl.percentage -= realChange;
                            if (targetControl.percentage < 0)
                            {
                                int leftover = Math.Abs(targetControl.percentage);
                                logger.Debug($"{leftover} points could not be removed from ({hresult.loser}) because its below 0.");
                                targetControl.percentage = 0;

                                int totalEnemyControl = 0;
                                foreach (FactionControl control in system.controlList)
                                {
                                    if (control.faction != employerControl.faction)
                                    {
                                        totalEnemyControl += control.percentage;
                                    }
                                }
                                if (totalEnemyControl != 0)
                                {
                                    realChange -= leftover;
                                }
                                else
                                {
                                    logger.Debug($"No other Factions on Planet.");
                                }
                            }
                            employerControl.percentage += realChange;
                            logger.Debug($"{realChange} points were traded.");
                        }
                    }
                    FactionControl afterBattleOwnerControl = system.FindHighestControl();
                    Faction        newOwner = afterBattleOwnerControl.faction;
                    if (oldOwner != newOwner)
                    {
                        hresult.planetSwitched = true;
                    }
                    else
                    {
                        hresult.planetSwitched = false;
                    }
                    hresult.system = mresult.systemName;
                    Holder.resultHistory.Add(hresult);
                    return(system);
                }
                catch (Exception e) {
                    logger.Warn(e, "Failed to process mission result!");
                    return(null);
                }
            }
        }
예제 #7
0
        // Thread-safe; returns copy of starmap. We clone to prevent modification during serialization (due to heavy nesting).
        public override System GetSystem(string name)
        {
            StarMap builtMap = StarMapStateManager.Build();

            return(builtMap.FindSystemByName(name));
        }
예제 #8
0
        // Thread-safe; returns copy of starmap. We clone to prevent modification during serialization (due to heavy nesting).
        public override StarMap GetStarmap()
        {
            StarMap builtMap = StarMapStateManager.Build();

            return(builtMap);
        }
예제 #9
0
        public System PostMissionResult(MissionResult mresult, string companyName)
        {
            try {
                int    realDifficulty = Math.Min(10, mresult.difficulty);
                string ip             = Helper.GetIP();
                int    realPlanets    = Math.Min(Helper.LoadSettings().MaxPlanetSupport, mresult.planetSupport);
                int    realRep        = Math.Min(Helper.LoadSettings().MaxRep, mresult.awardedRep);
                if ((Helper.LoadSettings().HalfSkullPercentageForWin *realDifficulty) + realRep + realPlanets > 50)
                {
                    Logger.LogToFile("Weird Result - Difficulty: " + realDifficulty + " - planet: " + realPlanets + " - rep: " + realRep + " - employer: " + mresult.employer + " - target: " + mresult.target + " - systemName: " + mresult.systemName + " - mresult: " + mresult.result + " - IP: " + ip);
                }
                HistoryResult hresult = new HistoryResult();
                hresult.date = DateTime.UtcNow;

                if (Helper.CheckUserInfo(ip, mresult.systemName, companyName))
                {
                    Logger.LogToFile("One ip trys to send Missions to fast. IP:" + ip);
                    return(null);
                }
                Logger.LogLine("New Result Posted");
                Console.WriteLine("employer: " + mresult.employer);
                Console.WriteLine("target: " + mresult.target);
                Console.WriteLine("systemName: " + mresult.systemName);
                Console.WriteLine("mresult: " + mresult.result);
                StarMap        map             = Helper.LoadCurrentMap();
                System         system          = map.FindSystemByName(mresult.systemName);
                FactionControl oldOwnerControl = system.FindHighestControl();
                Faction        oldOwner        = Faction.INVALID_UNSET;
                if (oldOwnerControl != null)
                {
                    oldOwner = oldOwnerControl.faction;
                }
                FactionControl employerControl = system.FindFactionControlByFaction(mresult.employer);
                FactionControl targetControl   = system.FindFactionControlByFaction(mresult.target);

                if (mresult.result == BattleTech.MissionResult.Victory)
                {
                    Console.WriteLine("Victory Result");
                    int realChange = Math.Min(Math.Abs(employerControl.percentage - 100), Math.Max(1, (Helper.LoadSettings().HalfSkullPercentageForWin *realDifficulty) + realRep + realPlanets));
                    hresult.winner              = employerControl.faction;
                    hresult.loser               = targetControl.faction;
                    hresult.pointsTraded        = realChange;
                    employerControl.percentage += realChange;
                    targetControl.percentage   -= realChange;
                    Console.WriteLine(realChange + " Points traded");
                    if (targetControl.percentage < 0)
                    {
                        int leftoverChange = Math.Abs(targetControl.percentage);
                        Console.WriteLine(leftoverChange + " Leftover Points");
                        targetControl.percentage = 0;
                        int debugcounter = leftoverChange;
                        while (leftoverChange > 0 && debugcounter != 0)
                        {
                            foreach (FactionControl leftOverFaction in system.controlList)
                            {
                                if (leftOverFaction.faction != mresult.employer &&
                                    leftOverFaction.faction != mresult.target && leftOverFaction.percentage > 0 &&
                                    leftoverChange > 0)
                                {
                                    leftOverFaction.percentage--;
                                    leftoverChange--;
                                    Console.WriteLine(leftOverFaction.faction.ToString() + " Points deducted");
                                }
                            }
                            debugcounter--;
                        }
                    }
                }
                else
                {
                    Console.WriteLine("Loss Result");
                    int realChange = Math.Min(employerControl.percentage, Math.Max(1, (Helper.LoadSettings().HalfSkullPercentageForLoss *realDifficulty) + realRep / 2 + realPlanets / 2));
                    hresult.winner              = targetControl.faction;
                    hresult.loser               = employerControl.faction;
                    hresult.pointsTraded        = realChange;
                    employerControl.percentage -= realChange;
                    targetControl.percentage   += realChange;
                    Console.WriteLine(realChange + " Points traded");
                }
                Helper.SaveCurrentMap(map);
                FactionControl afterBattleOwnerControl = system.FindHighestControl();
                Faction        newOwner = afterBattleOwnerControl.faction;
                if (oldOwner != newOwner)
                {
                    hresult.planetSwitched = true;
                }
                else
                {
                    hresult.planetSwitched = false;
                }
                hresult.system = mresult.systemName;
                Holder.resultHistory.Add(hresult);
                return(system);
            }
            catch (Exception e) {
                Logger.LogError(e);
                return(null);
            }
        }