예제 #1
0
        // Adds War to War Table
        public static void Add(War war)
        {
            Random rand = new Random();
            war.ID = rand.Next();

            ClanWars.Add(war);

            Write();
        }
예제 #2
0
파일: Player.cs 프로젝트: dwaby/Log
        public Player(Data.DataAccess database)
        {
            m_Database = database;

            List<Data.War> warsData = m_Database.GetItems<Data.War>();
            foreach (Data.War warData in warsData)
            {
                War war = new War(warData, m_Database);
                m_Wars.Add(war);
            }
        }
예제 #3
0
        public ActionResult Create(CreateWarViewModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    War newWar = new War();
                    newWar.EnemyClanName = model.EnemyClanName;
                    newWar.EnemyClanTag = model.EnemyClanTag;
                    newWar.Type = model.WarType;
                    newWar.StartDate = model.StartDate;
                    newWar.FinishedFlag = false;

                    WarManager.Add(newWar);

                    List<WarStat> stats = new List<WarStat>();
                    foreach(string id in model.WarMembers)
                    {
                        int memberId = 0;
                        int.TryParse(id, out memberId);

                        WarStat stat = new WarStat(newWar.ID, memberId);

                        stats.Add(stat);
                    }

                    WarManager.AddStats(stats);
                }
            }
            catch
            {
                return View(new CreateWarViewModel());
            }

            return RedirectToAction("EditMode");
        }
 public CaravanArrivalAction_AIAttackSettlement(MapParent target, War war)
 {
     this.mapParent = target;
     War            = war;
 }
예제 #5
0
 public WarGameEvent(War war, WarStatusEnum warStatus, GameTime time)
     : base(EventTypeEnum.War, time.Day, time.Time)
 {
     WarID     = war.ID;
     WarStatus = warStatus;
 }
예제 #6
0
        public void Handle(GameClient Session, ClientMessage Event)
        {
            // Session.SendNotification("Sorry. Diese Funktion ist im Moment noch nicht verfügbar! Wir arbeiten daran :)");
            Action <object> action2 = null;
            SnowStorm       War     = Session.GetClientMessageHandler().CheckAGame();

            if (War == null)
            {
                War = new SnowStorm(Session.GetHabbo());
            }
            if (!War.WarUsers.Contains(Session.GetHabbo()))
            {
                War.WarUsers.Add(Session.GetHabbo());
            }
            ServerMessage message = new ServerMessage(Outgoing.CreateWar);

            message.AppendInt32(-1);
            message.AppendString("SnowStorm level " + War.WarLevel);
            message.AppendInt32(0);
            message.AppendInt32(War.WarLevel);
            message.AppendInt32(2);
            message.AppendInt32(War.MaxUsers);
            message.AppendString(War.WarOwner.Username);
            message.AppendInt32(0x11);
            message.AppendInt32(War.WarUsers.Count);
            foreach (Habbo WarUser in War.WarUsers)
            {
                message.AppendInt32(WarUser.Id);
                message.AppendString(WarUser.Username);
                message.AppendString(WarUser.Figure);
                message.AppendString(WarUser.Gender.ToLower());
                message.AppendInt32(-1);
                message.AppendInt32(WarUser.SnowLevel);
                message.AppendInt32(WarUser.SnowPoints);
                message.AppendInt32(1);
            }
            message.AppendInt32(120);
            Session.SendMessage(message);
            //Session.GetHabbo().SnowUserId = War.WarUsers.Count;
            War.SendToStorm(Session.GetClientMessageHandler().AddToNewGame(War), false, Session.GetHabbo().Id);
            if (War.WarOwner == Session.GetHabbo())
            {
                if (action2 == null)
                {
                    action2 = delegate(object obj)
                    {
                        while (War.Countdown != 0)
                        {
                            War.Countdown--;
                            Thread.Sleep(1000);
                        }
                        try
                        {
                            this.StartGame(War);
                        }catch
                        {
                            foreach (Habbo h in War.WarUsers)
                            {
                                if (h != null && h.GetClient() != null)
                                {
                                    h.GetClient().SendNotification("Spiel wurde abgebrochen. Der Ersteller ist offline gegangen!");
                                }
                            }
                        }
                    };
                }
                Action <object> action = action2;
                new Task(action, "break").Start();
            }
            ServerMessage packet = new ServerMessage(Outgoing.StartCounter);

            packet.AppendInt32(War.Countdown);
            Session.SendMessage(packet);
        }
예제 #7
0
        public override int Effect(Deity creator)
        {
            Civilisation war_target = candidate_nations[rnd.Next(candidate_nations.Count)];

            // The war to be declared.
            War declared_war = new War("War of " + _commanded_nation.Name + " vs. " + war_target.Name, creator);

            declared_war.Attackers.Add(_commanded_nation);
            declared_war.Defenders.Add(war_target);

            // Add allies to the war. The order is important as all nations which are allied to both nations will side with the defender.
            foreach (Relations relation in war_target.Relationships)
            {
                if (relation.Status == RelationStatus.Allied)
                {
                    declared_war.Defenders.Add(relation.Target);
                }
            }

            foreach (Relations relation in _commanded_nation.Relationships)
            {
                if (relation.Status == RelationStatus.Allied)
                {
                    if (!declared_war.Defenders.Contains(relation.Target))
                    {
                        declared_war.Attackers.Add(relation.Target);
                    }
                }
            }


            List <WeightedObjects <WarGoal> >[] war_goals = new List <WeightedObjects <WarGoal> > [2];
            for (int i = 0; i < 2; i++)
            {
                war_goals[i] = new List <WeightedObjects <WarGoal> >();
                foreach (WarGoal war_goal in war_target.PossibleWarGoals)
                {
                    war_goals[i].Add(new WeightedObjects <WarGoal>(war_goal));
                }

                // determine the weights of each war goal. Certain types of polities can only take certain types of war goals.
                foreach (WeightedObjects <WarGoal> weighted_war_goal in war_goals[i])
                {
                    Civilisation taker, target;
                    if (i == 0)
                    {
                        taker  = _commanded_nation;
                        target = war_target;
                    }
                    else
                    {
                        taker  = war_target;
                        target = _commanded_nation;
                    }

                    weighted_war_goal.Object.Winner = taker;

                    if (taker.isNomadic)
                    {
                        if (target.isNomadic)
                        {
                            if (weighted_war_goal.Object.Type == WarGoalType.Conquest)
                            {
                                weighted_war_goal.Weight += Constants.WEIGHT_STANDARD_CHANGE;
                            }
                            else
                            if (weighted_war_goal.Object.Type == WarGoalType.VassalizeCity)
                            {
                                weighted_war_goal.Weight += Constants.WEIGHT_STANDARD_CHANGE;
                            }
                        }
                    }
                    else
                    {
                        if (target.isNomadic)
                        {
                            if (weighted_war_goal.Object.Type == WarGoalType.RemoveNomadicPresence)
                            {
                                weighted_war_goal.Weight += Constants.WEIGHT_STANDARD_CHANGE;
                            }
                        }
                        else
                        {
                            if (weighted_war_goal.Object.Type == WarGoalType.CityConquest)
                            {
                                weighted_war_goal.Weight += Constants.WEIGHT_STANDARD_CHANGE * 2;
                            }
                            if (weighted_war_goal.Object.Type == WarGoalType.Conquest)
                            {
                                weighted_war_goal.Weight += Constants.WEIGHT_STANDARD_CHANGE;
                            }
                        }
                    }
                }
            }

            List <WarGoal> weighted_war_goals = WeightedObjects <WarGoal> .ChooseHeaviestObjects(war_goals[0]);

            declared_war.WarGoalAttackers = weighted_war_goals[rnd.Next(weighted_war_goals.Count)];

            weighted_war_goals = WeightedObjects <WarGoal> .ChooseHeaviestObjects(war_goals[1]);

            declared_war.WarGoalDefenders = weighted_war_goals[rnd.Next(weighted_war_goals.Count)];


            // Add war to the list of ongoing conflicts.
            Program.State.OngoingWars.Add(declared_war);

            declared_war.Begin = Simulation.Time.Shuffle;

            // Add powers related to the war to connected deities.
            // attacker related
            // Only the war leader can surrender as only he stands to lose anything, all other participants can only white peace.
            creator.Powers.Add(new SurrenderWar(_commanded_nation, declared_war));
            foreach (Civilisation attacker in declared_war.Attackers)
            {
                creator.Powers.Add(new WhitePeace(attacker, declared_war));

                foreach (Civilisation defender in declared_war.Defenders)
                {
                    creator.Powers.Add(new AttackNation(attacker, defender, declared_war));
                }
            }


            // defender related
            declared_war.Defenders[0].Creator.Powers.Add(new SurrenderWar(declared_war.Defenders[0], declared_war));
            foreach (Civilisation defender in declared_war.Defenders)
            {
                defender.Creator.Powers.Add(new WhitePeace(defender, declared_war));

                foreach (Civilisation attacker in declared_war.Defenders)
                {
                    creator.Powers.Add(new AttackNation(defender, attacker, declared_war));
                }
            }
            creator.LastCreation = declared_war;

            Program.WorldHistory.AddRecord(RecordType.WarReport, declared_war, War.printWar);

            return(0);
        }
예제 #8
0
 public WarPrinter(War war, World world)
 {
     War   = war;
     World = world;
 }
