示例#1
0
            public static void Perform()
            {
                Common.StringBuilder msg = new Common.StringBuilder("ServicePoolCleanup");

                try
                {
                    GrimReaper grim = null;

                    for (int i = Services.AllServices.Count - 1; i >= 0; i--)
                    {
                        Service service = Services.AllServices[i];

                        if (service == null)
                        {
                            Services.AllServices.RemoveAt(i);

                            msg += Common.NewLine + "Empty Service Removed";
                            continue;
                        }

                        msg += Common.NewLine + "Service: " + service.ServiceType;

                        if (service is GrimReaper)
                        {
                            grim = service as GrimReaper;
                        }

                        List <SimDescription> pool = new List <SimDescription>();

                        for (int j = service.mPool.Count - 1; j >= 0; j--)
                        {
                            SimDescription sim = service.mPool[j];
                            if ((sim == null) || (!sim.IsValidDescription) || (sim.Household == null))
                            {
                                service.mPool.RemoveAt(j);

                                msg += Common.NewLine + "Bogus Service Removed " + service.GetType();
                            }
                            else
                            {
                                pool.Add(sim);
                            }
                        }

                        if (pool.Count == 0)
                        {
                            continue;
                        }

                        int maxSims = 2;

                        if (service.Tuning != null)
                        {
                            maxSims = service.Tuning.kMaxNumNPCsInPool;
                            if (maxSims < 0)
                            {
                                maxSims = 0;
                            }
                        }

                        Dictionary <ulong, bool> assigned = new Dictionary <ulong, bool>();

                        msg += Common.NewLine + "Tuning: " + maxSims;
                        msg += Common.NewLine + "Count: " + pool.Count;

                        ResortWorker      workerService = service as ResortWorker;
                        List <ObjectGuid> objsToUnReg   = new List <ObjectGuid>();
                        if (workerService != null)
                        {
                            if (workerService.mWorkerInfo != null)
                            {
                                foreach (KeyValuePair <ObjectGuid, ResortWorker.WorkerInfo> info in workerService.mWorkerInfo)
                                {
                                    bool       objValid = false;
                                    GameObject obj      = GameObject.GetObject(info.Key);
                                    if (obj != null && obj.InWorld)
                                    {
                                        Lot lotCurrent = obj.LotCurrent;
                                        if (lotCurrent != null && lotCurrent.IsCommunityLotOfType(CommercialLotSubType.kEP10_Resort))
                                        {
                                            objValid = true;
                                            assigned[info.Value.CurrentSimDescriptionID] = true;
                                            assigned[info.Value.DesiredSimDescriptionID] = true;
                                        }
                                    }

                                    if (!objValid)
                                    {
                                        objsToUnReg.Add(info.Key);
                                    }
                                }

                                foreach (ObjectGuid guid in objsToUnReg)
                                {
                                    workerService.UnregisterObject(guid);
                                }
                                objsToUnReg.Clear();
                            }
                        }

                        RandomUtil.RandomizeListOfObjects(pool);

                        for (int j = pool.Count - 1; j >= 0; j--)
                        {
                            if (workerService == null)
                            {
                                if (pool.Count <= maxSims)
                                {
                                    break;
                                }
                            }

                            SimDescription choice = pool[j];

                            if (service.IsSimAssignedTask(choice))
                            {
                                continue;
                            }

                            if (assigned.ContainsKey(choice.SimDescriptionId))
                            {
                                continue;
                            }

                            ServiceCleanup.AttemptServiceDisposal(choice, false, "Too Many " + service.ServiceType);

                            pool.RemoveAt(j);
                        }

                        List <SimDescription> serviceSims = new List <SimDescription>(service.Pool);
                        foreach (SimDescription serviceSim in serviceSims)
                        {
                            if (serviceSim == null)
                            {
                                continue;
                            }

                            if (!serviceSim.IsValidDescription)
                            {
                                service.EndService(serviceSim);
                            }
                            else if (SimTypes.IsDead(serviceSim))
                            {
                                service.EndService(serviceSim);
                            }
                        }
                    }

                    if (grim != null)
                    {
                        if (grim.mPool.Count == 0)
                        {
                            SimDescription sim = grim.CreateNewNPCForPool(null);
                            if (sim != null)
                            {
                                grim.AddSimToPool(sim);
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    Common.Exception(msg, e);
                }
                finally
                {
                    Common.DebugNotify(msg);
                }
            }
示例#2
0
        private async Task FinishSession()
        {
            try
            {
                if (Result > 0)
                {
                    return;
                }
                Result = RandomUtil.NextInt(2) + RandomUtil.NextInt(2) + RandomUtil.NextInt(2) + RandomUtil.NextInt(2);
                _logic.CalculateResult(Result, SessionId);
                string data = _logic.GetQuery();
                if (string.IsNullOrEmpty(data))
                {
                    return;
                }
                History.Enqueue(Result);
                if (History.Count > 50)
                {
                    History.TryDequeue(out var r);
                }
                await GameDAO.ExecuteAsync(data);

                NLogManager.LogMessage("FINISH SESION: => " + data);
                var           rewards  = _logic.GetReward();
                var           listSit  = Sitting.Values.ToList();
                List <object> sittings = new List <object>();
                foreach (var re in rewards)
                {
                    Player p = GetPlayer(re.Key);

                    if (p != null)
                    {
                        long totalLose   = re.Value.Sum(x => x.Lose);
                        long totalwin    = re.Value.Sum(x => x.Prize);
                        long totalrefund = re.Value.Sum(x => x.Refund);
                        if (re.Key == Banker)
                        {
                            p.IncreaseBalance(totalwin - totalLose, MoneyType);
                        }
                        else
                        {
                            p.IncreaseBalance(totalwin + totalrefund, MoneyType);
                        }
                        if (listSit.Exists(x => x?.AccountId == re.Key))
                        {
                            sittings.Add(new
                            {
                                AccountId   = p.AccountId,
                                Balance     = MoneyType == MoneyType.GOLD ? p.Gold : p.Coin,
                                TotalLose   = totalLose,
                                TotalWin    = totalwin,
                                TotalRefund = re.Key == Banker ? 0 : totalrefund,
                                TotalPrize  = totalwin
                            });
                        }
                    }
                }

                foreach (var re in rewards)
                {
                    Player p = GetPlayer(re.Key);

                    if (p != null)
                    {
                        long balance       = MoneyType == MoneyType.GOLD ? p.Gold : p.Coin;
                        var  lstConnection = _connectionHandler.GetConnections(p.AccountId);
                        _hubContext.Clients.Clients(lstConnection.ToList()).showResult(Result, new
                        {
                            winLose = re.Value,
                            balance = balance
                        }, sittings);
                    }
                }

                var player = _players.Where(x => !rewards.ContainsKey(x.Key));

                foreach (var re in player)
                {
                    long balance       = MoneyType == MoneyType.GOLD ? re.Value.Gold : re.Value.Coin;
                    var  lstConnection = _connectionHandler.GetConnections(re.Value.AccountId);
                    _hubContext.Clients.Clients(lstConnection.ToList()).showResult(Result, new
                    {
                        winLose = new List <Reward>(),
                        balance = balance
                    }, sittings);
                }
            }
            catch (Exception ex)
            {
                NLogManager.PublishException(ex);
            }
        }
示例#3
0
        private new void LoopDel(StateMachineClient smc, InteractionInstance.LoopData loopData)
        {
            try
            {
                bool flag = false;
                if (simToChat == null)
                {
                    flag = true;
                }
                else
                {
                    SimDescription simDescription = simToChat.SimDescription;
                    if ((simDescription == null) || !simDescription.IsValidDescription)
                    {
                        flag = true;
                    }
                }

                if (flag)
                {
                    Actor.AddExitReason(ExitReason.Finished);
                }
                else
                {
                    int lifeTime = (int)loopData.mLifeTime;
                    if (Actor.HasTrait(TraitNames.AntiTV) && (lifeTime > Computer.kTechnophobeTraitMaximumChatTime))
                    {
                        Actor.AddExitReason(ExitReason.Finished);
                    }

                    int chatRelationshipIncreaseEveryXMinutes = Target.ComputerTuning.ChatRelationshipIncreaseEveryXMinutes;
                    if (chatRelationshipIncreaseEveryXMinutes != 0)
                    {
                        if ((lifeTime / Target.ComputerTuning.ChatRelationshipIncreaseEveryXMinutes) > RelationshipIncreases)
                        {
                            RelationshipIncreases++;
                            Target.ChatUpdate(Actor, simToChat, Target);
                        }
                    }

                    int cyberWoohooChanceToClimaxEveryXMinutes = KamaSimtra.Settings.mCyberWoohooChanceToClimaxEveryXMinutes;
                    if (cyberWoohooChanceToClimaxEveryXMinutes != 0)
                    {
                        if ((lifeTime / cyberWoohooChanceToClimaxEveryXMinutes) > mClimaxChances)
                        {
                            mClimaxChances++;

                            if (RandomUtil.RandomChance(KamaSimtra.Settings.mCyberWoohooChanceToClimax * mClimaxChances))
                            {
                                CommonWoohoo.RunPostWoohoo(Actor, simToChat, Target, CommonWoohoo.WoohooStyle.Safe, CommonWoohoo.WoohooLocation.Computer, false);

                                Actor.AddExitReason(ExitReason.Finished);
                            }
                        }
                    }

                    if (timeTillLearn < lifeTime)
                    {
                        Relationship relation = Relationship.Get(Actor, simToChat, true);
                        if (relation != null)
                        {
                            relation.ConsiderLearningAboutTargetSim(Actor, simToChat, Target.ComputerTuning.ChatIntimacylevel);
                        }

                        timeTillLearn = lifeTime + RandomUtil.RandomFloatGaussianDistribution(Target.ComputerTuning.ChatLearnSomethingFrequencyStart, Target.ComputerTuning.ChatLearnSomethingFrequencyEnd);
                    }
                }
            }
            catch (ResetException)
            {
                throw;
            }
            catch (Exception e)
            {
                Common.Exception(Actor, Target, e);
                Actor.AddExitReason(ExitReason.Finished);
            }
        }
示例#4
0
        protected override bool PrivateUpdate(ScenarioFrame frame)
        {
            List <GameObject> tables  = new List <GameObject>();
            List <GameObject> empties = new List <GameObject>();

            OccupationNames occupation = OccupationNames.Undefined;
            SkillNames      skill      = SkillNames.Painting;

            if (Sim.CreatedSim.Occupation is Stylist)
            {
                skill      = SkillNames.Styling;
                occupation = OccupationNames.Stylist;
            }
            else if (Sim.CreatedSim.Occupation is InteriorDesigner)
            {
                occupation = OccupationNames.InteriorDesigner;
            }

            foreach (Lot lot in ManagerLot.GetOwnedLots(Sim.Household))
            {
                foreach (DraftingTable table in lot.GetObjects <DraftingTable>())
                {
                    if (table.Stool == null)
                    {
                        continue;
                    }

                    if (table.InUse)
                    {
                        continue;
                    }

                    DraftingTable.Canvas draft = table.Draft;
                    if (draft != null)
                    {
                        if (!table.IsDraftValid(Sim.CreatedSim, skill, occupation))
                        {
                            IncStat("Draft Mismatch");
                            continue;
                        }
                        else if ((draft.IsComplete) && (!TakeDraft(table)))
                        {
                            IncStat("Take Fail");
                            continue;
                        }
                        else
                        {
                            tables.Add(table);
                        }
                    }
                    else
                    {
                        empties.Add(table);
                    }
                }
            }

            if (tables.Count == 0)
            {
                tables.AddRange(empties);
            }

            if (tables.Count == 0)
            {
                IncStat("No Tables");
                return(false);
            }

            GameObject choice = RandomUtil.GetRandomObjectFromList(tables);

            if (Sim.CreatedSim.Occupation is Stylist)
            {
                return(Situations.PushInteraction(this, Sim, choice, DraftingTable.Research.SingletonStylist));
            }
            else if (Sim.CreatedSim.Occupation is InteriorDesigner)
            {
                return(Situations.PushInteraction(this, Sim, choice, DraftingTable.Research.SingletonInteriorDesigner));
            }
            else
            {
                return(Situations.PushInteraction(this, Sim, choice, DraftingTable.Research.SingletonPainting));
            }
        }
 private static string createBoundary()
 {
     return("boundary" + RandomUtil.getRandomLong());
 }
示例#6
0
 public override void OnKill(BattleUnitModel target)
 {
     base.OnKill(target);
     RandomUtil.SelectOne <BattleUnitModel>(BattleObjectManager.instance.GetAliveList_opponent(this.owner.faction)).bufListDetail.AddBuf(new BattleUnitBuf_AttackTarget());
 }
示例#7
0
        protected override bool PrivateUpdate(ScenarioFrame frame)
        {
            base.PrivateUpdate(frame);

            CatHuntingSkill skill = Sim.SkillManager.AddElement(SkillNames.CatHunting) as CatHuntingSkill;

            if (skill == null)
            {
                IncStat("Skill Fail");
                return(false);
            }

            if ((skill.SkillLevel < 1) || (!skill.CanCatchAnything()) || (RandomUtil.RandomChance(25)))
            {
                PopulateFishingPoints();

                List <GameObjectHit> fishingSpots = new List <GameObjectHit>();
                foreach (Pair <Lot, GameObjectHit> pair in sFishingPoints)
                {
                    if ((pair.First.IsCommunityLot) || (pair.First.CanSimTreatAsHome(Sim.CreatedSim)))
                    {
                        fishingSpots.Add(pair.Second);
                    }
                }

                if (fishingSpots.Count != 0x0)
                {
                    Terrain.CatFishHere fishing = Terrain.CatFishHere.Singleton.CreateInstance(Terrain.Singleton, Sim.CreatedSim, Sim.CreatedSim.InheritedPriority(), true, true) as Terrain.CatFishHere;
                    if (fishing == null)
                    {
                        IncStat("Fish Creation Fail");
                    }
                    else
                    {
                        fishing.Hit = RandomUtil.GetRandomObjectFromList <GameObjectHit>(fishingSpots);

                        if (Situations.PushInteraction(this, Sim, Managers.Manager.AllowCheck.Active, fishing))
                        {
                            return(true);
                        }

                        IncStat("Fish Fail");
                    }
                }
                else
                {
                    IncStat("No Fishing Spots");
                }
            }

            List <SimDescription> choices = new List <SimDescription>();

            foreach (SimDescription sim in new SimScoringList(this, "LikesCats", HouseholdsEx.Humans(Sim.Household), false).GetBestByMinScore(1))
            {
                if (sim.ChildOrBelow)
                {
                    continue;
                }

                choices.Add(sim);
            }

            if (choices.Count == 0)
            {
                IncStat("No Master");
                return(false);
            }

            CatHuntingComponent.StalkForPrey interaction = CatHuntingComponent.StalkForPrey.Singleton.CreateInstance(Sim.CreatedSim, Sim.CreatedSim, Sim.CreatedSim.InheritedPriority(), true, true) as CatHuntingComponent.StalkForPrey;
            if (interaction == null)
            {
                IncStat("Catch Creation Fail");
                return(false);
            }

            interaction.PushedByGoCatch         = true;
            interaction.PickAnyPrey             = true;
            interaction.PresentToID             = RandomUtil.GetRandomObjectFromList(choices).SimDescriptionId;
            interaction.ForceCatchFailureObject = false;

            if (Situations.PushInteraction(this, Sim, Managers.Manager.AllowCheck.Active, interaction))
            {
                return(true);
            }

            IncStat("Catch Prey Fail");
            return(false);
        }
示例#8
0
        public static Vehicle Sim_GetVehicle(Sim ths, Lot lot, bool allowUFO)
        {
            if (ths.IsPet)
            {
                return(null);
            }

            var vehicleForCurrentInteraction = ths.GetVehicleForCurrentInteraction();

            if (vehicleForCurrentInteraction != null && !(vehicleForCurrentInteraction is Boat))
            {
                return(vehicleForCurrentInteraction);
            }

            bool child    = ths.Posture == null || !ths.Posture.Satisfies(CommodityKind.CarryingChild, null);
            bool canDrive = ths.CanDriveOrCallTaxi();

            if (canDrive &&
                !Vehicle.WorldHasSpecialCarRules(GameUtils.GetCurrentWorld())

                && (!(ths.SimRoutingComponent != null && ths.SimRoutingComponent.AllowBikes)

                    || (ths.Autonomy != null &&
                        ths.Autonomy.SituationComponent != null &&
                        ths.Autonomy.SituationComponent.InSituationOfType(typeof(GoHereWithSituation)))

                    || ths.CurrentInteraction is TravelUtil.SitInCarToTriggerTravel ||
                    ths.CurrentInteraction is TravelUtil.SitInCarToReturnHomeWithinHomeWorld))
            {
                child = false;
            }

            Vehicle vehicle = null;

            vehicle = ths.GetOwnedAndUsableVehicle(lot, true, child && !ths.IsHoldingAnything(), !GameUtils.IsInstalled(ProductVersion.EP4), allowUFO);

            if (vehicle == null || vehicle.HasBeenDestroyed)
            {
                if (canDrive)
                {
                    if (ths.SimDescription == null)
                    {
                        return(null);
                    }

                    if (child)
                    {
                        vehicle = Vehicle_CreateTaxiBicycle(ths.SimDescription.Child);
                    }
                    else if (ths.SimDescription.CanDrive && ths.IsHoldingAnything())
                    {
                        IGameObject gameObject = (!GameUtils.IsInstalled(ProductVersion.EP11) ||
                                                  GameUtils.GetCurrentWorld() != WorldName.FutureWorld) ?
                                                 GlobalFunctions.CreateObjectOutOfWorld(RandomUtil.CoinFlip() ?
                                                                                        "CarUsed2" : "CarSedan", ProductVersion.BaseGame, null, null)
                            : GlobalFunctions.CreateObjectOutOfWorld(RandomUtil.CoinFlip() ? "HoverCarUsed"
                            : "HoverCarExpensive", ProductVersion.EP11, null, null);

                        CarOwnable carOwnable = gameObject as CarOwnable;
                        if (carOwnable != null)
                        {
                            Lot       lotHome   = ths.LotHome;
                            Household household = ths.Household;

                            if (lotHome != null && household != null && !household.IsServiceNpcHousehold)
                            {
                                int cost = carOwnable.Cost;
                                if (ths.FamilyFunds >= cost)
                                {
                                    ths.ModifyFunds(-cost);
                                }
                                else
                                {
                                    household.UnpaidBills += cost;
                                }
                            }

                            carOwnable.GeneratedOwnableForNpc = (lotHome == null);
                            carOwnable.DestroyOnRelease       = (lotHome == null);
                            carOwnable.LotHome = lotHome;

                            vehicle = carOwnable;
                        }
                        else if (gameObject != null)
                        {
                            gameObject.Destroy();
                            vehicle = null;
                        }
                    }
                    else
                    {
                        try
                        {
                            if (CarNpcManager.Singleton == null)
                            {
                                throw new NullReferenceException("CarNpcManager.Singleton == null");
                            }
                            vehicle = CarNpcManager.Singleton.CreateNpcCar(CarNpcManager.NpcCars.Taxi);
                        }
                        catch (ResetException)
                        {
                            throw;
                        }
                        catch (Exception) { }
                    }
                }
                else
                {
                    if (ths.IsHoldingAnything())
                    {
                        return(null);
                    }
                    vehicle = Vehicle_CreateTaxiBicycle(ths.SimDescription.Child);
                }
            }

            if (vehicle == null || vehicle.HasBeenDestroyed)
            {
                if (child && !ths.IsHoldingAnything() && ths.SimDescription != null)
                {
                    vehicle = Vehicle_CreateTaxiBicycle(ths.SimDescription.Child);
                }
                else if (CarNpcManager.Singleton != null)
                {
                    vehicle = CarNpcManager.Singleton.CreateNpcCar(CarNpcManager.NpcCars.Taxi);
                }
            }
            return(vehicle);
        }
示例#9
0
        protected override bool PrivateUpdate(ScenarioFrame frame)
        {
            List <Book> choices = new List <Book>();

            if ((choices.Count == 0) && (AllowSkill))
            {
                mBooks.Clear();

                foreach (BookSkill book in Inventories.InventoryDuoFindAll <BookSkill, Book>(Sim))
                {
                    GreyedOutTooltipCallback greyedOutTooltipCallback = null;
                    if (!book.TestReadBook(Sim.CreatedSim, false, ref greyedOutTooltipCallback))
                    {
                        continue;
                    }

                    BookSkillData data = book.Data as BookSkillData;
                    if (data == null)
                    {
                        continue;
                    }

                    if (mBooks.ContainsKey(data.SkillGuid))
                    {
                        continue;
                    }

                    mBooks.Add(data.SkillGuid, book);
                }

                foreach (Lot lot in ManagerLot.GetOwnedLots(Sim))
                {
                    foreach (BookSkill book in lot.GetObjects <BookSkill>())
                    {
                        GreyedOutTooltipCallback greyedOutTooltipCallback = null;
                        if (!book.TestReadBook(Sim.CreatedSim, false, ref greyedOutTooltipCallback))
                        {
                            continue;
                        }

                        BookSkillData data = book.Data as BookSkillData;
                        if (data == null)
                        {
                            continue;
                        }

                        if (mBooks.ContainsKey(data.SkillGuid))
                        {
                            continue;
                        }

                        mBooks.Add(data.SkillGuid, book);
                    }
                }

                if ((!Sim.CreatedSim.LotCurrent.IsResidentialLot) && (!Sim.CreatedSim.LotCurrent.IsWorldLot))
                {
                    foreach (BookSkill book in Sim.CreatedSim.LotCurrent.GetObjects <BookSkill>())
                    {
                        GreyedOutTooltipCallback greyedOutTooltipCallback = null;
                        if (!book.TestReadBook(Sim.CreatedSim, false, ref greyedOutTooltipCallback))
                        {
                            continue;
                        }

                        BookSkillData data = book.Data as BookSkillData;
                        if (data == null)
                        {
                            continue;
                        }

                        if (mBooks.ContainsKey(data.SkillGuid))
                        {
                            continue;
                        }

                        mBooks.Add(data.SkillGuid, book);
                    }
                }

                if (mBooks.Count > 0)
                {
                    if (base.PrivateUpdate(frame))
                    {
                        return(true);
                    }
                    else
                    {
                        if (choices.Count == 0)
                        {
                            choices.AddRange(mBooks.Values);
                        }
                    }
                }
            }

            if ((choices.Count == 0) && (AllowNormal))
            {
                Dictionary <BookData, Book> books = new Dictionary <BookData, Book>();

                foreach (BookGeneral book in Inventories.InventoryDuoFindAll <BookGeneral, Book>(Sim))
                {
                    GreyedOutTooltipCallback greyedOutTooltipCallback = null;
                    if (!book.TestReadBook(Sim.CreatedSim, false, ref greyedOutTooltipCallback))
                    {
                        continue;
                    }

                    if (Sim.ReadBookDataList.ContainsKey(book.Data.ID))
                    {
                        continue;
                    }

                    if (books.ContainsKey(book.Data))
                    {
                        continue;
                    }

                    books.Add(book.Data, book);
                }

                foreach (Lot lot in ManagerLot.GetOwnedLots(Sim))
                {
                    foreach (BookGeneral book in lot.GetObjects <BookGeneral>())
                    {
                        GreyedOutTooltipCallback greyedOutTooltipCallback = null;
                        if (!book.TestReadBook(Sim.CreatedSim, false, ref greyedOutTooltipCallback))
                        {
                            continue;
                        }

                        if (Sim.ReadBookDataList.ContainsKey(book.Data.ID))
                        {
                            continue;
                        }

                        if (books.ContainsKey(book.Data))
                        {
                            continue;
                        }

                        books.Add(book.Data, book);
                    }
                }

                if ((!Sim.CreatedSim.LotCurrent.IsResidentialLot) && (!Sim.CreatedSim.LotCurrent.IsWorldLot))
                {
                    foreach (BookGeneral book in Sim.CreatedSim.LotCurrent.GetObjects <BookGeneral>())
                    {
                        GreyedOutTooltipCallback greyedOutTooltipCallback = null;
                        if (!book.TestReadBook(Sim.CreatedSim, false, ref greyedOutTooltipCallback))
                        {
                            continue;
                        }

                        if (Sim.ReadBookDataList.ContainsKey(book.Data.ID))
                        {
                            continue;
                        }

                        if (books.ContainsKey(book.Data))
                        {
                            continue;
                        }

                        books.Add(book.Data, book);
                    }
                }

                if (books.Count > 0)
                {
                    choices.AddRange(books.Values);
                }
            }

            if (choices.Count > 0)
            {
                return(Perform(RandomUtil.GetRandomObjectFromList(choices)));
            }

            return(false);
        }
示例#10
0
        public SpinResult Spin(long accountId, string accountName, int roomId, MoneyType moneyType, string lineData)
        {
            String s = "[tamquoc] Spin play: " +
                       "\r\naccountId: " + accountId +
                       "\r\naccountName: " + accountName +
                       "\r\nroomId: " + roomId +
                       "\r\nmoneyType: " + moneyType +
                       "\r\nlineData: " + lineData;
            var roomValue     = GetBetValueByRoom(roomId);
            var totalBetValue = lineData.Split(',').Length *roomValue;
            var slotsData     = _testService.IsTestAccount(accountName) ? _testService.GetTestData() : _slotsGeneService.GenerateSlotsData();

            var       newSlotsData = _slotsGeneService.HandleSlotsData(slotsData);
            var       slotMachine  = new SlotMachine();
            var       prizeLines   = slotMachine.GetLinesPrize(newSlotsData, roomValue, lineData, out var isJackpot, out var payLinePrizeValue);
            var       countBonus   = slotsData.Count(x => x == 3); // Đếm biểu tượng bonus
            var       countScatter = slotsData.Count(x => x == 2); // đếm biểu tượng freeSpins
            BonusGame bonusGame    = null;

            // Tạo Bonus Game nếu có
            if (countBonus >= 3)
            {
                bonusGame = _bonusGeneService.GenerateBonusGame(totalBetValue, countBonus - 2);
                s        += "\r\nWin bonus: " + JsonConvert.SerializeObject(bonusGame);
            }

            var addFreeSpins = 0;

            if (countScatter >= 3)
            {
                addFreeSpins = (countScatter - 2) * 4;  // Thêm lượt FreeSpins
                s           += "\r\nWin Free spin: " + addFreeSpins;
            }
            var inputSpinData = new InputSpinData()
            {
                AccountId       = accountId,
                AccountName     = accountName,
                MoneyType       = moneyType,
                AddFreeSpins    = addFreeSpins,
                RoomId          = roomId,
                IsJackpot       = isJackpot,
                SlotsData       = string.Join(",", slotsData.Select(x => x.ToString())),
                TotalBonusValue = countBonus > 3 ? bonusGame.TotalPrizeValue : 0,
                TotalPrizeValue = payLinePrizeValue,
                LineData        = lineData,
                TotalBetValue   = totalBetValue
            };
            var outputSpinData = _dbService.Spin(inputSpinData);

            if (outputSpinData.ResponseStatus < 0)
            {
                if (outputSpinData.ResponseStatus == -90) // Limit Fund
                {
                    return(new SpinResult()
                    {
                        SpinId = outputSpinData.SpinId,
                        SlotsData = _missData[RandomUtil.NextInt(0, _missData.Length)],
                        AddFreeSpin = 0,
                        PrizeLines = new List <PrizeLine>(),
                        Balance = outputSpinData.Balance,
                        FreeSpins = outputSpinData.FreeSpins,
                        Jackpot = outputSpinData.Jackpot,
                        ResponseStatus = 1
                    });
                }
                return(new SpinResult()
                {
                    ResponseStatus = outputSpinData.ResponseStatus
                });
            }

            if (countBonus >= 3)
            {
                _dbService.CreateBonusGame(moneyType, outputSpinData.SpinId, roomId, accountId, accountName, totalBetValue, bonusGame.BonusData, bonusGame.Mutiplier, bonusGame.TotalPrizeValue, out var bonusResponse);
            }

            UpdateCacheJackpot(roomId, outputSpinData.Jackpot, moneyType); // Cập nhật jackpot cho cache
            var totalPrizeValue = payLinePrizeValue + outputSpinData.TotalJackpotValue;

            HonorHandler.Instance.SaveHonor(accountName, roomId, totalPrizeValue, inputSpinData.IsJackpot ? 1 : 2); // Luu vinh danh

            var d = new SpinResult()
            {
                SpinId                 = outputSpinData.SpinId,
                SlotsData              = slotsData,
                AddFreeSpin            = addFreeSpins,
                IsJackpot              = isJackpot,
                PrizeLines             = prizeLines,
                BonusGame              = bonusGame,
                TotalPrizeValue        = payLinePrizeValue + outputSpinData.TotalJackpotValue,
                TotalPaylinePrizeValue = payLinePrizeValue,
                TotalJackpotValue      = outputSpinData.TotalJackpotValue,
                Balance                = outputSpinData.Balance,
                FreeSpins              = outputSpinData.FreeSpins,
                Jackpot                = outputSpinData.Jackpot,
                ResponseStatus         = outputSpinData.ResponseStatus
            };

            s += "\r\nResponse: " + JsonConvert.SerializeObject(d);
            NLogManager.LogMessage(s);
            return(d);
        }
示例#11
0
        public ActionResult NM_PerformAction()
        {
            if (dontCall)
            {
                return(ActionResult.Continue);
            }

            Boat boat = null;

            try
            {
                mRoutingSim.SimRoutingComponent.DisallowBeingPushed = true;

                if (mRoutingSim.HasExitReason((ExitReason)mOriginalRoute.ExitReasonsInterrupt))
                {
                    AddFailureExplanation(FailureExplanation.CancelledByScript);
                    return(ActionResult.Terminate);
                }

                Lot lot = (mOriginalRoute == null) ? mRoutingSim.LotCurrent : LotManager.GetLotAtPoint(mOriginalRoute.GetOriginalStartPoint());
                boat = Sim_GetBoatForGetInBoatRouteAction(mRoutingSim, lot);
                if (boat == null)
                {
                    AddFailureExplanation(FailureExplanation.VehicleSequenceFailure);
                    return(ActionResult.Terminate);
                }

                mLastFoundBoatId = boat.ObjectId;
                Vector3 pt;
                mOriginalRoute.GetSegmentStartPoint(0u, out pt);
                Vector3 dir;
                mOriginalRoute.GetSegmentStartDirection(0u, out dir);

                mBoatAppearingPt = pt;

                mnReplanFrequency = RandomUtil.GetInt(SimRoutingComponent.AvoidanceReplanCheckFrequencyMin, SimRoutingComponent.AvoidanceReplanCheckFrequencyMax);
                mnReplanOffset    = RandomUtil.GetInt(SimRoutingComponent.AvoidanceReplanCheckOffsetMin, SimRoutingComponent.AvoidanceReplanCheckOffsetMax);

                StandAndWaitController standAndWaitController = new StandAndWaitController();
                standAndWaitController.AllowZeroCycle = true;
                standAndWaitController.Duration       = SimRoutingComponent.DefaultStandAndWaitDuration;
                standAndWaitController.OnCycle        = base.StandAndWaitCycleHandler;
                standAndWaitController.Run(mRoutingSim);

                if (mStandAndWaitResult == ActionResult.Terminate)
                {
                    if (mLastFoundObstruction.IsValid && mOriginalRoute.DoRouteFail)
                    {
                        mRoutingSim.SimRoutingComponent.PlayRouteFailureIfAppropriate(mLastFoundObstruction.ObjectFromId <GameObject>());
                    }
                    return(mStandAndWaitResult);
                }

                if (mStandAndWaitResult == ActionResult.ContinueAndFollowPath)
                {
                    return(mStandAndWaitResult);
                }

                ItemComponent itemComp = boat.ItemComp;
                if (itemComp != null && itemComp.InventoryParent != null)
                {
                    itemComp.InventoryParent.RemoveByForce(boat);
                }

                MooringPost mooringPost = boat.Parent as MooringPost;
                if (mooringPost != null)
                {
                    mooringPost.UnReserveSpot(boat);
                }

                boat.PlaceAt(pt, dir, mRoutingSim);

                BoatRoutingComponent boatRoutingComponent = boat.RoutingComponent as BoatRoutingComponent;
                if (boatRoutingComponent != null)
                {
                    boatRoutingComponent.ForceUpdateDynamicFootprint();
                    boatRoutingComponent.EnableDynamicFootprint();
                }

                mRoutingSim.FadeOut(true, 0.5f, null);

                if (!boat.HaveSimWaitBeforeGettingIn(mRoutingSim))
                {
                    mRoutingSim.FadeIn(false, 0f);
                    return(ActionResult.Terminate);
                }

                boat.SimIsGettingIn = true;

                if (boat.Driver == null)
                {
                    boat.PutInDriver(mRoutingSim);
                }
                else
                {
                    boat.PutInPassenger(mRoutingSim);
                }

                boat.SimIsGettingIn = false;

                if (!(boat is BoatTaxi))
                {
                    mRoutingSim.FadeIn(true, 0.5f);
                }

                GameObject objectInRightHand = mRoutingSim.GetObjectInRightHand();
                if (objectInRightHand != null && !(objectInRightHand is Sim))
                {
                    objectInRightHand.SetHiddenFlags(HiddenFlags.Model);
                }

                mRoutingSim.SimRoutingComponent.ClearPush();

                mOriginalRoute.FollowerAgeGenderSpecies = (uint)boat.GetBoatSpecies();
                mOriginalRoute.Follower = boat.Proxy;
                mOriginalRoute.SetOption2(Route.RouteOption2.BeginAsBoat, true);
                mOriginalRoute.SetOption2(Route.RouteOption2.UseFollowerStartOrientation, boat.UsesTurnHelperFootprint());
                mOriginalRoute.SetOption(Route.RouteOption.RouteAsGhost, false);

                return(ActionResult.ContinueAndPopPathAndReplan);
            }
            catch
            {
                if (boat != null && boat.DestroyOnRelease)
                {
                    boat.Destroy();
                }
                throw;
            }
            finally
            {
                mRoutingSim.SimRoutingComponent.DisallowBeingPushed = false;
            }
        }
示例#12
0
        public LuckyGame PlayLuckyGame(MoneyType moneyType, long accountId, string accountName, int roomId, X2Game step, int spinId)
        {
            var result = RandomUtil.NextInt(2);

            return(_dbService.PlayLuckyGame(moneyType, accountId, accountName, roomId, spinId, step, result));
        }
示例#13
0
        public override bool Run()
        {
            try
            {
                BuffInstance element = Actor.BuffManager.GetElement(BuffNames.ReallyHasToPee);
                if ((element != null) && (element.mTimeoutCount <= Urinal.kTimeoutRemainingForBladderEmergency))
                {
                    RequestWalkStyle(Sim.WalkStyle.Run);
                }
                if (!Target.Line.WaitForTurn(this, SimQueue.WaitBehavior.DefaultAllowSubstitution, ~(ExitReason.Replan | ExitReason.MidRoutePushRequested | ExitReason.ObjectStateChanged | ExitReason.PlayIdle | ExitReason.MaxSkillPointsReached), Urinal.kTimeToWaitInLine))
                {
                    return(false);
                }
                if (!Target.RouteToUrinalAndCheckInUse(Actor))
                {
                    return(false);
                }
                ClearRequestedWalkStyles();

                if (Shooless.Settings.GetPrivacy(Target))
                {
                    mSituation = Urinal.UrinalSituation.Create(Actor, Actor.LotCurrent);
                }

                if (mSituation != null)
                {
                    if (!mSituation.Start())
                    {
                        return(false);
                    }
                    if (!Target.RouteToUrinalAndCheckInUse(Actor))
                    {
                        return(false);
                    }
                }
                CancellableByPlayer = false;
                StandardEntry();
                mCurrentStateMachine = Target.GetStateMachine(Actor);
                Glass.CarryingGlassPosture posture = Actor.Posture as Glass.CarryingGlassPosture;
                if (posture != null)
                {
                    mDrinkInHand = posture.ObjectBeingCarried as Glass;
                    CarrySystem.ExitCarry(Actor);
                    mDrinkInHand.FadeOut(true);
                    mDrinkInHand.UnParent();
                    Actor.PopPosture();
                    SetParameter("hasDrink", true);
                    SetActor("drink", mDrinkInHand);
                    if (Target.HasDrinkSlot && (Target.GetContainedObject(Slot.ContainmentSlot_0) == null))
                    {
                        mDrinkInHand.ParentToSlot(Target, Slot.ContainmentSlot_0);
                        mDrinkInHand.FadeIn();
                    }
                }
                mCensorEnabled = true;
                Actor.EnableCensor(Sim.CensorType.LowerBody);
                AddOneShotScriptEventHandler(0x78, OnAnimationEvent);
                AnimateSim("use");
                if (element != null)
                {
                    element.mTimeoutPaused = true;
                }
                if (Actor.HasTrait(TraitNames.Inappropriate))
                {
                    mWillFart = RandomUtil.RandomChance01(Urinal.kChanceInappropriateFart);
                    if (mWillFart)
                    {
                        mFartTime = RandomUtil.RandomFloatGaussianDistribution(0.1f, 0.9f);
                    }
                }
                BeginCommodityUpdate(CommodityKind.Bladder, 0f);
                BeginCommodityUpdates();
                bool succeeded = false;

                try
                {
                    Actor.Motives.LerpToFill(this, CommodityKind.Bladder, Urinal.kMaxLengthUseToilet);
                    StartStages();

                    succeeded = DoLoop(~(ExitReason.Replan | ExitReason.MidRoutePushRequested | ExitReason.ObjectStateChanged | ExitReason.PlayIdle | ExitReason.BuffFailureState | ExitReason.MaxSkillPointsReached | ExitReason.HigherPriorityNext), new Interaction <Sim, Urinal> .InsideLoopFunction(LoopFunc), mCurrentStateMachine);
                }
                finally
                {
                    EndCommodityUpdates(succeeded);
                }

                if (succeeded)
                {
                    Motive motive = Actor.Motives.GetMotive(CommodityKind.Bladder);
                    if (motive != null)
                    {
                        motive.PotionBladderDecayOverride = false;
                    }
                }

                if (element != null)
                {
                    element.mTimeoutPaused = false;
                }

                if (Target.IsCleanable)
                {
                    Target.Cleanable.DirtyInc(Actor);
                }

                bool flag2 = Target.Line.MemberCount() > 0x1;
                InteractionInstance instance = null;
                if ((mSituation == null) || !mSituation.SomeoneDidIntrude)
                {
                    if (Target.AutoFlushes)
                    {
                        Target.FlushToilet(Actor, mCurrentStateMachine, false);
                    }
                    else
                    {
                        Target.ToiletVolume++;
                        if (Target.ShouldFlush(Actor, Autonomous))
                        {
                            Target.FlushToilet(Actor, mCurrentStateMachine, true);
                        }
                    }
                    if (((mDrinkInHand == null) && Urinal.ShouldWashHands(Actor)) && !flag2)
                    {
                        Sink target = Toilet.FindClosestSink(Actor);
                        if (target != null)
                        {
                            instance = Sink.WashHands.Singleton.CreateInstance(target, Actor, GetPriority(), false, true);
                        }
                    }
                }
                AddOneShotScriptEventHandler(0x68, OnAnimationEvent);
                AddOneShotScriptEventHandler(0x64, OnAnimationEvent);
                AnimateSim("exit");
                if (mSituation != null)
                {
                    mSituation.ExitUrinalSituation();
                }
                if (mDrinkInHand != null)
                {
                    CarrySystem.EnterWhileHolding(Actor, mDrinkInHand);
                    Actor.Posture = new Glass.CarryingGlassPosture(Actor, mDrinkInHand);
                    mDrinkInHand.FadeIn();
                }
                if (flag2)
                {
                    PrivacySituation.RouteToAdjacentRoom(Actor);
                }
                StandardExit();
                if (instance != null)
                {
                    Actor.InteractionQueue.PushAsContinuation(instance, true);
                }
                if (!flag2 && (instance == null))
                {
                    Actor.RouteAway(Urinal.kMinDistanceToMoveAwayAfterUsingUrinal, Urinal.kMaxDistanceToMoveAwayAfterUsingUrinal, false, GetPriority(), true, true, true, RouteDistancePreference.NoPreference);
                }
                return(succeeded);
            }
            catch (ResetException)
            {
                throw;
            }
            catch (Exception e)
            {
                Common.Exception(Actor, Target, e);
                return(false);
            }
        }
示例#14
0
        protected bool AddCoworker(Career job)
        {
            SimDescription newCoworker = null;

            if (!job.GetType().ToString().StartsWith("Sims3."))
            {
                List <SimDescription> previous = new List <SimDescription>(job.Coworkers);

                if (job.AddCoworker())
                {
                    foreach (SimDescription sim in job.Coworkers)
                    {
                        if (previous.Contains(sim))
                        {
                            continue;
                        }

                        newCoworker = sim;
                        break;
                    }
                }
            }
            else
            {
                List <SimDescription> candidateCoworkers = new List <SimDescription>();
                foreach (SimDescription sim in job.CareerLoc.Workers)
                {
                    if (IsValid(job, sim, true))
                    {
                        candidateCoworkers.Add(sim);
                    }
                }

                if (candidateCoworkers.Count == 0)
                {
                    foreach (CareerLocation location in job.Locations)
                    {
                        if (location == job.CareerLoc)
                        {
                            continue;
                        }

                        location.CheckWorkers();
                        foreach (SimDescription coworker in location.Workers)
                        {
                            if (IsValid(job, coworker, true))
                            {
                                candidateCoworkers.Add(coworker);
                            }
                        }
                    }
                }

                if (candidateCoworkers.Count > 0)
                {
                    newCoworker = RandomUtil.GetRandomObjectFromList(candidateCoworkers);
                    job.AddCoworker(newCoworker);
                }
            }

            if (newCoworker != null)
            {
                if (GetValue <MeetImmediatelyOption, bool>())
                {
                    Relationship.Get(job.OwnerDescription, newCoworker, true).MakeAcquaintances();
                }
                else
                {
                    Relationship.Get(job.OwnerDescription, newCoworker, true);
                }

                if (!SimTypes.IsSelectable(newCoworker))
                {
                    mNewCoworkers.Add(newCoworker);
                }

                IncStat("Added");
                return(true);
            }
            else
            {
                IncStat("No choices");
                return(false);
            }
        }
示例#15
0
        public override bool Run() // Run
        {
            if (Autonomous || Actor.IsNPC)
            {
                return(false);
            }
            if (!NFinalizeDeath.CheckAccept("Are You Sure All Kill Sim?"))
            {
                return(false);
            }

            List <Sim> list = new List <Sim>();

            foreach (Sim sim in NFinalizeDeath.SC_GetObjects <Sim>())
            {
                //if (sim.SimDescription.ToddlerOrAbove && !sim.IsInActiveHousehold && sim.LotCurrent != Household.ActiveHousehold.LotHome) //OK
                //if (!sim.IsInActiveHousehold || !(sim.Service is GrimReaper)) //Failed
                //if (sim.IsNPC && !sim.IsInActiveHousehold) //OK
                //if (sim.IsNPC && !sim.IsInActiveHousehold || !(sim.Service is GrimReaper)) // Failed All Sim Not If ||
                //if (!(sim.Service is GrimReaper)) // OK
                {
                    //sim.InteractionQueue.AddNext(NotKillSimNPCOnly.Singleton.CreateInstance(sim, sim, new InteractionPriority((InteractionPriorityLevel)12, 1f), false, true));
                    //SpeedTrap.Sleep(1);
                    //if (!NFinalizeDeath.CheckAccept("Done?")) return false;
                    //sim.InteractionQueue.Add(CCnlean.Singleton.CreateInstance(Actor, sim, new InteractionPriority((InteractionPriorityLevel)1, 0f), false, true));
                    list.Add(sim);
                }
            }
            if (list.Count > 0)
            {
                foreach (Sim nlist in list)
                {
                    try
                    {
                        //Name is
                        if (nlist.SimDescription.FirstName == "Death" && nlist.SimDescription.LastName == "Good System")
                        {
                            continue;
                        }

                        if (nlist.SimDescription.FirstName == "Good System" && nlist.SimDescription.LastName == "Death Helper")
                        {
                            continue;
                        }

                        if (nlist.SimDescription.FirstName == "Grim" && nlist.SimDescription.LastName == "Reaper")
                        {
                            continue;
                        }
                    }
                    catch (NullReferenceException)
                    { }
                    //nlist.BuffManager.RemoveAllElements();

                    /*
                     * List<SimDescription.DeathType> listr = new List<SimDescription.DeathType>();
                     * listr.Add(SimDescription.DeathType.Drown);
                     * listr.Add(SimDescription.DeathType.Starve);
                     * listr.Add(SimDescription.DeathType.Thirst);
                     * listr.Add(SimDescription.DeathType.Burn);
                     * listr.Add(SimDescription.DeathType.Freeze);
                     * listr.Add(SimDescription.DeathType.ScubaDrown);
                     * listr.Add(SimDescription.DeathType.Shark);
                     * listr.Add(SimDescription.DeathType.Jetpack);
                     * listr.Add(SimDescription.DeathType.Meteor);
                     * listr.Add(SimDescription.DeathType.Causality);
                     * listr.Add(SimDescription.DeathType.Electrocution);
                     * if (Actor.SimDescription.Elder)
                     * {
                     *  listr.Add(SimDescription.DeathType.OldAge);
                     * }
                     * listr.Add(SimDescription.DeathType.HauntingCurse);
                     * SimDescription.DeathType randomObjectFromList = RandomUtil.GetRandomObjectFromList(listr);
                     * //Urnstones.CreateGrave(nlist.SimDescription, randomObjectFromList, true, true);
                     */
                    //KillTask kt = new KillTask(Target, RandomUtil.CoinFlip() ? KillTask.GetDGSDeathType(Target) : KillTask.GetDeathType(Target), null, false, false);
                    //kt.AddToSimulator();
                    KillPro.FastKill(nlist, RandomUtil.CoinFlip() ? KillTask.GetDGSDeathType(Target) : KillTask.GetDeathType(Target), Actor, true, false);
                }
                //nlist.InteractionQueue.CancelAllInteractionsByType(NotKillSimNPCOnly.Singleton);
            }
            return(true);
        }
示例#16
0
        public static BTResult AmphibiousMovement(Animal agent, Vector2 generalDirection, bool wandering, AnimalState state, float minDistance = 2f, float maxDistance = 20f)
        {
            var startPathPos = agent.Position.WorldPosition3i;

            //Plop us into water if we're above it.
            if (World.World.GetBlock((Vector3i)startPathPos.Down()).GetType() == typeof(WaterBlock))
            {
                startPathPos = startPathPos.Down();
            }

            if (!World.World.IsUnderwater(startPathPos))
            {
                startPathPos = RouteManager.NearestWalkablePathPos(agent.Position.WorldPosition3i); //Boot us down/up to the surface if we're on land.
            }
            if (!startPathPos.IsValid)
            {
                return(LandMovement(agent, generalDirection, wandering, state, minDistance, maxDistance));
            }

            generalDirection = generalDirection == Vector2.zero ? Vector2.right.Rotate(RandomUtil.Range(0f, 360)) : generalDirection.Normalized;

            // Take random ground position in the given direction
            var targetGround = (agent.Position + (generalDirection * RandomUtil.Range(minDistance, maxDistance)).X_Z()).WorldPosition3i;

            // Floating animals will stick to water surface or land, non floating - land or return to swimming state
            if (World.World.IsUnderwater(targetGround) && agent.Species.FloatOnSurface)
            {
                targetGround.y = World.World.MaxWaterHeight[targetGround];
            }
            else
            {
                targetGround = RouteManager.NearestWalkableXYZ(targetGround, 5);
                if (!agent.Species.FloatOnSurface && !targetGround.IsValid)
                {
                    agent.Floating = false;
                    return(BTResult.Failure("Can't float, continue swimming"));
                }
            }

            // This is a low-effort search that includes water surface and should occasionally fail, just pick a semi-random node that was visited when it fails
            var routeProps = new RouteProperties()
            {
                MaxTargetLocationHeightDelta = agent.Species.ClimbHeight
            };
            var allowWaterSearch = new AStarSearch(RouteCacheData.NeighborsIncludeWater, agent.FacingDir, startPathPos, targetGround, 30, routeProps, false);

            if (allowWaterSearch.Status != SearchStatus.PathFound)
            {
                targetGround = allowWaterSearch.GroundNodes.Last().Key;
                allowWaterSearch.GetPathToWaterPos(targetGround);
            }

            // Apply land movement only for land positions
            if (!World.World.IsUnderwater(agent.Position.WorldPosition3i))
            {
                if (allowWaterSearch.GroundPath.Count < 2)
                {
                    return(LandMovement(agent, generalDirection, wandering, state, minDistance, maxDistance, skipRouteProperties: true));
                }
                if (allowWaterSearch.Status == SearchStatus.Unpathable && allowWaterSearch.GroundNodes.Count < RouteRegions.MinimumRegionSize)
                {
                    // Search region was unexpectedly small and agent is on land, might be trapped by player construction.
                    // Try regular land movement so region checks can apply & the agent can get unstuck (or die)
                    return(LandMovement(agent, generalDirection, wandering, state, minDistance, maxDistance));
                }
            }

            var smoothed = allowWaterSearch.LineOfSightSmoothWaterPosition(agent.GroundPosition);
            var route    = new Route(agent.Species.GetTraversalData(wandering), agent.FacingDir, smoothed);

            if (!route.IsValid)
            {
                route = Route.Basic(agent.Species.GetTraversalData(wandering), agent.FacingDir, agent.GroundPosition, route.EndPosition);
            }
            var routeTime = agent.SetRoute(route, state, null);

            return(routeTime < float.Epsilon ? BTResult.Failure("route not set") : BTResult.Success($"swimming path"));
        }
示例#17
0
        protected override bool PrivateUpdate(ScenarioFrame frame)
        {
            List <GameObject> objects = new List <GameObject>();

            int min = Minimum;
            int max = Maximum;

            AddStat("Minimum", min);
            AddStat("Maximum", max);

            foreach (Lot lot in ManagerLot.GetOwnedLots(Target))
            {
                foreach (GameObject obj in lot.GetObjects <GameObject>())
                {
                    if (!obj.IsStealable())
                    {
                        continue;
                    }

                    if (string.IsNullOrEmpty(obj.CatalogName))
                    {
                        continue;
                    }

                    if (obj.Value <= 0)
                    {
                        continue;
                    }

                    if (obj.Value < min)
                    {
                        continue;
                    }

                    if (obj.Value > max)
                    {
                        continue;
                    }

                    objects.Add(obj);
                }
            }

            if (objects.Count == 0)
            {
                return(false);
            }

            mFail = IsFail(Sim, Target);

            GameObject choice = RandomUtil.GetRandomObjectFromList(objects);

            mObjectName  = choice.CatalogName;
            mObjectValue = choice.Value;

            if (!mFail)
            {
                EventTracker.SendEvent(EventTypeId.kStoleObject, Sim.CreatedSim, choice);

                AddStat("Object Value", mObjectValue);

                if ((KeepObject) && (Sim.CreatedSim != null))
                {
                    if (!Inventories.TryToMove(choice, Sim.CreatedSim))
                    {
                        return(false);
                    }

                    choice.SetStealActors(Sim.CreatedSim, Target.CreatedSim);
                }
                else
                {
                    Money.AdjustFunds(Target, "Burgled", -mObjectValue);

                    Money.AdjustFunds(Sim, "Burgled", mObjectValue);
                }

                TraitFunctions.ItemStolenCallback(Target.Household, Origin.FromBurglar);

                foreach (Sim sim in HouseholdsEx.AllSims(Target.Household))
                {
                    EventTracker.SendEvent(EventTypeId.kWasRobbed, sim);
                }
            }

            if (OnInvestigateScenario != null)
            {
                OnInvestigateScenario(this, frame);
            }

            return(true);
        }
示例#18
0
        public static BTResult RouteToWater(Animal agent, bool wandering, AnimalState state)
        {
            var start = agent.Position.WorldPosition3i;

            // only works for surface start points
            if (World.World.IsUnderwater(start))
            {
                return(BTResult.Failure("Already underwater."));
            }
            if (start.y != World.World.MaxYCache[start])
            {
                return(BTResult.Failure("Not on world surface."));
            }
            if (RouteManager.RouteToSeaMap == null)
            {
                return(BTResult.Failure("Missing sea route map."));
            }

            if (start.IsValid)
            {
                agent.ChangeState(state, 0, false);

                // get a destination a decent
                var current = start;
                for (int i = 0; i < 10; i++)
                {
                    var next = RouteManager.RouteToSeaMap[current];
                    if (next == current)
                    {
                        break;
                    }
                    current = next;
                    if (WorldPosition3i.Distance(current, start) > 10)
                    {
                        break;
                    }
                }

                var target = ((Vector2)WorldPosition3i.GetDelta(current, start).XZ).Rotate(RandomUtil.Range(-20, 20));
                return(AmphibiousMovement(agent, target, wandering, state, 10, 20));
            }

            return(BTResult.Failure("Invalid start pos"));
        }
示例#19
0
        public override bool Run()
        {
            try
            {
                IWooHooDefinition definition = InteractionDefinition as IWooHooDefinition;

                if (WoohooObject == null)
                {
                    return(false);
                }

                if (!SafeToSync())
                {
                    return(false);
                }

                AllInOneBathroom.WoohooInAllInOneBathroomB entry = AllInOneBathroom.WoohooInAllInOneBathroomB.Singleton.CreateInstance(Actor, Target, GetPriority(), Autonomous, CancellableByPlayer) as AllInOneBathroom.WoohooInAllInOneBathroomB;
                entry.TryForBaby = TryForBaby;
                entry.LinkedInteractionInstance = this;
                Target.InteractionQueue.Add(entry);
                Actor.SynchronizationLevel  = Sim.SyncLevel.Started;
                Actor.SynchronizationTarget = Target;
                Actor.SynchronizationRole   = Sim.SyncRole.Initiator;
                if (!WoohooObject.SimLine.WaitForTurn(this, SimQueue.WaitBehavior.Default, ~(ExitReason.Replan | ExitReason.MidRoutePushRequested | ExitReason.ObjectStateChanged | ExitReason.PlayIdle | ExitReason.MaxSkillPointsReached), 10f))
                {
                    return(false);
                }

                if (!Actor.RouteToSlotAndCheckInUse(WoohooObject, Slot.RoutingSlot_1))
                {
                    return(false);
                }

                StandardEntry();
                WoohooObject.AddToUseList(Actor);
                WoohooObject.AddToUseList(Target);
                BeginCommodityUpdates();

                if (!Actor.WaitForSynchronizationLevelWithSim(Target, Sim.SyncLevel.Routed, 30f))
                {
                    WoohooObject.RemoveFromUseList(Actor);
                    WoohooObject.RemoveFromUseList(Target);
                    EndCommodityUpdates(false);
                    StandardExit();
                    return(false);
                }

                EnterStateMachine("AllInOneBathroom", "Enter", "x");
                SetActor("bathroom", WoohooObject);
                SetActor("y", Target);
                AddOneShotScriptEventHandler(0x64, AnimationCallback);
                AddOneShotScriptEventHandler(0x65, AnimationCallback);
                RockGemMetalBase.HandleNearbyWoohoo(Actor, RockGemMetalBase.HowMuchWooHoo.MoreWoohoo);

                if (mReactToSocialBroadcasterActor == null)
                {
                    mReactToSocialBroadcasterActor = new ReactionBroadcaster(Actor, Conversation.ReactToSocialParams, SocialComponentEx.ReactToJealousEventHigh);
                }

                if (mReactToSocialBroadcasterTarget == null)
                {
                    mReactToSocialBroadcasterTarget = new ReactionBroadcaster(Target, Conversation.ReactToSocialParams, SocialComponentEx.ReactToJealousEventHigh);
                }

                Animate("x", "WooHoo");

                List <Sim> exceptions = new List <Sim>();
                exceptions.Add(Target);
                WoohooObject.PushSimsFromFootprint(0x31229a4d, Actor, exceptions, true);
                WoohooObject.PushSimsFromFootprint(0x31229a4e, Actor, exceptions, true);
                Animate("x", "Exit");

                RockGemMetalBase.HandleNearbyWoohoo(Actor, RockGemMetalBase.HowMuchWooHoo.LessWoohoo);

                CommonWoohoo.RunPostWoohoo(Actor, Target, WoohooObject, definition.GetStyle(this), definition.GetLocation(WoohooObject), true);

                if (CommonPregnancy.IsSuccess(Actor, Target, Autonomous, definition.GetStyle(this)))
                {
                    Pregnancy pregnancy = CommonPregnancy.Impregnate(Actor, Target, Autonomous, definition.GetStyle(this));
                    if (pregnancy != null)
                    {
                        if (RandomUtil.RandomChance(AllInOneBathroom.kChanceOfHydrophobicTrait))
                        {
                            pregnancy.SetForcedBabyTrait(TraitNames.Hydrophobic);
                        }
                    }
                }

                WoohooObject.RemoveFromUseList(Actor);
                WoohooObject.RemoveFromUseList(Target);
                WoohooObject.SimLine.RemoveFromQueue(Actor);
                EndCommodityUpdates(true);
                StandardExit();

                EventTracker.SendEvent(EventTypeId.kWooHooInAllInOneBathroom, Actor, Target);

                VisitSituation situation  = VisitSituation.FindVisitSituationInvolvingGuest(Actor);
                VisitSituation situation2 = VisitSituation.FindVisitSituationInvolvingGuest(Target);
                if ((situation != null) && (situation2 != null))
                {
                    situation.GuestStartingInappropriateAction(Actor, 3.5f);
                    situation2.GuestStartingInappropriateAction(Target, 3.5f);
                }

                Relationship.Get(Actor, Target, true).LTR.UpdateLiking(AllInOneBathroom.kLTRGainFromWoohooInAllInOneBathroom);
                return(true);
            }
            catch (ResetException)
            {
                throw;
            }
            catch (Exception exception)
            {
                Common.Exception(Actor, Target, exception);
                return(false);
            }
        }
示例#20
0
        protected override bool OnPerform()
        {
            string msg = "OnPerform" + Common.NewLine;

            try
            {
                if ((TrafficManager.Singleton == null) || (LotManager.sLots == null))
                {
                    return(true);
                }

                Simulator.DestroyObject(TrafficManager.Singleton.mUpdateTrafficTask);
                TrafficManager.Singleton.mUpdateTrafficTask = ObjectGuid.InvalidObjectGuid;

                while (!TrafficManager.Enabled)
                {
                    FoodTruckManagerEx.Update();
                    SpeedTrap.Sleep((uint)SimClock.ConvertToTicks(RandomUtil.GetFloat(TrafficManager.kTrafficCheckTime[0x0], TrafficManager.kTrafficCheckTime[0x1]), TimeUnit.Hours));
                }

                msg += "A";

                List <Lot> list = new List <Lot>();
                foreach (Lot lot in LotManager.AllLots)
                {
                    if (lot.StreetParking == null)
                    {
                        continue;
                    }

                    if (lot.IsWorldLot)
                    {
                        continue;
                    }

                    list.Add(lot);
                }

                if (TrafficManager.GeneratedTrafficTuning.sLotTuning == null)
                {
                    return(true);
                }

                msg += "B";

                PairedListDictionary <Type, int> dictionary = new PairedListDictionary <Type, int>();
                foreach (Type type in TrafficManager.GeneratedTrafficTuning.sLotTuning.Keys)
                {
                    if (!TrafficManager.Enabled)
                    {
                        break;
                    }

                    int[] carRange = TrafficManager.GeneratedTrafficTuning.GetCarRange(type);
                    if (carRange == null)
                    {
                        continue;
                    }

                    if (Math.Max(carRange[0x0], carRange[0x1]) > 0x0)
                    {
                        msg += "C";

                        int numTaxis = RandomUtil.GetInt(carRange[0x0], carRange[0x1]);
                        foreach (Lot lot in list)
                        {
                            if (!TrafficManager.Enabled)
                            {
                                break;
                            }

                            int num2 = (int)Sims3.SimIFace.Queries.CountObjects(type, lot.LotId);
                            if (num2 > 0x0)
                            {
                                msg += "D";

                                PairedListDictionary <Type, int> dictionary2;
                                Type type2;
                                int  num3 = 0x0;
                                if (TrafficManager.sGeneratedCarCount != null)
                                {
                                    TrafficManager.sGeneratedCarCount.TryGetValue(type.ToString(), out num3);
                                }

                                msg += "E";

                                if (!dictionary.ContainsKey(type))
                                {
                                    dictionary.Add(type, 0x0);
                                }

                                msg += "F";

                                (dictionary2 = dictionary)[type2 = type] = dictionary2[type2] + num2;
                                if (num3 < (numTaxis * dictionary[type]))
                                {
                                    msg += "G";

                                    CarNpcWithNoDriver car = GlobalFunctions.CreateObjectOutOfWorld("CarTaxiLightweight", ProductVersion.EP3) as CarNpcWithNoDriver;
                                    if (car != null)
                                    {
                                        Matrix44 mat = new Matrix44();
                                        if (lot.StreetParking.GetParkingSpotForCar(car, ref mat))
                                        {
                                            msg += "H";

                                            Vector3[]    vectorArray;
                                            Quaternion[] quaternionArray;
                                            if (World.FindPlaceOnRoadOffScreen(car.Proxy, mat.pos.V3, FindPlaceOnRoadOption.Road, 100f, out vectorArray, out quaternionArray))
                                            {
                                                msg += "I";

                                                car.GeneratingClassName = type.ToString();
                                                car.PlaceAt(vectorArray[0x0], mat.at.V3, null);
                                                car.DriveAroundFor(RandomUtil.GetFloat(TrafficManager.kCarDriveAroundTimeRange[0x0], TrafficManager.kCarDriveAroundTimeRange[0x1]), TimeUnit.Hours);
                                            }
                                            else
                                            {
                                                car.Destroy();
                                            }

                                            msg += "J";

                                            lot.StreetParking.FreeParkingSpotForCar(car);
                                            SpeedTrap.Sleep((uint)RandomUtil.GetInt(TrafficManager.kAfterSpawnWaitTime[0x0], TrafficManager.kAfterSpawnWaitTime[0x1]));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                msg += "K";

                // Custom
                FoodTruckManagerEx.Update();

                msg += "L";

                uint tickCount = (uint)SimClock.ConvertToTicks(RandomUtil.GetFloat(TrafficManager.kTrafficCheckTime[0x0], TrafficManager.kTrafficCheckTime[0x1]), TimeUnit.Hours);
                SpeedTrap.Sleep(tickCount);
            }
            catch (Exception e)
            {
                Common.Exception(msg, e);
            }

            return(true);
        }
示例#21
0
 private void setNextHop()
 {
     State.NextHop  = new TimeSpan(0, 0, 0, 0, RandomUtil.RandomInt(1700, 3500));
     State.StartHop = DateTime.Now;
 }
示例#22
0
        public IMyVoxelFillProperties CreateRandom(int index, MaterialSelectionModel defaultMaterial, IEnumerable <MaterialSelectionModel> materialsCollection, IEnumerable <GenerateVoxelDetailModel> voxelCollection)
        {
            int idx;

            var randomModel = new AsteroidSeedFillProperties
            {
                Index           = index,
                MainMaterial    = defaultMaterial,
                FirstMaterial   = defaultMaterial,
                SecondMaterial  = defaultMaterial,
                ThirdMaterial   = defaultMaterial,
                FourthMaterial  = defaultMaterial,
                FifthMaterial   = defaultMaterial,
                SixthMaterial   = defaultMaterial,
                SeventhMaterial = defaultMaterial,
            };

            // Must be by reference, not value.
            var largeVoxelFileList = voxelCollection.Where(v => v.FileSize > 100000).ToList();
            var smallVoxelFileList = voxelCollection.Where(v => v.FileSize > 0 && v.FileSize < 100000).ToList();

            // Random Asteroid.
            var d       = RandomUtil.GetDouble(1, 100);
            var islarge = false;

            if (largeVoxelFileList.Count == 0 && smallVoxelFileList.Count == 0)
            {
                // no asteroids?  You are so screwed.
                throw new Exception("No valid asteroids found. Re-validate your game cache.");
            }

            if (largeVoxelFileList.Count == 0) // empty last list? Force to small list.
            {
                d = 1;
            }
            if (smallVoxelFileList.Count == 0) // empty small list? Force to large list.
            {
                d = 100;
            }

            if (d > 70)
            {
                idx = RandomUtil.GetInt(largeVoxelFileList.Count);
                randomModel.VoxelFile = largeVoxelFileList[idx];
                islarge = true;
            }
            else
            {
                idx = RandomUtil.GetInt(smallVoxelFileList.Count);
                randomModel.VoxelFile = smallVoxelFileList[idx];
            }

            // Random Main Material non-Rare.
            var nonRare = materialsCollection.Where(m => m.IsRare == false).ToArray();

            idx = RandomUtil.GetInt(nonRare.Length);
            randomModel.MainMaterial = nonRare[idx];

            int    chunks, chunkSize;
            double multiplier = 1.0;
            var    rare       = materialsCollection.Where(m => m.IsRare && m.MinedRatio >= 2).ToList();
            var    superRare  = materialsCollection.Where(m => m.IsRare && m.MinedRatio < 2).ToList();

            if (islarge)
            {
                // Random 1-4 are rare.
                chunks    = 20;
                chunkSize = 5;

                if (rare.Count > 0)
                {
                    idx = RandomUtil.GetInt(rare.Count);
                    randomModel.FirstMaterial = rare[idx];
                    randomModel.FirstVeins    = RandomUtil.GetInt((int)(chunks * multiplier), (int)(chunks * 1.5 * multiplier));
                    randomModel.FirstRadius   = RandomUtil.GetInt((int)(chunkSize * multiplier), (int)(chunkSize * 1.5 * multiplier));
                    rare.RemoveAt(idx);
                }
                multiplier *= 0.85;

                if (rare.Count > 0)
                {
                    idx = RandomUtil.GetInt(rare.Count);
                    randomModel.SecondMaterial = rare[idx];
                    randomModel.SecondVeins    = RandomUtil.GetInt((int)(chunks * multiplier), (int)(chunks * 1.5 * multiplier));
                    randomModel.SecondRadius   = RandomUtil.GetInt((int)(chunkSize * multiplier), (int)(chunkSize * 1.5 * multiplier));
                    rare.RemoveAt(idx);
                }
                multiplier *= 0.85;

                if (rare.Count > 0)
                {
                    idx = RandomUtil.GetInt(rare.Count);
                    randomModel.ThirdMaterial = rare[idx];
                    randomModel.ThirdVeins    = RandomUtil.GetInt((int)(chunks * multiplier), (int)(chunks * 1.5 * multiplier));
                    randomModel.ThirdRadius   = RandomUtil.GetInt((int)(chunkSize * multiplier), (int)(chunkSize * 1.5 * multiplier));
                    rare.RemoveAt(idx);
                }
                multiplier *= 0.85;

                if (rare.Count > 0)
                {
                    idx = RandomUtil.GetInt(rare.Count);
                    randomModel.FourthMaterial = rare[idx];
                    randomModel.FourthVeins    = RandomUtil.GetInt((int)(chunks * multiplier), (int)(chunks * 1.5 * multiplier));
                    randomModel.FourthRadius   = RandomUtil.GetInt((int)(chunkSize * multiplier), (int)(chunkSize * 1.5 * multiplier));
                    rare.RemoveAt(idx);
                }

                // Random 5-7 are super-rare

                multiplier = 1.0;
                chunks     = 50;
                chunkSize  = 2;

                if (superRare.Count > 0)
                {
                    idx = RandomUtil.GetInt(superRare.Count);
                    randomModel.FifthMaterial = superRare[idx];
                    randomModel.FifthVeins    = RandomUtil.GetInt((int)(chunks * multiplier), (int)(chunks * 1.5 * multiplier));
                    randomModel.FifthRadius   = RandomUtil.GetInt((int)(chunkSize * multiplier), (int)(chunkSize * 1.5 * multiplier));
                    superRare.RemoveAt(idx);
                }
                multiplier *= 0.5;

                if (superRare.Count > 0)
                {
                    idx = RandomUtil.GetInt(superRare.Count);
                    randomModel.SixthMaterial = superRare[idx];
                    randomModel.SixthVeins    = RandomUtil.GetInt((int)(chunks * multiplier), (int)(chunks * 1.5 * multiplier));
                    randomModel.SixthRadius   = RandomUtil.GetInt((int)(chunkSize * multiplier), (int)(chunkSize * 1.5 * multiplier));
                    superRare.RemoveAt(idx);
                }
                multiplier *= 0.5;

                if (superRare.Count > 0)
                {
                    idx = RandomUtil.GetInt(superRare.Count);
                    randomModel.SeventhMaterial = superRare[idx];
                    randomModel.SeventhVeins    = RandomUtil.GetInt((int)(chunks * multiplier), (int)(chunks * 1.5 * multiplier));
                    randomModel.SeventhRadius   = RandomUtil.GetInt((int)(chunkSize * multiplier), (int)(chunkSize * 1.5 * multiplier));
                    superRare.RemoveAt(idx);
                }
                multiplier *= 0.5;
            }
            else // Small Asteroid.
            {
                // Random 1-3 are rare.
                chunks    = 10;
                chunkSize = 2;

                if (rare.Count > 0)
                {
                    idx = RandomUtil.GetInt(rare.Count);
                    randomModel.FirstMaterial = rare[idx];
                    randomModel.FirstVeins    = RandomUtil.GetInt((int)(chunks * multiplier), (int)(chunks * 1.5 * multiplier));
                    randomModel.FirstRadius   = RandomUtil.GetInt((int)(chunkSize * multiplier), (int)(chunkSize * 1.5 * multiplier));
                    rare.RemoveAt(idx);
                }
                multiplier *= 0.75;

                if (rare.Count > 0)
                {
                    idx = RandomUtil.GetInt(rare.Count);
                    randomModel.SecondMaterial = rare[idx];
                    randomModel.SecondVeins    = RandomUtil.GetInt((int)(chunks * multiplier), (int)(chunks * 1.5 * multiplier));
                    randomModel.SecondRadius   = RandomUtil.GetInt((int)(chunkSize * multiplier), (int)(chunkSize * 1.5 * multiplier));
                    rare.RemoveAt(idx);
                }
                multiplier *= 0.75;

                if (rare.Count > 0)
                {
                    idx = RandomUtil.GetInt(rare.Count);
                    randomModel.ThirdMaterial = rare[idx];
                    randomModel.ThirdVeins    = RandomUtil.GetInt((int)(chunks * multiplier), (int)(chunks * 1.5 * multiplier));
                    randomModel.ThirdRadius   = RandomUtil.GetInt((int)(chunkSize * multiplier), (int)(chunkSize * 1.5 * multiplier));
                    rare.RemoveAt(idx);
                }


                // Random 4-5 is super-rare

                multiplier = 1.0;
                chunks     = 15;

                if (superRare.Count > 0)
                {
                    idx = RandomUtil.GetInt(superRare.Count);
                    randomModel.FourthMaterial = superRare[idx];
                    randomModel.FourthVeins    = RandomUtil.GetInt((int)(chunks * multiplier), (int)(chunks * 1.5 * multiplier));
                    randomModel.FourthRadius   = 0;
                    superRare.RemoveAt(idx);
                }
                multiplier *= 0.5;

                if (superRare.Count > 0)
                {
                    idx = RandomUtil.GetInt(superRare.Count);
                    randomModel.FifthMaterial = superRare[idx];
                    randomModel.FifthVeins    = RandomUtil.GetInt((int)(chunks * multiplier), (int)(chunks * 1.5 * multiplier));
                    randomModel.FifthRadius   = 0;
                    superRare.RemoveAt(idx);
                }
            }

            return(randomModel);
        }
示例#23
0
        public override bool Run()
        {
            try
            {
                StandardEntry();
                if (!Target.StartComputing(this, SurfaceHeight.Table, true))
                {
                    StandardExit();
                    return(false);
                }

                AnimateSim("GenericTyping");

                List <GameObject> broken     = new List <GameObject>();
                List <GameObject> repairable = new List <GameObject>();
                foreach (GameObject obj in Sims3.Gameplay.Queries.GetObjects <GameObject>())
                {
                    if (!obj.InWorld)
                    {
                        continue;
                    }

                    if (obj.InUse)
                    {
                        continue;
                    }

                    if (!obj.IsRepairable)
                    {
                        continue;
                    }

                    if (obj.InInventory)
                    {
                        continue;
                    }

                    if (obj.LotCurrent == Actor.LotHome)
                    {
                        continue;
                    }

                    if (obj.LotCurrent == null)
                    {
                        continue;
                    }

                    if (obj.LotCurrent.Household == null)
                    {
                        continue;
                    }

                    if (obj.IsInHiddenResidentialRoom)
                    {
                        continue;
                    }

                    RepairableComponent component = obj.Repairable;
                    if (component == null)
                    {
                        continue;
                    }

                    bool found = false;
                    foreach (Sim sim in obj.LotCurrent.Household.Sims)
                    {
                        if (!sim.SimDescription.TeenOrAbove)
                        {
                            continue;
                        }

                        if (sim.LotCurrent != obj.LotCurrent)
                        {
                            continue;
                        }

                        found = true;
                        break;
                    }

                    if ((found) && (component.Broken))
                    {
                        broken.Add(obj);
                    }
                    else
                    {
                        if (obj.LotCurrent == Actor.LotCurrent)
                        {
                            continue;
                        }

                        repairable.Add(obj);
                    }
                }

                GameObject choice = null;
                if (broken.Count > 0)
                {
                    choice = RandomUtil.GetRandomObjectFromList(broken);
                }
                else if (repairable.Count > 0)
                {
                    if (NRaas.Careers.Settings.mRepairAllowToBreak)
                    {
                        choice = RandomUtil.GetRandomObjectFromList(repairable);

                        if (!choice.Repairable.Broken)
                        {
                            choice.Repairable.BreakObject();
                        }
                    }
                    else
                    {
                        Common.Notify(Actor, Common.Localize("FindBroken:Failure", Actor.IsFemale));
                    }
                }

                if (choice != null)
                {
                    Camera.FocusOnGivenPosition(choice.Position, Camera.kDefaultLerpDuration);
                }

                Target.StopComputing(this, Computer.StopComputingAction.TurnOff, false);
                StandardExit();
            }
            catch (Exception exception)
            {
                Common.Exception(Actor, Target, exception);
            }
            return(true);
        }
示例#24
0
        public override void DoAction(IEventArgs args)
        {
            ItemDrop[] list = FreeItemDrop.GetDropItems(FreeUtil.ReplaceVar(cat, args), FreeUtil.ReplaceInt(count, args));

            if (list != null)
            {
                Vector3 p = UnityPositionUtil.ToVector3(pos.Select(args));
                foreach (ItemDrop drop in list)
                {
                    args.GameContext.session.entityFactoryObject.SceneObjectEntityFactory.
                    CreateSimpleEquipmentEntity((ECategory)drop.cat, drop.id, drop.count, new Vector3(p.x + RandomUtil.Random(-100, 100) / 100f, p.y, p.z + RandomUtil.Random(-100, 100) / 100f));
                }
            }
        }
示例#25
0
        protected override bool PrivateUpdate(ScenarioFrame frame)
        {
            if (mNewSim != null)
            {
                return(base.PrivateUpdate(frame));
            }

            if (GetValue <PetAdoptionScenario.UsePetPoolOption, bool>())
            {
                PetPoolType poolType = PetPoolType.None;
                switch (Species)
                {
                case CASAgeGenderFlags.Dog:
                case CASAgeGenderFlags.LittleDog:
                    poolType = PetPoolType.AdoptDog;
                    break;

                case CASAgeGenderFlags.Cat:
                    poolType = PetPoolType.AdoptCat;
                    break;

                case CASAgeGenderFlags.Horse:
                    poolType = PetPoolType.AdoptHorse;
                    break;
                }

                List <SimDescription> choices = PetPoolManager.GetPetsByType(poolType);
                if ((choices != null) && (choices.Count > 0))
                {
                    CASAgeGenderFlags ages = Ages;
                    for (int i = choices.Count - 1; i >= 0; i--)
                    {
                        if ((ages & choices[i].Age) != choices[i].Age)
                        {
                            choices.RemoveAt(i);
                        }
                        else if (choices[i].Species != Species)
                        {
                            choices.RemoveAt(i);
                        }
                    }

                    if (choices.Count == 0)
                    {
                        IncStat("No Matching In Pool");
                    }
                    else
                    {
                        mNewSim = RandomUtil.GetRandomObjectFromList(choices);

                        PetPoolManager.RemovePet(poolType, mNewSim, true);
                    }

                    return(base.PrivateUpdate(frame));
                }
                else
                {
                    IncStat("Pool Empty: " + poolType);
                }
            }

            if (Manager.GetValue <ScheduledImmigrationScenario.GaugeOption, int>() > 0)
            {
                return(base.PrivateUpdate(frame));
            }
            else
            {
                IncStat("Immigration Disabled");
                return(false);
            }
        }
示例#26
0
        public override bool Run()
        {
            EWCatFishingSkill skill = Actor.SkillManager.GetSkill <EWCatFishingSkill>(EWCatFishingSkill.SkillNameID);

            if (skill == null)
            {
                skill = (Actor.SkillManager.AddElement(EWCatFishingSkill.SkillNameID) as EWCatFishingSkill);
                if (skill == null)
                {
                    return(false);
                }
            }
            if (!DrinkFromPondHelper.RouteToDrinkLocation(Hit.mPoint, Actor, Hit.mType, Hit.mId))
            {
                return(false);
            }
            if (skill.OppFishercatCompleted)
            {
                skill.StartSkillGain(EWCatFishingSkill.kEWFishingSkillGainRateFishercat);
            }
            else
            {
                skill.StartSkillGain(EWCatFishingSkill.kEWFishingSkillGainRateNormal);
            }
            StandardEntry();
            EnterStateMachine("CatHuntInPond", "Enter", "x");
            AddOneShotScriptEventHandler(101u, (SacsEventHandler)(object)new SacsEventHandler(SnapOnExit));
            BeginCommodityUpdates();
            AnimateSim("PrePounceLoop");
            // TODO: If we don't have an opportunity for catching fish faster, we should
            bool flag = DoTimedLoop(RandomUtil.GetFloat(kMinMaxPrePounceTime[0], kMinMaxPrePounceTime[1]));

            if (flag)
            {
                EventTracker.SendEvent(EventTypeId.kGoFishingCat, Actor);
                AnimateSim("FishLoop");
                float successBonus = 0;
                if ((TerrainIsWaterPond && skill.OppPondProvisionerCompleted) ||
                    (!TerrainIsWaterPond && skill.OppSaltaholicCompleted))
                {
                    successBonus = EWCatFishingSkill.kFishCatchingBonus;
                }
                flag = RandomUtil.InterpolatedChance(0f, skill.MaxSkillLevel, kMinMaxSuccesChance[0] + successBonus,
                                                     kMinMaxSuccesChance[1] + successBonus, skill.SkillLevel);
                if (flag)
                {
                    FishType caughtFishType = GetCaughtFishType(Actor, Hit);
                    Fish     fish           = Fish.CreateFishOfRandomWeight(caughtFishType, Actor.SimDescription);

                    // Register will return a message if the fish is new or interesting
                    string message = skill.RegisterCaughtFish(fish, TerrainIsWaterPond);
                    if (fish.CatHuntingComponent != null)
                    {
                        fish.CatHuntingComponent.SetCatcher(Actor);
                    }
                    fish.UpdateVisualState(CatHuntingComponent.CatHuntingModelState.Carried);
                    SetActor("fish", fish);
                    if (Actor.Motives.GetValue(CommodityKind.Hunger) <= kEatFishHungerThreshold)
                    {
                        message += Localization.LocalizeString("Gameplay/Abstracts/ScriptObject/CatFishHere:EatFishTns",
                                                               Actor, fish.GetLocalizedName(), fish.Weight);
                        Actor.ShowTNSIfSelectable(message, NotificationStyle.kGameMessagePositive);
                        AnimateSim("ExitEat");
                        fish.Destroy();
                        Actor.Motives.ChangeValue(CommodityKind.Hunger, kHungerGainFromEating);
                    }
                    else
                    {
                        message += Localization.LocalizeString("Gameplay/Abstracts/ScriptObject/CatFishHere:PutFishInInventoryTns",
                                                               Actor, fish.GetLocalizedName(), fish.Weight);
                        Actor.ShowTNSIfSelectable(message, NotificationStyle.kGameMessagePositive);
                        AnimateSim("ExitInventory");
                        fish.UpdateVisualState(CatHuntingComponent.CatHuntingModelState.InInventory);
                        if (!Actor.Inventory.TryToAdd(fish))
                        {
                            fish.Destroy();
                        }
                    }
                }
                else
                {
                    Actor.ShowTNSIfSelectable(Localization.LocalizeString("Gameplay/Abstracts/ScriptObject/CatFishHere:FishFail",
                                                                          Actor.Name), NotificationStyle.kGameMessageNegative);
                    AnimateSim("ExitFailure");
                }
            }
            else
            {
                AnimateSim("ExitPrePounce");
            }
            EndCommodityUpdates(flag);
            StandardExit();
            skill.StopSkillGain();
            return(true);
        }
示例#27
0
        public override bool Run()
        {
            string msg = "Run" + Common.NewLine;

            try
            {
                StandardEntry();
                if (!Target.StartComputing(this, SurfaceHeight.Table, true))
                {
                    StandardExit();
                    return(false);
                }

                timeTillLearn = RandomUtil.RandomFloatGaussianDistribution(Target.ComputerTuning.ChatLearnSomethingFrequencyStart, Target.ComputerTuning.ChatLearnSomethingFrequencyEnd);
                Target.StartVideo(Computer.VideoType.Chat);
                if (CheckForCancelAndCleanup())
                {
                    Target.StopComputing(this, Computer.StopComputingAction.TurnOff, false);
                    return(false);
                }

                bool ignoreGender = RandomUtil.RandomChance(KamaSimtra.Settings.mCyberWoohooChanceOfMisunderstanding);

                simToChat = GetSelectedObject() as Sim;
                if (simToChat == null)
                {
                    //msg += Common.NewLine + "CyberWoohoo";

                    List <Sim> unknown = new List <Sim>();
                    List <Sim> known   = new List <Sim>();
                    GetPotentials(Actor, Target, Autonomous, ignoreGender, unknown, known);

                    //Common.DebugStackLog(msg);

                    if ((unknown.Count > 0x0) && Actor.IsSelectable)
                    {
                        simToChat = RandomUtil.GetRandomObjectFromList(unknown);
                    }
                    else if (known.Count > 0x0)
                    {
                        simToChat = RandomUtil.GetRandomObjectFromList(known);
                    }
                }

                bool succeeded = false;
                if (simToChat == null)
                {
                    Actor.ShowTNSIfSelectable(Common.Localize("CyberWoohoo:NoOne", Actor.IsFemale), StyledNotification.NotificationStyle.kSimTalking);
                }
                else
                {
                    Common.DebugNotify("CyberWoohoo: " + simToChat.FullName, Actor);

                    BeginCommodityUpdates();
                    AnimateSim("GenericTyping");
                    succeeded = DoLoop(~(ExitReason.Replan | ExitReason.MidRoutePushRequested | ExitReason.ObjectStateChanged | ExitReason.PlayIdle | ExitReason.MaxSkillPointsReached), LoopDel, null);
                    EndCommodityUpdates(succeeded);

                    if (Woohooer.Settings.mApplyBuffs)
                    {
                        if (mClimaxChances <= 2)
                        {
                            Actor.BuffManager.AddElement(KamaSimtra.sPremature, WoohooBuffs.sWoohooOrigin);
                        }

                        int score = ScoringLookup.GetScore("LikeCyberWoohoo", Actor.SimDescription) + KamaSimtra.Settings.mCyberWoohooBaseChanceScoring;
                        if (score > 0)
                        {
                            Actor.BuffManager.RemoveElement(KamaSimtra.sDislikeCyberWoohoo);
                            Actor.BuffManager.AddElement(KamaSimtra.sLikeCyberWoohoo, WoohooBuffs.sWoohooOrigin);
                        }
                        else if (score < 0)
                        {
                            Actor.BuffManager.RemoveElement(KamaSimtra.sLikeCyberWoohoo);
                            Actor.BuffManager.AddElement(KamaSimtra.sDislikeCyberWoohoo, WoohooBuffs.sWoohooOrigin);
                        }
                    }
                }

                Target.StopComputing(this, Computer.StopComputingAction.TurnOff, false);
                StandardExit();
                return(succeeded);
            }
            catch (ResetException)
            {
                throw;
            }
            catch (Exception e)
            {
                Common.Exception(Actor, Target, msg, e);
                return(false);
            }
        }
示例#28
0
        public override bool Run()
        {
            try
            {
                if (!Target.RouteToCone(Actor))
                {
                    return(false);
                }

                StandardEntry();

                try
                {
                    BeginCommodityUpdates();
                    if (((Target.mJobSelectionDay.Ticks == 0x0L) || (SimClock.CurrentDayOfWeek != Target.mJobSelectionDay.DayOfWeek)) || (SimClock.ElapsedTime(TimeUnit.Days, Target.mJobSelectionDay) >= 1f))
                    {
                        Target.mAvailableJobs.Clear();
                        Target.mTakenJobs.Clear();
                        Target.mJobSelectionDay = SimClock.CurrentTime();
                        Target.StartTimer();
                    }

                    if (GameUtils.IsUniversityWorld())
                    {
                        EnterStateMachine("JobBoard", "Enter", "x");
                        SetActor("jobBoard", Target);
                        AnimateSim("Exit");
                    }
                    else
                    {
                        Actor.PlaySoloAnimation("a2o_postBoxJobBoard_checkBoard_x", true);
                    }

                    EndCommodityUpdates(true);

                    Definition definition = InteractionDefinition as Definition;

                    Tutorialette.TriggerLesson(Lessons.QuestTracker, Actor);
                    if (Autonomous || !UIUtils.IsOkayToStartModalDialog())
                    {
                        Actor.Wander(kMinWanderDistance, kMaxWanderDistance, false, RouteDistancePreference.NoPreference, false);
                    }
                    else
                    {
                        OpportunityNames choice = OpportunityNames.Undefined;
                        if (Target.mTakenJobs.Count >= kOpportunitiesPerDay)
                        {
                            string msg = "JobBoardEmptyTNS";
                            if (GameUtils.IsUniversityWorld())
                            {
                                msg = "JobBoardEmptyTNSEP9";
                            }

                            Actor.ShowTNSIfSelectable(LocalizeString(Actor.IsFemale, msg, new object[0x0]), StyledNotification.NotificationStyle.kSimTalking);
                        }
                        else
                        {
                            if ((Target.mAvailableJobs.Count + Target.mTakenJobs.Count) < kOpportunitiesPerDay)
                            {
                                List <Opportunity> opportunities = OpportunityEx.GetAllOpportunities(Actor, definition.mOppName);

                                List <float> weights = new List <float>();
                                foreach (Opportunity opp in opportunities)
                                {
                                    float num = Actor.SimDescription.OpportunityHistory.HasRejectedOpportunity(opp.Guid) ? OpportunityHistory.kUserRejectedOpportunityWeightMultiplier : 1f;
                                    weights.Add(opp.ChanceToGetOnPhone * num);
                                }

                                Opportunity opportunity = null;
                                while (opportunities.Count > 0)
                                {
                                    int index = RandomUtil.GetWeightedIndex(weights.ToArray());

                                    opportunity = opportunities[index];

                                    weights.RemoveAt(index);
                                    opportunities.RemoveAt(index);

                                    if (!Target.mAvailableJobs.Contains(opportunity.Guid))
                                    {
                                        Target.mAvailableJobs.Add(opportunity.Guid);
                                        Target.mIndexOfLastChosen = Target.mAvailableJobs.Count - 0x1;

                                        if (!OpportunityEx.Perform(Actor.SimDescription, opportunity.Guid))
                                        {
                                            return(false);
                                        }

                                        choice = opportunity.Guid;
                                        break;
                                    }
                                }

                                if (choice == OpportunityNames.Undefined)
                                {
                                    Actor.ShowTNSIfSelectable(LocalizeString(Actor.IsFemale, "NoValidOppsTNS", new object[] { Actor }), StyledNotification.NotificationStyle.kGameMessagePositive, Target.ObjectId, Actor.ObjectId);
                                    return(false);
                                }
                            }
                            else
                            {
                                choice = OpportunityNames.Undefined;
                                int count = Target.mAvailableJobs.Count;
                                if (count > 0x0)
                                {
                                    int num2 = (Target.mIndexOfLastChosen + 0x1) % count;
                                    for (int i = 0x0; i < Target.mAvailableJobs.Count; i++)
                                    {
                                        int num4 = (i + num2) % count;
                                        OpportunityNames names3 = Target.mAvailableJobs[num4];
                                        if ((Actor.OpportunityManager.IsOpportunityAvailable(names3)) && (Actor.OpportunityManager.IsOpportunityCategory(names3, definition.mOppName)))
                                        {
                                            choice = names3;
                                            Target.mIndexOfLastChosen = num4;
                                            break;
                                        }
                                    }
                                }

                                if (choice != OpportunityNames.Undefined)
                                {
                                    if (!OpportunityEx.Perform(Actor.SimDescription, choice))
                                    {
                                        return(false);
                                    }
                                }
                                else
                                {
                                    Actor.ShowTNSIfSelectable(LocalizeString(Actor.IsFemale, "NoValidOppsTNS", new object[] { Actor }), StyledNotification.NotificationStyle.kGameMessagePositive, Target.ObjectId, Actor.ObjectId);
                                }
                            }

                            if (choice != OpportunityNames.Undefined)
                            {
                                Target.mIndexOfLastChosen = 0x0;
                                Target.mAvailableJobs.Remove(choice);
                                Target.mTakenJobs.Add(choice);
                                if (Target.mTakenJobs.Count >= kOpportunitiesPerDay)
                                {
                                    Target.StopHelperEffect();
                                }
                            }
                        }
                    }
                }
                finally
                {
                    StandardExit();
                }

                return(true);
            }
            catch (ResetException)
            {
                throw;
            }
            catch (Exception e)
            {
                Common.Exception(Actor, Target, e);
                return(false);
            }
        }
示例#29
0
        protected override bool PrivateUpdate(ScenarioFrame frame)
        {
            base.PrivateUpdate(frame);

            if (sSkills == null)
            {
                sSkills = new Dictionary <Sims3.Gameplay.Skills.SkillNames, InteractionDefinition>();

                sSkills.Add(Sims3.Gameplay.Skills.SkillNames.Guitar, GuitarPlayForTips.Singleton);
                sSkills.Add(Sims3.Gameplay.Skills.SkillNames.BassGuitar, BassGuitarPlayForTips.Singleton);
                sSkills.Add(Sims3.Gameplay.Skills.SkillNames.Piano, PianoPlayForTips.Singleton);
                sSkills.Add(Sims3.Gameplay.Skills.SkillNames.Drums, DrumsPlayForTips.Singleton);
                sSkills.Add(Sims3.Gameplay.Skills.SkillNames.LaserHarp, LaserHarpPlayForTips.Singleton);
            }

            List <Sims3.Gameplay.Skills.SkillNames> choices = new List <Sims3.Gameplay.Skills.SkillNames>();

            SimData data = Options.GetSim(Sim);

            foreach (Sims3.Gameplay.Skills.SkillNames skill in sSkills.Keys)
            {
                if (!Skills.AllowSkill(this, Sim, data, skill))
                {
                    continue;
                }

                choices.Add(skill);
            }

            if (choices.Count == 0)
            {
                IncStat("No Choices");
                return(false);
            }

            BandInstrument        instrument = null;
            InteractionDefinition definition = null;

            RandomUtil.RandomizeListOfObjects(choices);

            foreach (Sims3.Gameplay.Skills.SkillNames skill in choices)
            {
                switch (skill)
                {
                case Sims3.Gameplay.Skills.SkillNames.Guitar:
                    instrument = Inventories.InventoryFind <Guitar>(Sim);
                    if (instrument == null)
                    {
                        instrument = ManagedBuyProduct <Guitar> .Purchase(Sim, 0, this, UnlocalizedName, null, BuildBuyProduct.eBuyCategory.kBuyCategoryElectronics, BuildBuyProduct.eBuySubCategory.kBuySubCategoryHobbiesAndSkills);
                    }
                    break;

                case Sims3.Gameplay.Skills.SkillNames.BassGuitar:
                    instrument = Inventories.InventoryFind <BassGuitar>(Sim);
                    if (instrument == null)
                    {
                        instrument = ManagedBuyProduct <BassGuitar> .Purchase(Sim, 0, this, UnlocalizedName, null, BuildBuyProduct.eBuyCategory.kBuyCategoryElectronics, BuildBuyProduct.eBuySubCategory.kBuySubCategoryHobbiesAndSkills);
                    }
                    break;

                case Sims3.Gameplay.Skills.SkillNames.Piano:
                    instrument = Inventories.InventoryFind <Piano>(Sim);
                    if (instrument == null)
                    {
                        instrument = ManagedBuyProduct <Piano> .Purchase(Sim, 0, this, UnlocalizedName, null, BuildBuyProduct.eBuyCategory.kBuyCategoryElectronics, BuildBuyProduct.eBuySubCategory.kBuySubCategoryHobbiesAndSkills);
                    }
                    break;

                case Sims3.Gameplay.Skills.SkillNames.Drums:
                    instrument = Inventories.InventoryFind <Drums>(Sim);
                    if (instrument == null)
                    {
                        instrument = ManagedBuyProduct <Drums> .Purchase(Sim, 0, this, UnlocalizedName, null, BuildBuyProduct.eBuyCategory.kBuyCategoryElectronics, BuildBuyProduct.eBuySubCategory.kBuySubCategoryHobbiesAndSkills);
                    }
                    break;

                case Sims3.Gameplay.Skills.SkillNames.LaserHarp:
                    instrument = Inventories.InventoryFind <LaserHarp>(Sim);
                    if (instrument == null)
                    {
                        instrument = ManagedBuyProduct <LaserHarp> .Purchase(Sim, 0, this, UnlocalizedName, null, BuildBuyProduct.eBuyCategory.kBuyCategoryElectronics, BuildBuyProduct.eBuySubCategory.kBuySubCategoryHobbiesAndSkills);
                    }
                    break;
                }

                if (instrument != null)
                {
                    definition = sSkills[skill];
                    break;
                }
            }

            if (instrument == null)
            {
                IncStat("No Instrument");
                return(false);
            }

            Lot lot = Sim.CreatedSim.LotCurrent;

            if ((Sim.LotHome == lot) || (lot.IsWorldLot) || (lot.IsResidentialLot))
            {
                if (!Situations.PushVisit(this, Sim, Lots.GetCommunityLot(Sim.CreatedSim, null, true)))
                {
                    IncStat("Push Lot Fail");
                    return(false);
                }
            }

            return(Situations.PushInteraction(this, Sim, instrument, definition));
        }
示例#30
0
 public override void DoAction(IEventArgs args)
 {
     RandomUtil.SetSeed(FreeUtil.ReplaceInt(seed, args));
 }