예제 #9
0
        private void dgResults_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            Type   objectType = dgResults.Rows[e.RowIndex].DataBoundItem.GetType();
            string column     = dgResults.Columns[e.ColumnIndex].HeaderText;

            if (e.Value != null && e.Value.GetType().IsEnum)
            {
                e.Value = e.Value.GetDescription();
            }

            if (objectType == typeof(HistoricalFigure))
            {
                HistoricalFigure hf = dgResults.Rows[e.RowIndex].DataBoundItem as HistoricalFigure;
                if (column == "Kills")
                {
                    e.Value = hf.NotableKills.Count;
                }
                else if (column == "Abductions")
                {
                    e.Value = hf.Abductions.Count;
                }
                else if (column == "Battles")
                {
                    e.Value = hf.Battles.Count;
                }
                else if (column == "Beast Attacks")
                {
                    e.Value = hf.BeastAttacks.Count;
                }
                else if (column == "Age")
                {
                    int    age;
                    string deathYear;
                    if (hf.DeathYear == -1)
                    {
                        age       = World.Events.Last().Year - hf.BirthYear;
                        deathYear = "Present";
                    }
                    else
                    {
                        age       = hf.DeathYear - hf.BirthYear;
                        deathYear = hf.DeathYear.ToString();
                    }

                    e.Value = age + " (" + hf.BirthYear + " - " + deathYear + ")";
                }
                else if (column == "Events")
                {
                    e.Value = hf.FilteredEvents.Count + " / " + hf.Events.Count;
                }
            }
            else if (objectType == typeof(Entity))
            {
                Entity entity = dgResults.Rows[e.RowIndex].DataBoundItem as Entity;
                if (column == "Name")
                {
                    e.Value = entity.ToString();
                    if (entity.IsCiv)
                    {
                        e.Value += " <Civ>";
                    }
                    e.Value += " (" + entity.Race + ")";
                }
                else if (column == "Sites")
                {
                    e.Value = entity.CurrentSites.Count;
                }
                else if (column == "Lost Sites")
                {
                    e.Value = entity.LostSites.Count;
                }
                else if (column == "Population")
                {
                    e.Value = entity.Populations.Sum(population => population.Count);
                }
                else if (column == "Wars")
                {
                    e.Value = entity.Wars.Count;
                }
                else if (column == "Wins : Losses")
                {
                    e.Value = entity.WarVictories + " / " + entity.WarLosses;
                }
                else if (column == "Kills : Deaths")
                {
                    e.Value = entity.WarKills + " / " + entity.WarDeaths;
                }
                else if (column == "Events")
                {
                    e.Value = entity.FilteredEvents.Count + " / " + entity.Events.Count;
                }
            }
            else if (objectType == typeof(Site))
            {
                Site site = dgResults.Rows[e.RowIndex].DataBoundItem as Site;
                if (column == "Owner")
                {
                    if (e.Value == null)
                    {
                        e.Value = "";
                    }
                    else
                    {
                        e.Value = site.CurrentOwner;
                        if (site.CurrentOwner is Entity)
                        {
                            e.Value += " (" + ((Entity)site.CurrentOwner).Race + ")";
                        }
                    }
                }
                else if (column == "Previous Owners")
                {
                    e.Value = site.PreviousOwners.Count;
                }
                else if (column == "Deaths")
                {
                    e.Value = site.Deaths.Count;
                }
                else if (column == "Warfare")
                {
                    e.Value = site.Warfare.Count;
                }
                else if (column == "Population")
                {
                    e.Value = site.Populations.Sum(population => population.Count);
                }
                else if (column == "Beast Attacks")
                {
                    e.Value = site.BeastAttacks.Count;
                }
                else if (column == "Events")
                {
                    e.Value = site.FilteredEvents.Count + " / " + site.Events.Count;
                }
            }
            else if (objectType == typeof(WorldRegion))
            {
                WorldRegion region = dgResults.Rows[e.RowIndex].DataBoundItem as WorldRegion;
                if (column == "Battles")
                {
                    e.Value = region.Battles.Count;
                }
                else if (column == "Deaths")
                {
                    e.Value = region.Deaths.Count;
                }
                else if (column == "Events")
                {
                    e.Value = region.FilteredEvents.Count + " / " + region.Events.Count;
                }
            }
            else if (objectType == typeof(UndergroundRegion))
            {
                UndergroundRegion uregion = dgResults.Rows[e.RowIndex].DataBoundItem as UndergroundRegion;
                if (column == "Events")
                {
                    e.Value = uregion.FilteredEvents.Count + " / " + uregion.Events.Count;
                }
            }
            else if (objectType == typeof(War))
            {
                War war = dgResults.Rows[e.RowIndex].DataBoundItem as War;
                //if (column == "Battles") e.Value = war.Battles;
                if (column == "Length")
                {
                    e.Value = war.StartYear + " - ";
                    if (war.EndYear == -1)
                    {
                        e.Value += "Present";
                    }
                    else
                    {
                        e.Value += war.EndYear.ToString();
                    }
                    e.Value += " (" + war.Length + ")";
                }
                else if (column == "Attacker")
                {
                    e.Value = war.Attacker.ToString() + " (" + war.Attacker.Race + ")";
                }
                else if (column == "Defender")
                {
                    e.Value = war.Defender.ToString() + " (" + war.Defender.Race + ")";
                }
                else if (column == "Kills")
                {
                    e.Value = war.DefenderDeathCount + " / " + war.AttackerDeathCount;
                }
                else if (column == "Victories")
                {
                    e.Value = war.AttackerBattleVictories.Count + " / " + war.DefenderBattleVictories.Count;
                }
                else if (column == "Sites Lost")
                {
                    e.Value = war.DefenderConquerings.Count(conquering => conquering.Notable) + " / " + war.AttackerConquerings.Count(conquering => conquering.Notable);
                }
                else if (column == "Events")
                {
                    e.Value = war.FilteredEvents.Count + " / " + war.AllEvents.Count;
                }
            }
            else if (objectType == typeof(Battle))
            {
                Battle battle = dgResults.Rows[e.RowIndex].DataBoundItem as Battle;
                if (column == "Attacker")
                {
                    e.Value = battle.Attacker.ToString() + " (" + battle.Attacker.Race + ")";
                }
                else if (column == "Defender")
                {
                    e.Value = battle.Defender.ToString() + " (" + battle.Defender.Race + ")";
                }
                else if (column == "Deaths")
                {
                    e.Value = battle.DeathCount;
                }
                else if (column == "Combatants")
                {
                    e.Value = battle.AttackersAsList.Count + " / " + battle.DefendersAsList.Count;
                }
                else if (column == "Remaining")
                {
                    e.Value = battle.AttackersRemainingCount + " / " + battle.DefendersRemainingCount;
                }
                else if (column == "Conquering")
                {
                    if (battle.Conquering == null)
                    {
                        e.Value = "";
                    }
                    else
                    {
                        e.Value = battle.Conquering.ToString();
                    }
                }
                else if (column == "Events")
                {
                    e.Value = battle.FilteredEvents.Count + " / " + battle.AllEvents.Count;
                }
            }
            else if (objectType == typeof(SiteConquered))
            {
                SiteConquered conquering = dgResults.Rows[e.RowIndex].DataBoundItem as SiteConquered;
                if (column == "Name")
                {
                    e.Value = conquering.ToString();
                }
                else if (column == "Deaths")
                {
                    e.Value = conquering.Deaths.Count;
                }
                else if (column == "Events")
                {
                    e.Value = conquering.FilteredEvents.Count + " / " + conquering.AllEvents.Count;
                }
            }
            else if (objectType == typeof(BeastAttack))
            {
                BeastAttack attack = dgResults.Rows[e.RowIndex].DataBoundItem as BeastAttack;
                if (column == "Name")
                {
                    e.Value = attack.ToString();
                }
                else if (column == "Deaths")
                {
                    e.Value = attack.Deaths.Count;
                }
                else if (column == "Events")
                {
                    e.Value = attack.FilteredEvents.Count + " / " + attack.AllEvents.Count;
                }
            }
            else if (objectType == typeof(Artifact))
            {
                Artifact artifact = dgResults.Rows[e.RowIndex].DataBoundItem as Artifact;
                if (column == "Events")
                {
                    e.Value = artifact.Events.Count;
                }
            }

            //if (objectType.BaseType == typeof(WorldObject) && column == "Events")
            //    e.Value = (dgResults.Rows[e.RowIndex].DataBoundItem as WorldObject).Events.Count;
            //if (objectType.BaseType == typeof(EventCollection) && column == "Events")
            //    e.Value = (dgResults.Rows[e.RowIndex].DataBoundItem as EventCollection).AllEvents.Count;

            dgResults.Rows[e.RowIndex].HeaderCell.Value = (e.RowIndex + 1).ToString();
        }
예제 #10
0
    public void processOptionB()
    {
        eventDecisionTwoPanel.SetActive(false);
        closeToolTips();
        App    app         = UnityEngine.Object.FindObjectOfType <App>();
        int    playerIndex = app.GetHumanIndex();
        Nation player      = State.getNations()[playerIndex];
        Nation otherMajor  = State.getNation(currentEvent.OtherMajor);

        Province disputedProvince = State.getProvince(currentEvent.Province);
        Nation   otherNation      = State.getNation(currentEvent.OtherMajor);

        if (currentEvent.OtherMinor > -1)
        {
            otherNation = State.getNation(currentEvent.OtherMinor);
        }
        if (currentEvent.EventType == MyEnum.eventType.riotResponce)
        {
            nextEventTurn(player);
        }
        else if (currentEvent.EventType == MyEnum.eventType.referendumDemanded)
        {
            // Accept....
            if (eventLogic.referendum(player, otherNation, currentEvent.OtherMinor, disputedProvince))
            {
                // Province Leaves!
                DecisionEvent newEvent = new DecisionEvent();
                eventLogic.initializeProvinceLeaveEvent(newEvent, currentEvent);
                currentEvent = newEvent;
                showDecisionPanel(player);
            }
            else
            {
                DecisionEvent newEvent = new DecisionEvent();
                eventLogic.initializeProvinceStaysEvent(newEvent, currentEvent);
                currentEvent = newEvent;
                showDecisionPanel(player);
            }
        }


        else if (currentEvent.EventType == MyEnum.eventType.AI_Attacks)
        {
            otherMajor = State.getNation(currentEvent.OtherMajor);
            war        = new War(otherMajor, player, disputedProvince.getIndex(), currentEvent.OtherMinor);
            if (war.AmphibiousAttack)
            {
                DecisionEvent newEvent = new DecisionEvent();
                eventLogic.initializeDecideIfUseNavyDefend(newEvent, currentEvent);
                currentEvent = newEvent;
                showDecisionPanel(player);
            }
            prepareWarPanel(player, otherMajor, war);
        }

        else if (currentEvent.EventType == MyEnum.eventType.notificationOfCrackdown)
        {
            DecisionEvent newEvent = new DecisionEvent();
            eventLogic.initializeAskIfBoycott_AI_Event(newEvent, currentEvent);
            currentEvent = newEvent;
            showDecisionPanel(player);
        }

        else if (currentEvent.EventType == MyEnum.eventType.AI_RejectsReferendum)
        {
            // Don't declare war but maybe boycott
            DecisionEvent newEvent = new DecisionEvent();
        }

        else if (currentEvent.EventType == MyEnum.eventType.askIfBoycott)
        {
            PlayerPayer.loseFace(player);
        }

        else if (currentEvent.EventType == MyEnum.eventType.end)
        {
            nextEventTurn(player);
        }

        else if (currentEvent.EventType == MyEnum.eventType.AI_AcceptsReferendum)
        {
            DecisionEvent newEvent = new DecisionEvent();
            if (eventLogic.referendum(otherMajor, player, currentEvent.OtherMinor, disputedProvince))
            {
                eventLogic.initalizeAI_ReferendumVotesYes(newEvent, currentEvent);
                currentEvent = newEvent;
                showDecisionPanel(player);
            }
            else
            {
                eventLogic.initalizeAI_ReferendumVotesNo(newEvent, currentEvent);
                currentEvent = newEvent;
                showDecisionPanel(player);
            }
        }

        nextEventTurn(player);
    }
예제 #11
0
    public void respondToProvinceRiots(Nation nation, Province prov)
    {
        Debug.Log("Respond to Province Riots");
        int           numberOfDisruptedProvinces = PlayerCalculator.getNumberOfDisrputedProvinces(nation);
        bool          sameCulture           = true;
        int           nationWithSameCulture = nation.getIndex();
        EventRegister eventLogic            = State.eventRegister;

        App    app        = UnityEngine.Object.FindObjectOfType <App>();
        int    humanIndex = app.GetHumanIndex();
        Nation human      = State.getNations()[humanIndex];

        if (!nation.culture.Equals(prov.getCulture()))
        {
            sameCulture           = false;
            nationWithSameCulture = Utilities.findNationWithThisCulture(prov.getCulture());
        }

        if (prov.isColony)
        {
            if (nation.GetColonialPoints() > 0)
            {
                //crack down on riots
                nation.SpendColonialPoints(1);
            }
            else
            {
                prov.setRioting(true);
            }
        }
        else if (!prov.isColony)
        {
            if (sameCulture)
            {
                if (nation.InfulencePoints > 0)
                {
                    standardProvinceResponse(nation, prov, -1, -1);
                }
                else
                {
                    prov.setRioting(true);
                }
            }
            // Now consider cases where the prov is not a colony and does not share the same culture as its owner

            else if (!prov.isColony && !sameCulture)
            {
                if (nation.InfulencePoints > 0)
                {
                    Debug.Log("Not colony and not same culture");
                    //Consider who might get angry with the crackdown
                    int    otherNationIndex = Utilities.findNationWithThisCulture(prov.getCulture());
                    Nation otherNation      = State.getNation(otherNationIndex);
                    Debug.Log("Other Nation is: " + otherNation.getName());
                    int    minorNationIndex = -1;
                    Nation minorNation      = new Nation();
                    if (otherNation.getType() == MyEnum.NationType.minor)
                    {
                        minorNationIndex = otherNation.getIndex();
                        minorNation      = otherNation;
                        otherNationIndex = PlayerCalculator.getMostFavouredMajorNation(otherNation);
                        // The other nation is the guardian, not the owner of the nation
                        otherNation = State.getNation(otherNationIndex);
                    }
                    int otherStrength = 0;
                    int selfStrength  = PlayerCalculator.CalculateArmyScore(nation);
                    // Will anger another great power
                    int relations = nation.Relations[otherNationIndex];
                    //This value is just for tests
                    if (relations < 85)
                    {
                        Debug.Log("here");
                        standardProvinceResponse(nation, prov, otherNationIndex, minorNationIndex);
                    }
                    else
                    {
                        if (State.mapUtilities.shareLandBorder(nation, otherNation))
                        {
                            otherStrength = PlayerCalculator.CalculateArmyScore(otherNation);
                        }
                        else
                        {
                            otherStrength = PlayerCalculator.CalculateNavalProjection(otherNation);
                        }

                        if (otherStrength * 1.15 < selfStrength)
                        {
                            //Not too afraid
                            standardProvinceResponse(nation, prov, otherNationIndex, minorNationIndex);
                            if (demandReferendum(otherNation, nation, prov))
                            {
                                if (acceptRefDemand(nation, otherNation, prov))
                                {
                                    referendum(nation, otherNation, prov);
                                }
                                else
                                {
                                    //nation refuses to hold a referendum
                                    if (warOverRejection(otherNation, nation, prov))
                                    {
                                        War war = new War(otherNation, nation, prov.getIndex(), minorNationIndex);
                                        war.warBetweenAI(otherNation, nation);
                                    }
                                    else if (boycottOverRefDemandRejection(otherNation))
                                    {
                                        otherNation.addBoycott(nation.getIndex());
                                        //....................
                                    }
                                    else
                                    {
                                        // Backdown
                                        PlayerPayer.loseFace(otherNation);
                                    }
                                }
                            }
                        }

                        if (otherStrength * 1.3 < selfStrength)
                        {
                            // Prefer not to provicate other nation, but might do so if situation calls for it

                            int roll = Random.Range(1, 100);
                            if (roll < 50)
                            {
                                nation.InfulencePoints--;
                                prov.adjustDiscontentment(1);
                                if (otherNation.getIndex() == humanIndex)
                                {
                                    DecisionEvent newEvent = new DecisionEvent();
                                    if (minorNationIndex == -1)
                                    {
                                        eventLogic.initalizeInformedOfCrackdownEvent(newEvent, human, nation, prov);
                                    }
                                    else
                                    {
                                        eventLogic.initalizeInformedOfCrackdownEvent(newEvent, human, nation, prov, minorNationIndex);
                                    }
                                    eventLogic.DecisionEvents.Enqueue(newEvent);
                                }
                                else if (demandReferendum(otherNation, nation, prov))
                                {
                                    if (acceptRefDemand(nation, otherNation, prov))
                                    {
                                        referendum(nation, otherNation, prov);
                                    }
                                    else
                                    {
                                        if (warOverRejection(otherNation, nation, prov))
                                        {
                                            War war = new War(otherNation, nation, prov.getIndex(), minorNationIndex);
                                            war.warBetweenAI(otherNation, nation);
                                        }
                                    }
                                }
                                else
                                {
                                    prov.setRioting(true);
                                }
                            }

                            else
                            {
                                prov.setRioting(true);
                            }
                        }
                        else
                        {
                            // Don't want to f**k with these guys
                            prov.setRioting(true);
                        }
                    }
                }
                else
                {
                    Debug.Log("No Influence Points");
                    prov.setRioting(true);
                    // Just for now
                    nation.InfulencePoints++;
                }
            }
        }
    }
예제 #12
0
 /// <summary>
 ///     戦争情報を書き出す
 /// </summary>
 /// <param name="war">戦争情報</param>
 /// <param name="writer">ファイル書き込み用</param>
 private static void WriteWar(War war, TextWriter writer)
 {
     writer.WriteLine("  war = {");
     if (war.Id != null)
     {
         writer.Write("    id          = ");
         WriteTypeId(war.Id, writer);
         writer.WriteLine();
     }
     if (war.StartDate != null)
     {
         writer.Write("    date        = ");
         WriteDate(war.StartDate, writer);
         writer.WriteLine();
     }
     if (war.EndDate != null)
     {
         writer.Write("    enddate     = ");
         WriteDate(war.EndDate, writer);
         writer.WriteLine();
     }
     writer.WriteLine("    attackers   = {");
     if (war.Attackers.Id != null)
     {
         writer.Write("      id          = ");
         WriteTypeId(war.Attackers.Id, writer);
         writer.WriteLine();
     }
     writer.Write("      participant = {");
     WriteCountryList(war.Attackers.Participant, writer);
     writer.WriteLine(" }");
     writer.WriteLine("    }");
     writer.WriteLine("    defenders   = {");
     if (war.Defenders.Id != null)
     {
         writer.Write("      id          = ");
         WriteTypeId(war.Defenders.Id, writer);
         writer.WriteLine();
     }
     writer.Write("      participant = {");
     WriteCountryList(war.Defenders.Participant, writer);
     writer.WriteLine(" }");
     writer.WriteLine("    }");
     writer.WriteLine("  }");
 }
예제 #13
0
 public WhitePeace(Civilisation commanded_nation, War white_peace_war) : base(commanded_nation)
 {
     _white_peaced_war = white_peace_war;
     initialize();
 }
예제 #14
0
 public AttackNation(Civilisation commanded_nation, Civilisation target_nation, War war) : base(commanded_nation)
 {
     _attacked_nation = target_nation;
     _war             = war;
     initialize();
 }
예제 #15
0
 public void EndWar(War war, WarEndReason reason)
 {
     war.EndTime   = DateTime.UtcNow;
     war.EndReason = reason;
     Instance.OnDiplomacyChanged();
 }
예제 #16
0
    /// <summary>
    /// The main method contains multiple while loops allowing the Generals to choose when to end a war and whether to wage war again once a war has ended
    /// </summary>
    /// <param name="args"></param>
    static void Main(string[] args)
    {
        bool stillPlaying = true;


        ///first while loop which starts a new war if the Generals choose to do so after the end of a war
        while (stillPlaying)
        {
            bool warOver = false;

            Console.WriteLine("Enter the name of the first army General: ");
            string generalName1 = Console.ReadLine();
            Console.WriteLine("Enter the name of the second army General: ");
            string generalName2 = Console.ReadLine();

            War war = new War(generalName1, generalName2);


            ///second while loop that continues the game until one General wins or a truce is agreed upon
            while (!warOver)
            {
                if (war.counter > 500)
                {
                    Console.WriteLine("Generals, you have been waging war for " + war.counter.ToString() + " battles. You may want to declare a truce. Type \"yes\" to continue the war: ");
                }
                else
                {
                    Console.WriteLine("Please type \"yes\" if you would you like to continue the war: ");
                }

                Console.WriteLine("Type anything else to end the war and declare a truce");
                string play = Console.ReadLine();


                if (play == "yes" || play == "\"yes\"")
                {
                    bool proceed       = false;
                    int  battlesFought = 0;
                    Console.WriteLine("How many battles are you willing to fight? ");


                    ///third while loop which requires input for battles fought to be a number between 1-10,000
                    while (!proceed)
                    {
                        string inputString = Console.ReadLine();
                        bool   parsed      = Int32.TryParse(inputString, out battlesFought);

                        if (!parsed)
                        {
                            Console.WriteLine("'{0}' is not a valid number. Please enter a new number", inputString);
                        }
                        else if (parsed)
                        {
                            battlesFought = Int32.Parse(inputString);
                            if (battlesFought > 10000 || battlesFought < 1)
                            {
                                Console.WriteLine("Your Leiutenant suggests waging between 1 and 10,000 battles. '{0}' battles would be ridiculous", inputString);
                            }
                            else
                            {
                                proceed = true;
                            }
                        }
                    }

                    Console.WriteLine();


                    for (int turn = 0; turn < battlesFought; turn = turn + 1)

                    {
                        war.Battle();
                        warOver = war.EndWar();
                        if (warOver == true)
                        {
                            break;
                        }
                    }
                }
                else
                {
                    war.truce = true;
                    warOver   = war.EndWar();
                    if (warOver == true)
                    {
                        break;
                    }
                }
            }

            Console.WriteLine("The War has ended. Should a new war begin?");
            Console.WriteLine("Type \"yes\" to play again or type anything else to exit");
            string playAgain = Console.ReadLine();


            if (playAgain == "yes" || playAgain == "\"yes\"")
            {
                continue;
            }
            else
            {
                stillPlaying = false;
            }
        }
    }
예제 #17
0
 public static byte[] WarToByteArray(War war)
 {
     return(SD.JoinSegs2Seg(SD.SegString(war.id), SD.SegInt(war.regEndBlock)));
 }
예제 #18
0
        /// <summary>
        ///     編集項目の値を取得する
        /// </summary>
        /// <param name="itemId">項目ID</param>
        /// <param name="war">戦争</param>
        /// <returns>編集項目の値</returns>
        public object GetItemValue(ScenarioEditorItemId itemId, War war)
        {
            switch (itemId)
            {
                case ScenarioEditorItemId.WarStartYear:
                    return war.StartDate?.Year;

                case ScenarioEditorItemId.WarStartMonth:
                    return war.StartDate?.Month;

                case ScenarioEditorItemId.WarStartDay:
                    return war.StartDate?.Day;

                case ScenarioEditorItemId.WarEndYear:
                    return war.EndDate?.Year;

                case ScenarioEditorItemId.WarEndMonth:
                    return war.EndDate?.Month;

                case ScenarioEditorItemId.WarEndDay:
                    return war.EndDate?.Day;

                case ScenarioEditorItemId.WarType:
                    return war.Id?.Type;

                case ScenarioEditorItemId.WarId:
                    return war.Id?.Id;

                case ScenarioEditorItemId.WarAttackerType:
                    return war.Attackers?.Id?.Type;

                case ScenarioEditorItemId.WarAttackerId:
                    if (war.Id == null)
                    {
                        return null;
                    }
                    return war.Attackers.Id.Id;

                case ScenarioEditorItemId.WarDefenderType:
                    return war.Defenders?.Id?.Type;

                case ScenarioEditorItemId.WarDefenderId:
                    if (war.Id == null)
                    {
                        return null;
                    }
                    return war.Defenders.Id.Id;
            }

            return null;
        }
예제 #19
0
        public static MvcHtmlString Create(War war, string @class = null)
        {
            string name = (war.IsRessistanceWar ? "ressistance " : "") + "war";

            return(LinkCreator.Create($"{name} #{war.ID}", "view", "war", new { warID = war.ID }, @class));
        }
예제 #20
0
 /// <summary>
 ///     編集項目の編集済みフラグを取得する
 /// </summary>
 /// <param name="itemId">項目ID</param>
 /// <param name="war">戦争</param>
 /// <returns>編集済みフラグ</returns>
 public bool IsItemDirty(ScenarioEditorItemId itemId, War war)
 {
     return war.IsDirty((War.ItemId) ItemDirtyFlags[(int) itemId]);
 }
예제 #21
0
    private void _updateWarPanel(Nation human, Nation ai, War war)
    {
        Nation attacker = State.getNation(war.AttackerIndex);
        Nation defender = State.getNation(war.DefenderIndex);

        Debug.Log("__Update war panel");
        if (war.Phase == MyEnum.warPhase.information)
        {
            phase_or_round.text = "Phase I: Information Gathering";
        }
        if (war.Phase == MyEnum.warPhase.tactic)
        {
            phase_or_round.text = "Phase II: Generals Decide on Tactics";
        }
        else if (war.Phase == MyEnum.warPhase.maneuver)
        {
            phase_or_round.text = "Phase III: Army Maneuvers to Execute Commands";
        }
        else if (war.Phase == MyEnum.warPhase.engagement)
        {
            phase_or_round.text = "Phase IV: Army Engages Enemy: Round: " + war.Round;
        }
        else if (war.Phase == MyEnum.warPhase.conclusion)
        {
            phase_or_round.text = "Phase V: Conclusion";
        }

        UpdateWarPanelSideInfo(human, ai, war);

        if (war.AttackerIndex == human.getIndex())
        {
            playerRecon.isOn          = war.AttackerRecon;
            playerEsopinage.isOn      = war.AttackerIntel;
            playerJudgement.isOn      = war.AttackerJudgement;
            playerTactics.text        = war.AttackerTactics.ToString();
            playerManouver.isOn       = war.AttackerManeuver;
            playerCombatModifier.text = war.AttackerDmgModifier.ToString();

            aiRecon.isOn          = war.DefenderRecon;
            aiEspionage.isOn      = war.DefenderIntel;
            aiJudgement.isOn      = war.DefenderJudgement;
            aiTactics.text        = war.DefenderTactics.ToString();
            aiManeuver.isOn       = war.DefenderManeuver;
            aiCombatModifier.text = war.DefenderDmgModifier.ToString();
        }
        else
        {
            playerRecon.isOn          = war.DefenderRecon;
            playerEsopinage.isOn      = war.DefenderIntel;
            playerJudgement.isOn      = war.DefenderJudgement;
            playerTactics.text        = war.DefenderTactics.ToString();
            playerManouver.isOn       = war.DefenderManeuver;
            playerCombatModifier.text = war.DefenderDmgModifier.ToString();

            aiRecon.isOn          = war.AttackerRecon;
            aiEspionage.isOn      = war.AttackerIntel;
            aiJudgement.isOn      = war.AttackerJudgement;
            aiTactics.text        = war.AttackerTactics.ToString();
            aiManeuver.isOn       = war.AttackerManeuver;
            aiCombatModifier.text = war.AttackerDmgModifier.ToString();
        }

        MyEnum.warPhase phase  = war.Phase;
        string          report = "";

        if (phase == MyEnum.warPhase.information)
        {
            if (playerRecon.isOn)
            {
                report += "Our reconnaissance has detected " + ai.getNationName() + "'s forces.\n";
            }
            else
            {
                report += "Our reconnaissance have been unable to detect the movements of " + ai.getNationName() + "'s forces.\n";
            }
            if (playerEsopinage.isOn)
            {
                report += human.getNationName() + "We have gained valuable information on the enemies’ plans.\n";
            }
            else
            {
                report += "Our useless intelligence operatives have failed to obtain any critical information regarding the" +
                          "enemies' plans.\n";
            }

            if (aiRecon.isOn)
            {
                report += "The movement our our forces have been detected by enemy reconnaissance.\n";
            }
            else
            {
                report += "Our forces were not detected by reconnaissance.\n";
            }

            if (aiEspionage.isOn)
            {
                report += "It seems that the enemy somehow got a hold of our battle plans.\n";
            }
            else
            {
                report += "The enemy appears to have no valuable information regarding our battle plans.\n";
            }
        }

        else if (phase == MyEnum.warPhase.tactic)
        {
            if (aiJudgement.isOn)
            {
                report += ai.getNationName() + "' generals have displayed tremendous tactical insight.\n";
            }
            else
            {
                report += ai.getNationName() + "' generals seem to have dipped a little too deep into the brandy bottle today.\n";
            }
            if (playerJudgement.isOn)
            {
                report += " Our generals have seized the moment and drawn up some excellent war plans. \n";
            }
            else
            {
                report += " Our generals have drawn up some underwhelming plans. \n";
            }
        }

        else if (phase == MyEnum.warPhase.maneuver)
        {
            if (playerManouver.isOn)
            {
                report += "We managed to out maneuver the enemie's forces!\n";
            }
            else if (aiManeuver.isOn)
            {
                report += "Drat! Our army has been out-maneuvered by those of " + ai.getName() + ".\n";
            }
            else
            {
                report += "Neither army has conducted is maneuver especially well.\n";
            }
        }

        else if (phase == MyEnum.warPhase.engagement)
        {
            if (war.AttackerIndex == human.getIndex())
            {
                report += "We destroyed " + war.AttackerAttackDamage + " enemy units during this round.\n";
                report += "We lost " + war.DefenderAttackDamage + " units this round.\n";
                report += "Our assult reduced enemy morale by " + war.AttackerShockDamage + " this round.\n";
                report += "Our army's morale was reduced by " + war.DefenderShockDamage + " this round.\n";
            }
            else
            {
                report += "We destroyed " + war.DefenderAttackDamage + " enemy units during this round.\n";
                report += "We lost " + war.AttackerAttackDamage + " units this round.\n";
                report += "Our assult reduced enemy morale by " + war.DefenderShockDamage + " this round.\n";
                report += "Our army's morale was reduced by " + war.AttackerShockDamage + " this round.\n";
            }
        }
        else if (phase == MyEnum.warPhase.conclusion)
        {
            bool defenderWon = war.defenderWon();
            if (war.AttackerIndex == human.getIndex())
            {
                // player is attacker
                if (defenderWon)
                {
                    if (war.AttackerForces == 0)
                    {
                        report += "Alas! Our forces have been completely destroyed! The battle is lost.\n";
                    }
                    else
                    {
                        report += "After being decisively outfought, our forces have been forced to retreat.";
                    }
                }
                else
                {
                    if (war.DefenderForces == 0)
                    {
                        report += "Our proud army had completely annihilated what had been " + defender.getName() + "'s pathetic forces!";
                    }
                    else
                    {
                        report += "After being outlcassed by our capable military, " + defender.getName() + "'s forces had no choice but to flee the field.";
                    }
                }
            }
            else
            {
                // Player is the defender
                if (defenderWon)
                {
                    if (war.AttackerForces == 0)
                    {
                        report += "Alas! Our forces have been completely destroyed! The battle is lost.\n";
                    }
                    else
                    {
                        report += "After being outlcassed by our capable military, " + defender.getName() + "'s forces had no choice but to flee the field.";
                    }
                }
                else
                {
                    if (war.DefenderForces == 0)
                    {
                        report += "Our proud army had completely annihilated what had been " + defender.getName() + "'s pathetic forces!";
                    }
                    else
                    {
                        report += "After being decisively outfought, our forces have been forced to retreat.";
                    }
                }
            }
        }
        phaseRoundReport.text = report;
    }
예제 #22
0
        public static void RegisterEnemyNoteCommands(CommandService commands, DiscordClient discord)
        {
            commands.CreateGroup("enemy note", cgb =>
            {
                cgb.Category("=== ENEMY NOTES COMMANDS ===");
                cgb.CreateCommand("list")
                .Description("!enemy note list - list all enemy base notes")
                .Alias(new string[] { "-l" })
                .AddCheck((command, user, channel) => !user.IsBot)
                .Do(async(e) =>
                {
                    #region enemy note list
                    try
                    {
                        ClasherDynastyDataContext dc = new ClasherDynastyDataContext();
                        List <EnemyBasesView> res    = new List <EnemyBasesView>();
                        res = (from ebv in dc.EnemyBasesViews select ebv).ToList();

                        string message = "ENEMY BASE NOTES: \n";
                        foreach (EnemyBasesView eb in res)
                        {
                            if (eb.NOTES != null && eb.NOTES != "")
                            {
                                message += "BASE: #" + eb.BASE__
                                           + ((eb.CLAIMED_BY == null) ? " | NOT CLAIMED" : " | CLAIMED BY: " + eb.CLAIMED_BY)
                                           + ((eb.ATTACKS == 0) ? "" : (" | ATTACKS: " + eb.ATTACKS
                                                                        + " | BEST ATTACK: " + eb.BEST
                                                                        + " | STARS: " + eb.STARS
                                                                        + " | DAMAGE: " + eb.DAMAGE + "%"))
                                           + ((eb.NOTES == null) ? "" : (" | NOTES: " + eb.NOTES)) + "\n";
                            }
                        }

                        await e.Channel.SendMessage(message);
                    }
                    catch (Exception ex) { discord.Log.Error("RegisterDisplayEnemyBaseNotes", ex.Message); }
                    #endregion
                });

                cgb.CreateCommand("add")
                .Description("!enemy note add [base number] ['note'] - add a note to the enemy war base.")
                .Alias(new string[] { "-a" })
                .AddCheck((command, user, channel) => !user.IsBot)
                .Parameter("Base", ParameterType.Required)
                .Parameter("Note", ParameterType.Required)
                .Do(async(e) =>
                {
                    #region enemy note add
                    try
                    {
                        ClasherDynastyDataContext dc = new ClasherDynastyDataContext();
                        War curWar = new War();
                        curWar     = (from w in dc.Wars
                                      orderby w.Date descending
                                      select w).Take(1).SingleOrDefault();

                        EnemyBase eb = new EnemyBase();
                        eb           = (from b in dc.EnemyBases
                                        where b.WarID == curWar.WarID &&
                                        b.EnemyBaseNo.ToString() == e.GetArg("Base")
                                        select b).SingleOrDefault();


                        eb.Notes = e.GetArg("Note");

                        dc.SubmitChanges();

                        await e.Channel.SendMessage("NOTE ADDED TO ENEMY BASE #" + e.GetArg("Base"));
                    }
                    catch (Exception ex) { discord.Log.Error("RegisterAddBaseNoteCommand", ex.Message); }
                    #endregion
                });

                cgb.CreateCommand("remove")
                .Description("!enemy note remove [base number] - remove the note from the enemy war base.")
                .Alias(new string[] { "-r" })
                .AddCheck((command, user, channel) => !user.IsBot)
                .Parameter("Base", ParameterType.Required)
                .Do(async(e) =>
                {
                    #region enemy note remove
                    try
                    {
                        ClasherDynastyDataContext dc = new ClasherDynastyDataContext();
                        War curWar = new War();
                        curWar     = (from w in dc.Wars
                                      orderby w.Date descending
                                      select w).Take(1).SingleOrDefault();

                        EnemyBase eb = new EnemyBase();
                        eb           = (from b in dc.EnemyBases
                                        where b.WarID == curWar.WarID &&
                                        b.EnemyBaseNo.ToString() == e.GetArg("Base")
                                        select b).SingleOrDefault();


                        eb.Notes = null;

                        dc.SubmitChanges();

                        await e.Channel.SendMessage("NOTE REMOVED FROM ENEMY BASE #" + e.GetArg("Base"));
                    }
                    catch (Exception ex) { discord.Log.Error("RegisterRemoveBaseNoteCommand", ex.Message); }
                    #endregion
                });
            });
        }
예제 #23
0
        static void GetWars_ESI()
        {
            var ourWars    = new List <long>();
            var removeWars = new List <long>();

            try
            {
                ourWars = Properties.Settings.Default.CurrentWars.Split(',').Select(s => Int64.Parse(s)).ToList();
            }
            catch (Exception ex)
            {
            }
            var atWar   = ourWars.Any();
            var counter = 0;

            var allWars = War.GetWarIds().OrderBy(w => w).ToList();

            var newWars = allWars.Where(w => w > Properties.Settings.Default.LastMessageId).ToList();

            Console.WriteLine(string.Format("Starting at war ID {0}", (Properties.Settings.Default.LastMessageId + 1).ToString()));

            newWars.ForEach(w =>
            {
                if (!ourWars.Contains(w))
                {
                    if (counter == 20)
                    {
                        System.Threading.Thread.Sleep(6000);
                        counter = 0;
                    }
                    try
                    {
                        var x = PingWar(w, "Started");
                        if (x.HasValue)
                        {
                            ourWars.Add(x.Value);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                    finally { counter++; }
                }
            });

            ourWars.ForEach(f =>
            {
                var warDeets = new War(f);
                if (warDeets.EndTime.HasValue && warDeets.EndTime.Value < DateTime.UtcNow)
                {
                    PingWar(f, "Ended");
                    removeWars.Add(f);
                }
            });
            ourWars = ourWars.Except(removeWars).ToList();

            if (ourWars.Any() && atWar != ourWars.Any())
            {
                Slack.Plugin.SetChannelTopic(Properties.Settings.Default.Group, Properties.Settings.Default.Room,
                                             Properties.Settings.Default.Token, WarMessage);
            }
            else if (!ourWars.Any() && atWar != ourWars.Any())
            {
                Slack.Plugin.SetChannelTopic(Properties.Settings.Default.Group, Properties.Settings.Default.Room,
                                             Properties.Settings.Default.Token, NoWarMessage);
            }

            Properties.Settings.Default.CurrentWars = String.Join(",", ourWars.Select(i => i.ToString()).ToArray());

            if (allWars.Count() > 0)
            {
                Properties.Settings.Default.LastMessageId = allWars.Max();
            }
            Properties.Settings.Default.Save();
        }
예제 #24
0
        /// <summary>
        ///     戦争の新規ボタン押下時の処理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnWarNewButtonClick(object sender, EventArgs e)
        {
            Scenario scenario = Scenarios.Data;
            List<War> wars = scenario.GlobalData.Wars;

            // 戦争リストに項目を追加する
            War war = new War
            {
                StartDate = new GameDate(),
                EndDate = new GameDate(),
                Id = Scenarios.GetNewTypeId(Scenarios.DefaultWarType, 1),
                Attackers = new Alliance { Id = Scenarios.GetNewTypeId(Scenarios.DefaultWarType, 1) },
                Defenders = new Alliance { Id = Scenarios.GetNewTypeId(Scenarios.DefaultWarType, 1) }
            };
            wars.Add(war);

            // 戦争リストビューに項目を追加する
            ListViewItem item = new ListViewItem { Tag = war };
            item.SubItems.Add("");
            warListView.Items.Add(item);

            Log.Info("[Scenario] war added ({0})", warListView.Items.Count - 1);

            // 編集済みフラグを設定する
            war.SetDirty(War.ItemId.StartYear);
            war.SetDirty(War.ItemId.StartMonth);
            war.SetDirty(War.ItemId.StartDay);
            war.SetDirty(War.ItemId.EndYear);
            war.SetDirty(War.ItemId.EndMonth);
            war.SetDirty(War.ItemId.EndDay);
            war.SetDirty(War.ItemId.Type);
            war.SetDirty(War.ItemId.Id);
            war.SetDirty(War.ItemId.AttackerType);
            war.SetDirty(War.ItemId.AttackerId);
            war.SetDirty(War.ItemId.DefenderType);
            war.SetDirty(War.ItemId.DefenderId);
            Scenarios.SetDirty();

            // 追加した項目を選択する
            if (warListView.SelectedIndices.Count > 0)
            {
                ListViewItem prev = warListView.SelectedItems[0];
                prev.Focused = false;
                prev.Selected = false;
            }
            item.Focused = true;
            item.Selected = true;
        }
예제 #25
0
        /// <summary>
        ///     編集項目の値が有効かどうかを判定する
        /// </summary>
        /// <param name="itemId">項目ID</param>
        /// <param name="val">編集項目の値</param>
        /// <param name="war">戦争</param>
        /// <returns>編集項目の値が有効でなければfalseを返す</returns>
        public bool IsItemValueValid(ScenarioEditorItemId itemId, object val, War war)
        {
            switch (itemId)
            {
                case ScenarioEditorItemId.WarStartYear:
                case ScenarioEditorItemId.WarEndYear:
                    if (((int) val < GameDate.MinYear) || ((int) val > GameDate.MaxYear))
                    {
                        return false;
                    }
                    break;

                case ScenarioEditorItemId.WarStartMonth:
                case ScenarioEditorItemId.WarEndMonth:
                    if (((int) val < GameDate.MinMonth) || ((int) val > GameDate.MaxMonth))
                    {
                        return false;
                    }
                    break;

                case ScenarioEditorItemId.WarStartDay:
                case ScenarioEditorItemId.WarEndDay:
                    if (((int) val < GameDate.MinDay) || ((int) val > GameDate.MaxDay))
                    {
                        return false;
                    }
                    break;
                case ScenarioEditorItemId.WarType:
                    if ((war.Id != null) && Scenarios.ExistsTypeId((int) val, war.Id.Id))
                    {
                        return false;
                    }
                    break;

                case ScenarioEditorItemId.WarId:
                    if ((war.Id != null) && Scenarios.ExistsTypeId(war.Id.Type, (int) val))
                    {
                        return false;
                    }
                    break;

                case ScenarioEditorItemId.WarAttackerType:
                    if (war.Attackers?.Id != null && Scenarios.ExistsTypeId((int) val, war.Attackers.Id.Id))
                    {
                        return false;
                    }
                    break;

                case ScenarioEditorItemId.WarAttackerId:
                    if (war.Attackers?.Id != null && Scenarios.ExistsTypeId(war.Attackers.Id.Type, (int) val))
                    {
                        return false;
                    }
                    break;

                case ScenarioEditorItemId.WarDefenderType:
                    if (war.Defenders?.Id != null && Scenarios.ExistsTypeId((int) val, war.Defenders.Id.Id))
                    {
                        return false;
                    }
                    break;

                case ScenarioEditorItemId.WarDefenderId:
                    if (war.Defenders?.Id != null && Scenarios.ExistsTypeId(war.Defenders.Id.Type, (int) val))
                    {
                        return false;
                    }
                    break;
            }

            return true;
        }
예제 #26
0
        public void CheckClanWar()
        {
            Logger.Instance.AddLog(LogType.Info, "部落战检测系统启动");
            DateTime lastBackup = DateTime.MinValue;

            computer.Open();
            computer.CPUEnabled = true;
            computer.RAMEnabled = true;
            do
            {
                try
                {
                    foreach (var hardware in computer.Hardware)
                    {
                        switch (hardware.HardwareType)
                        {
                        case HardwareType.CPU:
                            hardware.Update();
                            var value = GetLoad(hardware);
                            if (value != null)
                            {
                                BaseData.Instance.cpuUsage = value.Value;
                            }
                            BaseData.Instance.cpuName = hardware.Name;
                            break;

                        case HardwareType.RAM:
                            hardware.Update();
                            value = GetLoad(hardware);
                            if (value != null)
                            {
                                BaseData.Instance.ramUsage = value.Value;
                            }
                            break;
                        }
                    }
                    Thread.Sleep(1000);
                    if ((DateTime.Now.Minute == 0 || DateTime.Now.Minute == 30) && DateTime.Now.Second == 0)
                    {
                        ICocCoreClans   clan    = BaseData.Instance.container.Resolve <ICocCoreClans>();
                        ICocCorePlayers players = BaseData.Instance.container.Resolve <ICocCorePlayers>();
                        try
                        {
                            foreach (var clanID in BaseData.Instance.config["部落冲突"])
                            {
                                if (clanID.KeyName.All(char.IsDigit))
                                {
                                    if (lastBackup.Date != DateTime.Now.Date)
                                    {
                                        try
                                        {
                                            Logger.Instance.AddLog(LogType.Info, "正在备份资料...");
                                            //BackUp our game Data
                                            if (!Directory.Exists("com.coc.groupadmin\\BackUp\\" + clanID.KeyName))
                                            {
                                                Directory.CreateDirectory("com.coc.groupadmin\\BackUp\\" + clanID.KeyName);
                                            }
                                            foreach (var file in Directory.GetFiles("com.coc.groupadmin\\" + clanID.KeyName))
                                            {
                                                if (File.Exists(file.Replace("com.coc.groupadmin\\", "com.coc.groupadmin\\BackUp\\")))
                                                {
                                                    File.Delete(file.Replace("com.coc.groupadmin\\", "com.coc.groupadmin\\BackUp\\"));
                                                }
                                                File.Copy(file, file.Replace("com.coc.groupadmin\\", "com.coc.groupadmin\\BackUp\\"));
                                            }
                                            lastBackup = DateTime.Now;
                                        }
                                        catch
                                        {
                                        }
                                    }
                                    try
                                    {
                                        if (long.TryParse(clanID.KeyName, out long value))
                                        {
                                            if (DateTime.Now.Month == 1 && DateTime.Now.Day == 1 && DateTime.Now.Hour == 0 && DateTime.Now.Minute == 0 && DateTime.Now.Second == 0)
                                            {
                                                //新年快乐
                                                Session.SendGroupMessage(value, new AtAllMessage(), new PlainMessage("我tm祝各位tm的" + DateTime.Now.Year + "新年快乐"));
                                            }
                                            if (!War.ContainsKey(value) || War[value] == null)
                                            {
                                                var clanData = clan.GetCurrentWar(clanID.Value);
                                                if (clanData.State.ToLower() == "preparation")
                                                {
                                                    //New thread
                                                    Thread t = new Thread(() => {
                                                        Session.SendGroupMessage(Convert.ToInt64(clanID.KeyName), new AtAllMessage(), new PlainMessage("部落战已进入准备日!"));
                                                        var wait = clanData.EndTime.ToLocalTime() - DateTime.Now - new TimeSpan(23, 0, 0);
                                                        Logger.Instance.AddLog(LogType.Debug, "部落战当前准备日,还需要等待" + wait.Days + "天" + wait.Hours + "小时" + wait.Minutes + "分钟" + wait.Seconds + "秒");
                                                        if (wait.TotalSeconds > 0)
                                                        {
                                                            Thread.Sleep(wait);
                                                            Session.SendGroupMessage(Convert.ToInt64(clanID.KeyName), new AtAllMessage(), new PlainMessage("部落战已开始!"));
                                                        }
                                                        return;
                                                    });
                                                    t.IsBackground = true;
                                                    if (War.ContainsKey(value))
                                                    {
                                                        War[value] = t;
                                                    }
                                                    else
                                                    {
                                                        War.Add(value, t);
                                                    }
                                                    t.Start();
                                                }
                                                else if (clanData.State.ToLower() == "inwar")
                                                {
                                                    Thread t = new Thread(() => {
                                                        var wait = clanData.EndTime.ToLocalTime() - DateTime.Now;
                                                        Logger.Instance.AddLog(LogType.Debug, "部落战当前已开始,还需要等待" + wait.Days + "天" + wait.Hours + "小时" + wait.Minutes + "分钟" + wait.Seconds + "秒");
                                                        if (wait.TotalSeconds > 0)
                                                        {
                                                            Thread.Sleep(wait);
                                                            Session.SendGroupMessage(Convert.ToInt64(clanID.KeyName), new AtAllMessage(), new PlainMessage("部落战已结束!"));
                                                        }
                                                        return;
                                                    });
                                                    t.IsBackground = true;
                                                    if (War.ContainsKey(value))
                                                    {
                                                        War[value] = t;
                                                    }
                                                    else
                                                    {
                                                        War.Add(value, t);
                                                    }
                                                    t.Start();
                                                }
                                            }
                                            else if (War[value].ThreadState == ThreadState.Stopped || War[value].ThreadState == ThreadState.Aborted || War[value].ThreadState == ThreadState.Suspended)
                                            {
                                                War[value] = null;
                                                GC.Collect();
                                                var clanData = clan.GetCurrentWar(clanID.Value);
                                                if (clanData.State.ToLower() == "preparation")
                                                {
                                                    //New thread
                                                    Thread t = new Thread(() => {
                                                        Session.SendGroupMessage(Convert.ToInt64(clanID.KeyName), new AtAllMessage(), new PlainMessage("部落战已进入准备日!"));
                                                        //Weird error which always more 12 hours
                                                        var wait = clanData.EndTime.ToLocalTime() - DateTime.Now - new TimeSpan(12, 0, 0);
                                                        Logger.Instance.AddLog(LogType.Debug, "部落战当前准备日,还需要等待" + wait.Days + "天" + wait.Hours + "小时" + wait.Minutes + "分钟" + wait.Seconds + "秒");
                                                        if (wait.TotalSeconds > 0)
                                                        {
                                                            Thread.Sleep(wait);
                                                            Session.SendGroupMessage(Convert.ToInt64(clanID.KeyName), new AtAllMessage(), new PlainMessage("部落战已开始!"));
                                                        }
                                                        return;
                                                    });
                                                    t.IsBackground = true;
                                                    War[value]     = t;
                                                    t.Start();
                                                }
                                                else if (clanData.State.ToLower() == "inwar")
                                                {
                                                    Thread t = new Thread(() => {
                                                        var wait = clanData.EndTime.ToLocalTime() - DateTime.Now;
                                                        Logger.Instance.AddLog(LogType.Debug, "部落战当前已开始,还需要等待" + wait.Days + "天" + wait.Hours + "小时" + wait.Minutes + "分钟" + wait.Seconds + "秒");
                                                        if (wait.TotalSeconds > 0)
                                                        {
                                                            Thread.Sleep(wait);
                                                            Session.SendGroupMessage(Convert.ToInt64(clanID.KeyName), new AtAllMessage(), new PlainMessage("部落战已结束!"));
                                                        }
                                                        return;
                                                    });
                                                    t.IsBackground = true;
                                                    War[value]     = t;
                                                    t.Start();
                                                }
                                            }
                                            var Members      = clan.GetClansMembers(clanID.Value);
                                            var GroupMembers = Session.GetGroupMemberListAsync(value).Result;
                                            foreach (var member in GroupMembers)
                                            {
                                                using var api = new GameAPI(value, member.Id, Session);
                                                foreach (var cd in api.Member.ClanData)
                                                {
                                                    var m = Members.Where(x => x.Tag == cd.ClanID || x.Tag.Replace("0", "O") == cd.ClanID || x.Tag.Replace("1", "I") == cd.ClanID || x.Tag.Replace("0", "O").Replace("1", "I") == cd.ClanID).FirstOrDefault();
                                                    if (m != null)
                                                    {
                                                        cd.InClan         = true;
                                                        cd.Name           = m.Name;
                                                        cd.LastSeenInClan = DateTime.Now;
                                                    }
                                                    else
                                                    {
                                                        cd.InClan = false;
                                                    }
                                                }
                                                if (api.Member.ClanData.Count == 1 && DateTime.Now.Hour == 0)
                                                {
                                                    Player player = players.GetPlayer(api.Member.ClanData.First().ClanID);
                                                    if (api.Member.Member.Card != BaseData.Instance.THLevels[player.TownHallLevel] + "本-" + player.Name)
                                                    {
                                                        Session.ChangeGroupMemberInfo(api.Member.Member.QQId, value, new GroupMemberCardInfo(BaseData.Instance.THLevels[player.TownHallLevel] + "本-" + player.Name, null));
                                                    }
                                                }
                                            }
                                        }
                                        else
                                        {
                                            Logger.Instance.AddLog(LogType.Error, "群号无法加载,资料出现错误");
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        Logger.Instance.AddLog(LogType.Error, clanID.KeyName + ": " + ex.Message);
                                    }
                                }
                            }
                        }
                        catch
                        {
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.Instance.AddLog(LogType.Error, "部落战检测出现错误: " + ex.ToString());
                }
            }while (true);
        }
예제 #27
0
        /// <summary>
        ///     戦争参加国リストを更新する
        /// </summary>
        /// <param name="war"></param>
        private void UpdateWarParticipant(War war)
        {
            IEnumerable<Country> countries = Countries.Tags;

            // 攻撃側参加国
            warAttackerListBox.BeginUpdate();
            warAttackerListBox.Items.Clear();
            if (war.Attackers?.Participant != null)
            {
                foreach (Country country in war.Attackers.Participant)
                {
                    warAttackerListBox.Items.Add(Countries.GetTagName(country));
                }
                countries = countries.Where(country => !war.Attackers.Participant.Contains(country));
            }
            warAttackerListBox.EndUpdate();

            // 防御側参加国
            warDefenderListBox.BeginUpdate();
            warDefenderListBox.Items.Clear();
            if (war.Defenders?.Participant != null)
            {
                foreach (Country country in war.Defenders.Participant)
                {
                    warDefenderListBox.Items.Add(Countries.GetTagName(country));
                }
                countries = countries.Where(country => !war.Defenders.Participant.Contains(country));
            }
            warDefenderListBox.EndUpdate();

            // 戦争非参加国
            _warFreeCountries = countries.ToList();
            warFreeCountryListBox.BeginUpdate();
            warFreeCountryListBox.Items.Clear();
            foreach (Country country in _warFreeCountries)
            {
                warFreeCountryListBox.Items.Add(Countries.GetTagName(country));
            }
            warFreeCountryListBox.EndUpdate();
        }
예제 #28
0
 /// <summary>
 ///     編集項目の値変更時のログを出力する
 /// </summary>
 /// <param name="itemId">項目ID</param>
 /// <param name="val">編集項目の値</param>
 /// <param name="war">戦争</param>
 /// <param name="index">戦争リストのインデックス</param>
 public void OutputItemValueChangedLog(ScenarioEditorItemId itemId, object val, War war, int index)
 {
     Log.Info("[Scenario] {0}: {1} -> {2} ({3})", ItemStrings[(int) itemId],
         ObjectHelper.ToString(GetItemValue(itemId, war)), ObjectHelper.ToString(val), index);
 }
예제 #29
0
 public void Watch()
 {
     War.record.SetWatchCount(data.uid_local, data.view_count + 1);
     War.Start(data, -1);
 }
예제 #30
0
 /// <summary>
 ///     項目値変更後の処理
 /// </summary>
 /// <param name="itemId">項目ID</param>
 /// <param name="val">編集項目の値</param>
 /// <param name="war">戦争</param>
 public void PostItemChanged(ScenarioEditorItemId itemId, object val, War war)
 {
     // 何もしない
 }
예제 #31
0
 /// <summary>
 /// Depending on isAttacker it returns either attacker or defender from War. (Not countries in wars!)
 /// </summary>
 public static Country GetMainCountry(this War war, bool isAttacker)
 {
     return(isAttacker ? war.Attacker : war.Defender);
 }
예제 #32
0
        /// <summary>
        ///     項目値変更前の処理
        /// </summary>
        /// <param name="itemId">項目ID</param>
        /// <param name="val">編集項目の値</param>
        /// <param name="war">同盟</param>
        public void PreItemChanged(ScenarioEditorItemId itemId, object val, War war)
        {
            switch (itemId)
            {
                case ScenarioEditorItemId.WarStartYear:
                    PreItemChangedWarStartDate((TextBox) _form.GetItemControl(ScenarioEditorItemId.WarStartMonth),
                        (TextBox) _form.GetItemControl(ScenarioEditorItemId.WarStartDay), war);
                    break;

                case ScenarioEditorItemId.WarStartMonth:
                    PreItemChangedWarStartDate((TextBox) _form.GetItemControl(ScenarioEditorItemId.WarStartYear),
                        (TextBox) _form.GetItemControl(ScenarioEditorItemId.WarStartDay), war);
                    break;

                case ScenarioEditorItemId.WarStartDay:
                    PreItemChangedWarStartDate((TextBox) _form.GetItemControl(ScenarioEditorItemId.WarStartYear),
                        (TextBox) _form.GetItemControl(ScenarioEditorItemId.WarStartMonth), war);
                    break;

                case ScenarioEditorItemId.WarEndYear:
                    PreItemChangedWarEndDate((TextBox) _form.GetItemControl(ScenarioEditorItemId.WarEndMonth),
                        (TextBox) _form.GetItemControl(ScenarioEditorItemId.WarEndDay), war);
                    break;

                case ScenarioEditorItemId.WarEndMonth:
                    PreItemChangedWarEndDate((TextBox) _form.GetItemControl(ScenarioEditorItemId.WarEndYear),
                        (TextBox) _form.GetItemControl(ScenarioEditorItemId.WarEndDay), war);
                    break;

                case ScenarioEditorItemId.WarEndDay:
                    PreItemChangedWarEndDate((TextBox) _form.GetItemControl(ScenarioEditorItemId.WarEndYear),
                        (TextBox) _form.GetItemControl(ScenarioEditorItemId.WarEndMonth), war);
                    break;

                case ScenarioEditorItemId.WarType:
                    if (war.Id == null)
                    {
                        war.Id = new TypeId();
                        PreItemChangedWarType((TextBox) _form.GetItemControl(ScenarioEditorItemId.WarId), val, war);
                    }
                    break;

                case ScenarioEditorItemId.WarId:
                    if (war.Id == null)
                    {
                        war.Id = new TypeId();
                        PreItemChangedWarId((TextBox) _form.GetItemControl(ScenarioEditorItemId.WarType), val, war);
                    }
                    break;

                case ScenarioEditorItemId.WarAttackerType:
                    if (war.Attackers.Id == null)
                    {
                        war.Attackers.Id = new TypeId();
                        PreItemChangedWarAttackerType(
                            (TextBox) _form.GetItemControl(ScenarioEditorItemId.WarAttackerId), val, war);
                    }
                    break;

                case ScenarioEditorItemId.WarAttackerId:
                    if (war.Attackers.Id == null)
                    {
                        war.Attackers.Id = new TypeId();
                        PreItemChangedWarAttackerId(
                            (TextBox) _form.GetItemControl(ScenarioEditorItemId.WarAttackerType), val, war);
                    }
                    break;

                case ScenarioEditorItemId.WarDefenderType:
                    if (war.Defenders.Id == null)
                    {
                        war.Defenders.Id = new TypeId();
                        PreItemChangedWarDefenderType(
                            (TextBox) _form.GetItemControl(ScenarioEditorItemId.WarDefenderId), val, war);
                    }
                    break;

                case ScenarioEditorItemId.WarDefenderId:
                    if (war.Defenders.Id == null)
                    {
                        war.Defenders.Id = new TypeId();
                        PreItemChangedWarDefenderId(
                            (TextBox) _form.GetItemControl(ScenarioEditorItemId.WarDefenderType), val, war);
                    }
                    break;
            }
        }
예제 #33
0
    public static void Main()
    {
        Console.WriteLine("A Game of War");

        War.Start();
    }
예제 #34
0
 /// <summary>
 ///     編集項目の編集済みフラグを設定する
 /// </summary>
 /// <param name="itemId">項目ID</param>
 /// <param name="war">戦争</param>
 public void SetItemDirty(ScenarioEditorItemId itemId, War war)
 {
     war.SetDirty((War.ItemId) ItemDirtyFlags[(int) itemId]);
     Scenarios.Data.SetDirty();
     Scenarios.SetDirty();
 }
예제 #35
0
 public async Task GetWar_InvalidId_EveCrestException()
 {
     War data = await crest.GetWarAsync(999999999);
 }
예제 #36
0
        /// <summary>
        ///     編集項目の値を設定する
        /// </summary>
        /// <param name="itemId">項目ID</param>
        /// <param name="val">編集項目の値</param>
        /// <param name="war">戦争</param>
        public void SetItemValue(ScenarioEditorItemId itemId, object val, War war)
        {
            switch (itemId)
            {
                case ScenarioEditorItemId.WarStartYear:
                    war.StartDate.Year = (int) val;
                    break;

                case ScenarioEditorItemId.WarStartMonth:
                    war.StartDate.Month = (int) val;
                    break;

                case ScenarioEditorItemId.WarStartDay:
                    war.StartDate.Day = (int) val;
                    break;

                case ScenarioEditorItemId.WarEndYear:
                    war.EndDate.Year = (int) val;
                    break;

                case ScenarioEditorItemId.WarEndMonth:
                    war.EndDate.Month = (int) val;
                    break;

                case ScenarioEditorItemId.WarEndDay:
                    war.EndDate.Day = (int) val;
                    break;

                case ScenarioEditorItemId.WarType:
                    war.Id.Type = (int) val;
                    break;

                case ScenarioEditorItemId.WarId:
                    war.Id.Id = (int) val;
                    break;

                case ScenarioEditorItemId.WarAttackerType:
                    war.Attackers.Id.Type = (int) val;
                    break;

                case ScenarioEditorItemId.WarAttackerId:
                    war.Attackers.Id.Id = (int) val;
                    break;

                case ScenarioEditorItemId.WarDefenderType:
                    war.Defenders.Id.Type = (int) val;
                    break;

                case ScenarioEditorItemId.WarDefenderId:
                    war.Defenders.Id.Id = (int) val;
                    break;
            }
        }
예제 #37
0
        public Battle(string name, Deity creator, Army attacker, Army defender, Province province, War war) : base(name, creator)
        {
            War            = war;
            Province       = province;
            InvolvedArmies = new Army[2] {
                attacker, defender
            };
            Modifiers = new int[2] {
                0, 0
            };
            Score = new int[2] {
                0, 0
            };

            chooseBattleLocation();
        }
예제 #38
0
 /// <summary>
 ///     編集項目の色を更新する
 /// </summary>
 /// <param name="control">コントロール</param>
 /// <param name="war">戦争</param>
 public void UpdateItemColor(Control control, War war)
 {
     ScenarioEditorItemId itemId = (ScenarioEditorItemId) control.Tag;
     control.ForeColor = IsItemDirty(itemId, war) ? Color.Red : SystemColors.WindowText;
 }
예제 #39
0
    public void processOptionA()
    {
        Debug.Log("Option A");
        Debug.Log(currentEvent.EventType);
        eventDecisionTwoPanel.SetActive(false);
        closeToolTips();
        App                   app            = UnityEngine.Object.FindObjectOfType <App>();
        int                   playerIndex    = app.GetHumanIndex();
        Nation                player         = State.getNations()[playerIndex];
        Nation                otherMajor     = State.getNation(currentEvent.OtherMajor);
        EventRegister         eventLogic     = State.eventRegister;
        Queue <DecisionEvent> decisionevents = eventLogic.DecisionEvents;

        MyEnum.eventType eventType        = currentEvent.EventType;
        Province         disputedProvince = State.getProvince(currentEvent.Province);
        int            minorNationIndex   = currentEvent.OtherMinor;
        EventResponder responder          = otherMajor.getAI().getEventResponder();

        if (eventType == MyEnum.eventType.riotResponce)
        {
            // Crackdown on riots to restore order
            crackdown();
        }
        else if (eventType == MyEnum.eventType.referendumDemanded)
        {
            // Refuse to hold a referendum
            refuseReferendum(player, otherMajor, disputedProvince);
        }



        else if (eventType == MyEnum.eventType.AI_RejectsReferendum)
        {
            Debug.Log("Player Decides to Declare War");
            war = new War(player, otherMajor, disputedProvince.getIndex(), minorNationIndex);
            prepareWarPanel(player, otherMajor, war);
            return;
        }

        else if (currentEvent.EventType == MyEnum.eventType.notificationOfCrackdown)
        {
            DecisionEvent newEvent = new DecisionEvent();
            Debug.Log("We demand Referendum");
            Debug.Log("Player Name: " + player.getNationName());
            Debug.Log("Other Nation: " + otherMajor.getNationName());
            if (responder.acceptRefDemand(otherMajor, player, disputedProvince))
            {
                Debug.Log("Accepts");
                eventLogic.initalizeAI_AcceptsReferendumEvent(newEvent, currentEvent);
            }
            else
            {
                Debug.Log("Rejects");
                eventLogic.initalizeAI_RejectsReferendumEvent(newEvent, currentEvent);
            }
            currentEvent = newEvent;
            showDecisionPanel(player);
        }



        else if (currentEvent.EventType == MyEnum.eventType.AI_RejectsReferendum)
        {
            // Declare war
            DecisionEvent newEvent = new DecisionEvent();
            war = new War(player, otherMajor, disputedProvince.getIndex(), minorNationIndex);
            prepareWarPanel(player, otherMajor, war);
        }

        else if (currentEvent.EventType == MyEnum.eventType.askIfBoycott)
        {
            player.addBoycott(otherMajor.getIndex());
        }

        else if (currentEvent.EventType == MyEnum.eventType.spreadDissentOppertunity)
        {
            Province prov = State.getProvince(currentEvent.Province);
            prov.adjustDiscontentment(1);
            player.InfulencePoints--;
            DecisionEvent newEvent = new DecisionEvent();

            if (eventLogic.spreadDiscontentDetected(player, otherMajor))
            {
                player.Relations[otherMajor.getIndex()] = -10;
                eventLogic.initializeReportDissentCaughtEvent(newEvent, currentEvent);
            }
            else
            {
                eventLogic.initializeReportDissentInfluenceEvent(newEvent, currentEvent);
            }
            currentEvent = newEvent;
        }

        else if (currentEvent.EventType == MyEnum.eventType.navyIntercept)
        {
            // Player decides to intercept enemy navy
        }



        nextEventTurn(player);
    }
예제 #40
0
 /// <summary>
 ///     編集項目の値を更新する
 /// </summary>
 /// <param name="control">コントロール</param>
 /// <param name="war">戦争</param>
 public void UpdateItemValue(TextBox control, War war)
 {
     ScenarioEditorItemId itemId = (ScenarioEditorItemId) control.Tag;
     control.Text = ObjectHelper.ToString(GetItemValue(itemId, war));
 }
예제 #41
0
    public void endWar(War war, Nation attacker, Nation defender)
    {
        Debug.Log("End war");
        warPanel.SetActive(false);
        App           app         = UnityEngine.Object.FindObjectOfType <App>();
        int           playerIndex = app.GetHumanIndex();
        Nation        human       = State.getNations()[playerIndex];
        Province      prov        = State.getProvince(0);
        EventRegister eventLogic  = State.eventRegister;
        DecisionEvent newEvent    = new DecisionEvent();

        if (war.ProvIndex != -1)
        {
            prov = State.getProvince(war.ProvIndex);
        }

        if (war.AttackerForces == 0 || war.AttackerMorale == 0)
        {
            Debug.Log("Attack fails");
            // Attack fails and defender wins
            attacker.decreasePrestige(2);
            defender.increasePrestige(2);
            attacker.landForces.Morale -= 10;
            defender.landForces.Morale += 10;
            int payment = (int)(attacker.getGold() / 3);
            PlayerPayer.payAnotherPlayer(attacker, defender, payment);

            if (war.AttackerIndex == human.getIndex())
            {
                eventLogic.initializeFailedInvasionEvent(newEvent, currentEvent, war);
            }
            else
            {
                eventLogic.initializeSucessfulDefenseEvent(newEvent, currentEvent, war);
            }
            currentEvent = newEvent;
            showDecisionPanel(human);
        }

        else if (war.DefenderMorale == 0 || war.DefenderForces == 0)
        {
            // Attack succeeds
            Debug.Log("Attack succeeds");
            attacker.increasePrestige(2);
            defender.decreasePrestige(2);
            attacker.landForces.Morale += 10;
            defender.landForces.Morale -= 10;
            if (war.ProvIndex > -1)
            {
                prov.changeProvinceControl(defender, attacker);
                MapChange        newMapChange = new MapChange(defender.getIndex(), attacker.getIndex(), prov.getIndex());
                List <MapChange> mapChanges   = State.MapChanges;
                mapChanges.Add(newMapChange);
            }
            else
            {
                int payment = (int)(defender.getGold() / 3);
                PlayerPayer.payAnotherPlayer(defender, attacker, payment);
            }

            if (war.AttackerIndex == human.getIndex())
            {
                eventLogic.initializeSucessfulInvasionEvent(newEvent, currentEvent, war);
                currentEvent = newEvent;
                showDecisionPanel(human);
            }
            else
            {
                eventLogic.initializeFailedDefenseEvent(newEvent, currentEvent, war);
                currentEvent = newEvent;
                showDecisionPanel(human);
            }
        }
    }
예제 #42
0
        /// <summary>
        ///     項目変更前の処理 - 戦争id
        /// </summary>
        /// <param name="control">typeのコントロール</param>
        /// <param name="val">編集項目の値</param>
        /// <param name="war">戦争</param>
        private void PreItemChangedWarId(TextBox control, object val, War war)
        {
            war.Id.Type = Scenarios.GetNewType(Scenarios.DefaultWarType, (int) val);

            // 編集済みフラグを設定する
            ScenarioEditorItemId itemId = (ScenarioEditorItemId) control.Tag;
            SetItemDirty(itemId, war);

            // 編集項目の値を更新する
            UpdateItemValue(control, war);

            // 編集項目の色を更新する
            UpdateItemColor(control, war);
        }
예제 #43
0
    public void DecideOnAction()
    {
        float number = Random.value * 100f;

        if (currentState.GetType() == typeof(Peace))
        {
            //Debug.Log("Army chance " + (1 - ((float)ArmyPopulation / (float)Population) / ArmyPopPercentage) * 100f);
            //Debug.Log("Pop chance " + (1 - ((float)Population / (float)TotalPossiblePopulation)) * 100f);

            if (number < (1 - ((float)ArmyPopulation / (float)Population) / ArmyPopPercentage) * 100f)
            {
                DoAction(AllActions["RecruitSoldiers"]);
            }
            else if (number < (1 - ((float)Population / (float)TotalPossiblePopulation)) * 100f)
            {
                DoAction(AllActions["GrowPopulation"]);
            }
            else
            {
                DoAction(AllActions["DoNothing"]);
            }
        }
        if (number < pacifistAggressive && currentState.GetType() != typeof(War) && AllActions.ContainsKey("DeclareWar"))
        {
            DoAction(AllActions["DeclareWar"], countries[0]);
        }
        else if (currentState.GetType() == typeof(War))
        {
            War     tempState = (War)currentState;
            Country enemy     = null;
            foreach (Country c in tempState.participants)
            {
                if (!c.Equals(this))
                {
                    enemy = c;
                    break;
                }
            }
            if (ArmyStrength * 3 < enemy.ArmyStrength)
            {
                DoAction(AllActions["Surrender"], countries[0]);
            }
            else if (number > pacifistAggressive)
            {
                DoAction(AllActions["ResolveWar"], countries[0]);
            }
            else if (number < pacifistAggressive && AllActions.ContainsKey("Battle"))
            {
                DoAction(AllActions["Battle"], countries[0]);
            }
            else
            {
                DoAction(AllActions["DoNothing"]);
            }
        }
        else
        {
            DoAction(AllActions["DoNothing"]);
        }
        if (currentAction.GetType() != typeof(DoNothing))
        {
            currentState.statePeriodLength++;
        }
    }
예제 #44
0
        /// <summary>
        ///     項目変更前の処理 - 戦争開始日時
        /// </summary>
        /// <param name="control1">連動するコントロール1</param>
        /// <param name="control2">連動するコントロール2</param>
        /// <param name="war">戦争</param>
        private void PreItemChangedWarStartDate(TextBox control1, TextBox control2, War war)
        {
            if (war.StartDate == null)
            {
                war.StartDate = new GameDate();

                // 編集済みフラグを設定する
                ScenarioEditorItemId itemId1 = (ScenarioEditorItemId) control1.Tag;
                SetItemDirty(itemId1, war);
                ScenarioEditorItemId itemId2 = (ScenarioEditorItemId) control2.Tag;
                SetItemDirty(itemId2, war);

                // 編集項目の値を更新する
                UpdateItemValue(control1, war);
                UpdateItemValue(control2, war);

                // 編集項目の色を更新する
                UpdateItemColor(control1, war);
                UpdateItemColor(control2, war);
            }
        }
예제 #45
0
        static long?PingWar(long warId, string type)
        {
            try
            {
                var warDeets = new War(warId);
                if (
                    (warDeets.Aggressor.Alliance_Id == allId)
                    ||
                    (warDeets.Aggressor.Corporation_Id == corpId)
                    ||
                    (warDeets.Defender.Alliance_Id == allId)
                    ||
                    (warDeets.Defender.Corporation_Id == corpId)
                    )
                {
                    var name = string.Empty;

                    if (warDeets.Aggressor.Alliance_Id.HasValue)
                    {
                        name = GetAlliance(warDeets.Aggressor.Alliance_Id.Value).Name;
                    }
                    else
                    {
                        name = GetCorporation(warDeets.Aggressor.Corporation_Id.Value).Corporation_Name;
                    }
                    if (warDeets.Defender.Alliance_Id.HasValue)
                    {
                        name = string.Concat(name, " vs ", GetAlliance(warDeets.Defender.Alliance_Id.Value).Name);
                    }
                    else
                    {
                        name = string.Concat(name, " vs ", GetCorporation(warDeets.Defender.Corporation_Id.Value).Corporation_Name);
                    }

                    var dt     = new DateTime();
                    var colour = string.Empty;
                    if (type == "Started")
                    {
                        dt     = warDeets.StartTime != null ? warDeets.StartTime : warDeets.Declared;
                        colour = "#ff80bf";
                        AddPost(string.Format("War {0} {1}", type, dt.ToString("yyyy-MM-dd HHmm")), name);
                    }
                    else
                    {
                        dt     = warDeets.EndTime.Value;
                        colour = "#ffe6f2";
                        ScrapPost(name);
                    }

                    SendMessage(name, string.Format("War {0}: {1}", type, dt.ToString()), colour);

                    return(warId);
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
                Console.WriteLine(string.Format("{0}: {1}", type, warId.ToString()));
                return(null);
            }
        }
예제 #46
0
        /// <summary>
        ///     項目変更前の処理 - 戦争type
        /// </summary>
        /// <param name="control">idのコントロール</param>
        /// <param name="val">編集項目の値</param>
        /// <param name="war">戦争</param>
        private void PreItemChangedWarType(TextBox control, object val, War war)
        {
            // 新規idを設定する
            war.Id.Id = Scenarios.GetNewId((int) val, 1);

            // 編集済みフラグを設定する
            ScenarioEditorItemId itemId = (ScenarioEditorItemId) control.Tag;
            SetItemDirty(itemId, war);

            // 編集項目の値を更新する
            UpdateItemValue(control, war);

            // 編集項目の色を更新する
            UpdateItemColor(control, war);
        }
예제 #47
0
 public override void Initialize(War war)
 {
     base.Initialize(war);
 }
예제 #48
0
        /// <summary>
        ///     戦争設定を構文解析する
        /// </summary>
        /// <param name="lexer">字句解析器</param>
        /// <returns>戦争設定</returns>
        private static War ParseWar(TextLexer lexer)
        {
            // =
            Token token = lexer.GetToken();
            if (token.Type != TokenType.Equal)
            {
                Log.InvalidToken(LogCategory, token, lexer);
                return null;
            }

            // {
            token = lexer.GetToken();
            if (token.Type != TokenType.OpenBrace)
            {
                Log.InvalidToken(LogCategory, token, lexer);
                return null;
            }

            War war = new War();
            while (true)
            {
                token = lexer.GetToken();

                // ファイルの終端
                if (token == null)
                {
                    break;
                }

                // } (セクション終端)
                if (token.Type == TokenType.CloseBrace)
                {
                    break;
                }

                // 無効なトークン
                if (token.Type != TokenType.Identifier)
                {
                    Log.InvalidToken(LogCategory, token, lexer);
                    lexer.SkipLine();
                    continue;
                }

                string keyword = token.Value as string;
                if (string.IsNullOrEmpty(keyword))
                {
                    continue;
                }
                keyword = keyword.ToLower();

                // id
                if (keyword.Equals("id"))
                {
                    TypeId id = ParseTypeId(lexer);
                    if (id == null)
                    {
                        Log.InvalidSection(LogCategory, "id", lexer);
                        continue;
                    }

                    // typeとidの組
                    war.Id = id;
                    continue;
                }

                // date
                if (keyword.Equals("date"))
                {
                    GameDate date = ParseDate(lexer);
                    if (date == null)
                    {
                        Log.InvalidSection(LogCategory, "date", lexer);
                        continue;
                    }

                    // 開始日時
                    war.StartDate = date;
                    continue;
                }

                // enddate
                if (keyword.Equals("enddate"))
                {
                    GameDate date = ParseDate(lexer);
                    if (date == null)
                    {
                        Log.InvalidSection(LogCategory, "enddate", lexer);
                        continue;
                    }

                    // 終了日時
                    war.EndDate = date;
                    continue;
                }

                // attackers
                if (keyword.Equals("attackers"))
                {
                    Alliance alliance = ParseAlliance(lexer);
                    if (alliance == null)
                    {
                        Log.InvalidSection(LogCategory, "attackers", lexer);
                        continue;
                    }

                    // 攻撃側参加国
                    war.Attackers = alliance;
                    continue;
                }

                // defenders
                if (keyword.Equals("defenders"))
                {
                    Alliance alliance = ParseAlliance(lexer);
                    if (alliance == null)
                    {
                        Log.InvalidSection(LogCategory, "defenders", lexer);
                        continue;
                    }

                    // 防御側参加国
                    war.Defenders = alliance;
                    continue;
                }

                // 無効なトークン
                Log.InvalidToken(LogCategory, token, lexer);
                lexer.SkipLine();
            }

            return war;
        }
예제 #49
0
파일: Player.cs 프로젝트: dwaby/Log
 public void AddWar(War war)
 {
     m_Wars.Add(war);
 }
예제 #50
0
        public string GetNewGameListstr(string mWhereStr)
        {
            string mSql = "";
            //string mCSql = "";
            string mWhere = "";

            mSql = string.Format("SELECT * FROM tb_game ");
            //mCSql = string.Format("SELECT count(0) FROM tb_game where 1=1");
            if (mWhereStr != "")
            {
                mWhereStr = mWhereStr.Replace("year", "Year([buydate])");
                string[] mWhereArr = mWhereStr.Split(';');
                foreach (string War in mWhereArr)
                {
                    if (War.Split(':')[0] == "name")
                    {
                        mWhere += " and " + War.Split(':')[0] + " like '%" + War.Split(':')[1] + "%'";
                    }
                    else
                    {
                        mWhere += " and " + War.Split(':')[0] + " = '" + War.Split(':')[1] + "'";
                    }
                }
            }
            //mWhere = string.Format(" and console = '{0}'", console);
            mSql += mWhere + " order by tb_game.buydate desc";
            //mCSql += mWhere;
            //cmd.CommandText = mSql;
            //conn.Open();
            //connCount.Open();
            DataTable dt = new DataTable();

            dt = sh.getDT(mSql);
            string        result = "";
            StringBuilder sb     = new StringBuilder();

            result = sb.ToString();

            if (dt.Rows.Count > 0)
            {
                sb.Append("[");
                foreach (DataRow dr in dt.Rows)
                {
                    sb.Append("{");
                    sb.Append("\"id\": \"" + dr["id"].ToString() + "\",");
                    sb.Append("\"console\": \"" + dr["console"].ToString() + "\",");
                    sb.Append("\"name\": \"" + dr["name"].ToString() + "\",");
                    sb.Append("\"price\": \"" + dr["price"].ToString() + "\",");
                    sb.Append("\"buydate\": \"" + Convert.ToDateTime(dr["buydate"]).ToString("yyyy-MM-dd") + "\"");
                    sb.Append("},");
                }
                sb.Remove(sb.Length - 1, 1);
                sb.Append("]");
            }
            //cmdCount.CommandText = mCSql;
            //string DCounts = sh.GetString(mCSql); // cmdCount.ExecuteScalar().ToString();


            result = sb.ToString();// + "&" + DCounts;

            return(result);
        }
예제 #51
0
        /** 生成关卡引导数据--6攻打主城,使用范围技能 */
        public GuideModuleData GenerateStage_6()
        {
            GuideModuleData moduleData = new GuideModuleData(6, "攻打主城,使用范围技能");

            moduleData.Add(new GuideStepData(GuideStepType.Begin_Guide, GuideStepCompleteType.NextFrame, "开始引导"));
//			moduleData.Add(new GuideStepData_Panel(GuidePanelID.War_TopBar, GuideStepType.War_ClosePanel, "关闭势力等级UI"));
            moduleData.Add(new GuideStepData_Panel(GuidePanelID.War_SendArmSettingPanel, GuideStepType.War_ClosePanel, "关闭 发兵百分比设置UI"));
            moduleData.Add(new GuideStepData(GuideStepType.War_Pause, GuideStepCompleteType.NextFrame, "暂停战斗"));
            moduleData.Add(new GuideStepData_Panel(GuidePanelID.Guide_Mask, GuideStepType.War_OpenPanel, "打开引导遮罩"));
            moduleData.Add(new GuideStepData_Panel(GuidePanelID.Guide_ClickScreenNext, GuideStepType.War_OpenPanel, "打开点击屏幕下一步"));



            moduleData.Add(new GuideStepData(GuideStepType.War_Card_Fly_Screen, GuideStepCompleteType.WaitSecond, openCardFlyTime, "卡牌飞入屏幕"));
            moduleData.Add(new GuideStepData(GuideStepType.War_OpenTeacherPanel, GuideStepCompleteType.WaitSecond, openTeacherTime, "打开美女对话面板"));

            int skillCount = War.ownLegionData == null ? 0 : War.ownLegionData.skillDatas.Count - 1;

            moduleData.Add(new GuideStepData_TeacherSay("本局可使用" + skillCount + "张<color=#FF9D0BFF>武将卡</color>", GuideStepCompleteType.ClickScreenCall));

            moduleData.Add(new GuideStepData(GuideStepType.War_Card_Fly_SkillBox, GuideStepCompleteType.WaitSecond, 1f, "卡牌飞入技能盒"));
            moduleData.Add(new GuideStepData(GuideStepType.War_CloseTeacherPanel, GuideStepCompleteType.NextFrame, "关闭美女对话面板"));



            moduleData.Add(new GuideStepData_Panel(GuidePanelID.GuideIntroducePanel_LegionLevel, GuideStepType.War_OpenPanel, "打开 引导介绍面板--士气"));
            moduleData.Add(new GuideStepData(GuideStepType.Empty, GuideStepCompleteType.ClickScreenCall, "空"));
            moduleData.Add(new GuideStepData(GuideStepType.War_LegionLevel_Fly, GuideStepCompleteType.Call, "士气等级飞到目标位置"));
            moduleData.Add(new GuideStepData_Panel(GuidePanelID.War_TopBar, GuideStepType.War_OpenPanel, "打开势力等级UI"));
            moduleData.Add(new GuideStepData_Panel(GuidePanelID.GuideIntroducePanel_LegionLevel, GuideStepType.War_ClosePanel, GuideStepCompleteType.NextFrame, "关闭 引导介绍面板--士气"));


            moduleData.Add(new GuideStepData_Panel(GuidePanelID.Guide_ClickScreenNext, GuideStepType.War_ClosePanel, "关闭点击屏幕下一步"));
            moduleData.Add(new GuideStepData_Panel(GuidePanelID.Guide_Mask, GuideStepType.War_ClosePanel, "关闭引导遮罩"));
            moduleData.Add(new GuideStepData(GuideStepType.War_Play, GuideStepCompleteType.NextFrame, "播放游戏"));


            moduleData.Add(new GuideStepData(GuideStepType.War_OpenTeacherPanel, GuideStepCompleteType.WaitSecond, openTeacherTime, "打开美女对话面板"));
            moduleData.Add(new GuideStepData_TeacherSay("出兵!攻占敌军<color=#FF9D0BFF>主基地</color>!", GuideStepCompleteType.NextFrame));

            int to = Application.isPlaying ? War.GetLegionData(2).initUseSkillBuildId : -1;

            if (to == -1)
            {
                to = 6;
            }

            moduleData.Add(new GuideStepData_SendArm(6, to, "发兵6->" + to));
            moduleData.Add(new GuideStepData(GuideStepType.War_CloseTeacherPanel, GuideStepCompleteType.NextFrame, "关闭美女对话面板"));
            moduleData.Add(new GuideStepData_LoackGuide(0.GLLProduce(true).GLLTime(true), GuideStepType.Unloack_Guide, GuideStepCompleteType.NextFrame, "解锁强制--引导"));


            moduleData.Add(new GuideStepListenerData("监听 箭塔被攻占").SetListener_BuildOccupied(to));

            moduleData.Add(new GuideStepData(GuideStepType.War_OpenTeacherPanel, GuideStepCompleteType.WaitSecond, openTeacherTime, "打开美女对话面板"));
            moduleData.Add(new GuideStepData_TeacherSay("斩杀了敌方主公,我军<color=#FF9D0BFF>士气</color>大大提升!", GuideStepCompleteType.NextFrame));
            moduleData.Add(new GuideStepData(GuideStepType.Empty, GuideStepCompleteType.WaitSecond, 2f, "空--等待时间"));


            int skillId = 19;

            moduleData.Add(new GuideStepData_LoackGuide(0.GLLProduceSkill(true), GuideStepType.Unloack_Guide, GuideStepCompleteType.NextFrame, "解锁强制--引导"));

            moduleData.Add(new GuideStepData_ProduceSkill(skillId, "快速生产一个技能"));
            moduleData.Add(new GuideStepData_LoackGuide(0.GLLHanld(true).GLLProduce(true).GLLTime(true), GuideStepType.Loack_Guide, GuideStepCompleteType.NextFrame, "解锁强制--引导"));
//			moduleData.Add(new GuideStepData(GuideStepType.War_OpenTeacherPanel, GuideStepCompleteType.WaitSecond, openTeacherTime, "打开美女对话面板"));
            moduleData.Add(new GuideStepData_TeacherSay("派<color=#FF9D0BFF>诸葛亮</color>入驻,兵营等级上限+1", GuideStepCompleteType.NextFrame));

            moduleData.Add(new GuideStepData_UseSkill(skillId, 5, "拖动技能A到建筑B"));
            moduleData.Add(new GuideStepData(GuideStepType.War_CloseTeacherPanel, GuideStepCompleteType.NextFrame, "关闭美女对话面板"));
            moduleData.Add(new GuideStepData_LoackGuide(0.GLLHanld(true).GLLProduce(true).GLLTime(true), GuideStepType.Unloack_Guide, GuideStepCompleteType.NextFrame, "解锁强制--引导"));


//
//			moduleData.Add(new GuideStepData_ExeSendArm(5, 6, -1, "执行发兵5->6"));
            moduleData.Add(new GuideStepData(GuideStepType.Empty, GuideStepCompleteType.WaitSecond, 3f, "空--等待时间"));

            moduleData.Add(new GuideStepData(GuideStepType.End_Guide, GuideStepCompleteType.NextFrame, "结束引导"));


            moduleData.Init();
            return(moduleData);
        }
예제 #52
0
        /// <summary>
        ///     戦争の編集項目を更新する
        /// </summary>
        /// <param name="war">戦争</param>
        private void UpdateWarItems(War war)
        {
            // 編集項目の値を更新する
            _controller.UpdateItemValue(warStartYearTextBox, war);
            _controller.UpdateItemValue(warStartMonthTextBox, war);
            _controller.UpdateItemValue(warStartDayTextBox, war);
            _controller.UpdateItemValue(warEndYearTextBox, war);
            _controller.UpdateItemValue(warEndMonthTextBox, war);
            _controller.UpdateItemValue(warEndDayTextBox, war);
            _controller.UpdateItemValue(warTypeTextBox, war);
            _controller.UpdateItemValue(warIdTextBox, war);
            _controller.UpdateItemValue(warAttackerTypeTextBox, war);
            _controller.UpdateItemValue(warAttackerIdTextBox, war);
            _controller.UpdateItemValue(warDefenderTypeTextBox, war);
            _controller.UpdateItemValue(warDefenderIdTextBox, war);

            // 編集項目の色を更新する
            _controller.UpdateItemColor(warStartYearTextBox, war);
            _controller.UpdateItemColor(warStartMonthTextBox, war);
            _controller.UpdateItemColor(warStartDayTextBox, war);
            _controller.UpdateItemColor(warEndYearTextBox, war);
            _controller.UpdateItemColor(warEndMonthTextBox, war);
            _controller.UpdateItemColor(warEndDayTextBox, war);
            _controller.UpdateItemColor(warTypeTextBox, war);
            _controller.UpdateItemColor(warIdTextBox, war);
            _controller.UpdateItemColor(warAttackerTypeTextBox, war);
            _controller.UpdateItemColor(warAttackerIdTextBox, war);
            _controller.UpdateItemColor(warDefenderTypeTextBox, war);
            _controller.UpdateItemColor(warDefenderIdTextBox, war);

            // 戦争参加国リストを更新する
            UpdateWarParticipant(war);
        }