public ChunkRunner() { Singleton <PropertyManager> .Instance.AddRootContext(this); m_raycastMask = 1 << LayerMask.NameToLayer("Blocks"); SceneLoader instance = SceneLoader.Instance; BindingManager bind = BindingManager.Instance; ShowNotification = (from _ in BlocksClearTriggered select true).TakeUntilDestroy(instance).ToSequentialReadOnlyReactiveProperty(); BlocksAmount = (from amount in AllBlockAmount select(!(BossBlock.Value == null)) ? Mathf.Max(0, amount - 1) : amount).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty(); (from custom in CustomLevel where custom select custom).Subscribe(delegate { bind.CustomLevelNode.SetActive(value: true); }).AddTo(instance); (from custom in CustomLevel.Pairwise() where !custom.Current && custom.Previous select custom).Subscribe(delegate { bind.CustomLevelNode.SetActive(value: false); bind.CustomLevelFinishedNode.SetActive(value: true); }).AddTo(instance); (from custom in CustomLevel.Pairwise() where !custom.Current && !custom.Previous select custom).Subscribe(delegate { bind.CustomLevelNode.SetActive(value: false); bind.CustomLevelFinishedNode.SetActive(value: false); }).AddTo(instance); ChunkProgress = CurrentChunkHealth.CombineLatest(ChunkMaxHealth, (BigDouble curr, BigDouble max) => (curr / max).ToFloat()).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty(); ChunkHealthText = CurrentChunkHealth.CombineLatest(ChunkMaxHealth, (BigDouble curr, BigDouble max) => BigString.ToString(curr) + " / " + BigString.ToString(max)).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty(); }
public StopWatchModel() { Debug.WriteLine("StopWatchModel ctor"); IsRunning = _isRunning.ToReadOnlyReactiveProperty(eventScheduler: Scheduler.Default); IsVisibleMillis = _isVisibleMillis; _timeFormat = IsVisibleMillis .Select(v => v ? @"mm\:ss\.fff" : @"mm\:ss") .ToReactiveProperty(raiseEventScheduler: Scheduler.Default); FormattedTime = _time.CombineLatest(_timeFormat, (time, format) => TimeSpan.FromMilliseconds(time).ToString(format)) .ToReadOnlyReactiveProperty(eventScheduler: Scheduler.Default); FormattedLaps = _laps.CombineLatest(_timeFormat, (laps, f) => laps.Select((x, i) => TimeSpan.FromMilliseconds(x).ToString(f))) .ToReadOnlyReactiveProperty(eventScheduler: Scheduler.Default); FormattedFastestLap = _laps.CombineLatest(_timeFormat, (laps, format) => { var fastest = laps.Count > 0 ? laps.Min() : 0; return(TimeSpan.FromMilliseconds(fastest).ToString(format)); }) .ToReadOnlyReactiveProperty(eventScheduler: Scheduler.Default); FormattedWorstLap = _laps.CombineLatest(_timeFormat, (laps, format) => { var worst = laps.Count > 0 ? laps.Max() : 0; return(TimeSpan.FromMilliseconds(worst).ToString(format)); }) .ToReadOnlyReactiveProperty(eventScheduler: Scheduler.Default); }
/// <summary> /// プロパティ初期化 /// </summary> private void InitializeProperty() { Cell_1_1 = _board.Cells[0, 0].ObserveProperty(n => n.TypeString).ToReactiveProperty(); Cell_1_2 = _board.Cells[0, 1].ObserveProperty(n => n.TypeString).ToReactiveProperty(); Cell_1_3 = _board.Cells[0, 2].ObserveProperty(n => n.TypeString).ToReactiveProperty(); Cell_2_1 = _board.Cells[1, 0].ObserveProperty(n => n.TypeString).ToReactiveProperty(); Cell_2_2 = _board.Cells[1, 1].ObserveProperty(n => n.TypeString).ToReactiveProperty(); Cell_2_3 = _board.Cells[1, 2].ObserveProperty(n => n.TypeString).ToReactiveProperty(); Cell_3_1 = _board.Cells[2, 0].ObserveProperty(n => n.TypeString).ToReactiveProperty(); Cell_3_2 = _board.Cells[2, 1].ObserveProperty(n => n.TypeString).ToReactiveProperty(); Cell_3_3 = _board.Cells[2, 2].ObserveProperty(n => n.TypeString).ToReactiveProperty(); Cell_1_1_Background = _board.Cells[0, 0].ObserveProperty(n => n.Background).ToReactiveProperty(); Cell_1_1_Foreground = _board.Cells[0, 0].ObserveProperty(n => n.Foreground).ToReactiveProperty(); Cell_1_2_Background = _board.Cells[0, 1].ObserveProperty(n => n.Background).ToReactiveProperty(); Cell_1_2_Foreground = _board.Cells[0, 1].ObserveProperty(n => n.Foreground).ToReactiveProperty(); Cell_1_3_Background = _board.Cells[0, 2].ObserveProperty(n => n.Background).ToReactiveProperty(); Cell_1_3_Foreground = _board.Cells[0, 2].ObserveProperty(n => n.Foreground).ToReactiveProperty(); Cell_2_1_Background = _board.Cells[1, 0].ObserveProperty(n => n.Background).ToReactiveProperty(); Cell_2_1_Foreground = _board.Cells[1, 0].ObserveProperty(n => n.Foreground).ToReactiveProperty(); Cell_2_2_Background = _board.Cells[1, 1].ObserveProperty(n => n.Background).ToReactiveProperty(); Cell_2_2_Foreground = _board.Cells[1, 1].ObserveProperty(n => n.Foreground).ToReactiveProperty(); Cell_2_3_Background = _board.Cells[1, 2].ObserveProperty(n => n.Background).ToReactiveProperty(); Cell_2_3_Foreground = _board.Cells[1, 2].ObserveProperty(n => n.Foreground).ToReactiveProperty(); Cell_3_1_Background = _board.Cells[2, 0].ObserveProperty(n => n.Background).ToReactiveProperty(); Cell_3_1_Foreground = _board.Cells[2, 0].ObserveProperty(n => n.Foreground).ToReactiveProperty(); Cell_3_2_Background = _board.Cells[2, 1].ObserveProperty(n => n.Background).ToReactiveProperty(); Cell_3_2_Foreground = _board.Cells[2, 1].ObserveProperty(n => n.Foreground).ToReactiveProperty(); Cell_3_3_Background = _board.Cells[2, 2].ObserveProperty(n => n.Background).ToReactiveProperty(); Cell_3_3_Foreground = _board.Cells[2, 2].ObserveProperty(n => n.Foreground).ToReactiveProperty(); IsFirstPlayer = new ReactiveProperty <bool>(true); IsDispWaitingImg = new ReactiveProperty <bool>(false); IsWinPlayer1 = _player1.ObserveProperty(p => p.IsWin).ToReactiveProperty(); IsWinPlayer2 = _player2.ObserveProperty(p => p.IsWin).ToReactiveProperty(); IsSettled = IsWinPlayer1.CombineLatest(IsWinPlayer2, (x, y) => x || y).ToReadOnlyReactiveProperty(); IsSettledCL = _board.ObserveProperty(n => n.SettledPattern).Select(n => n == SettledPattern.CrossLeft).ToReactiveProperty(); IsSettledCR = _board.ObserveProperty(n => n.SettledPattern).Select(n => n == SettledPattern.CrossRight).ToReactiveProperty(); IsSettledVL = _board.ObserveProperty(n => n.SettledPattern).Select(n => n == SettledPattern.VerticalLeft).ToReactiveProperty(); IsSettledVC = _board.ObserveProperty(n => n.SettledPattern).Select(n => n == SettledPattern.VerticalCenter).ToReactiveProperty(); IsSettledVR = _board.ObserveProperty(n => n.SettledPattern).Select(n => n == SettledPattern.VerticalRight).ToReactiveProperty(); IsSettledHT = _board.ObserveProperty(n => n.SettledPattern).Select(n => n == SettledPattern.HorizontalTop).ToReactiveProperty(); IsSettledHM = _board.ObserveProperty(n => n.SettledPattern).Select(n => n == SettledPattern.HorizontalMiddle).ToReactiveProperty(); IsSettledHB = _board.ObserveProperty(n => n.SettledPattern).Select(n => n == SettledPattern.HorizontalBottom).ToReactiveProperty(); IsYouWin = IsFirstPlayer.CombineLatest(IsWinPlayer1, (x, y) => x ? y : !y).CombineLatest(IsSettled, (x, y) => x && y).Delay(TimeSpan.FromSeconds(1)).ToReactiveProperty(); IsYouLose = IsFirstPlayer.CombineLatest(IsWinPlayer2, (x, y) => x ? y : !y).CombineLatest(IsSettled, (x, y) => x && y).Delay(TimeSpan.FromSeconds(1)).ToReactiveProperty(); IsDraw = new ReactiveProperty <bool>(false); }
public DownloadStatus() { Bytes = new ReactiveProperty <long>(); TotalBytes = new ReactiveProperty <long>(); Progress = Bytes.CombineLatest(TotalBytes, (b, t) => t > 0 ? (double)b / (double)t : 0.0) .ToReadOnlyReactiveProperty(); Weight = new ReactiveProperty <double>(); IsActive = new ReactiveProperty <bool>(); Description = new ReactiveProperty <string>(); IsIdle = new ReactiveProperty <bool>(); IsActive.Subscribe(_ => { _downloadSpeedCalculator.Restart(DateTime.Now); }); var timedBytes = Bytes.Select(b => new ByteSample { Bytes = b, Timestamp = DateTime.Now }); var interval = Observable .Interval(TimeSpan.FromSeconds(1)) .Select(_ => new ByteSample { Bytes = Bytes.Value, Timestamp = DateTime.Now }); var updateStream = timedBytes.Merge(interval); BytesPerSecond = updateStream .Select(b => _downloadSpeedCalculator.Calculate(b.Bytes, b.Timestamp)) .ToReadOnlyReactiveProperty(); }
public void PostInit() { SceneLoader instance = SceneLoader.Instance; DrillAdCooldown = (from _ in TickerService.MasterTicksSlow select(float) Singleton <AdRunner> .Instance.GetNextTimeToShowAd(AdPlacement.Drill).TotalSeconds into secsLeft select(int) Mathf.Max(0f, secsLeft)).DistinctUntilChanged().TakeUntilDestroy(instance).ToReactiveProperty(); DrillAdAvailable = (from avail in DrillAdCooldown.CombineLatest(PlayerData.Instance.DrillLevel, (int cd, int lvl) => cd <= 0 && lvl < m_maxDrillAds) select(avail)).CombineLatest(Singleton <AdRunner> .Instance.AdReady, (bool time, bool ad) => time && ad).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty(); DrillAdCooldownLeft = DrillAdCooldown.Select(delegate(int seconds) { string empty = string.Empty; return((seconds > 0) ? TextUtils.FormatSecondsShort(seconds) : PersistentSingleton <LocalizationService> .Instance.Text("AD.Placement.NotAvailable")); }).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty(); (from ad in Singleton <AdRunner> .Instance.AdPlacementFinished where ad == AdPlacement.Drill select ad).Subscribe(delegate { DrillAdFinished(); }).AddTo(instance); (from ad in Singleton <AdRunner> .Instance.AdPlacementSkipped where ad == AdPlacement.Drill select ad).Subscribe(delegate { DrillAdSkipped(); }).AddTo(instance); (from ad in Singleton <AdRunner> .Instance.AdPlacementFailed where ad == AdPlacement.Drill select ad).Subscribe(delegate { DrillAdSkipped(); }).AddTo(instance); }
public LogicNode(ILogicNode parentNode, string name) { Parent = parentNode; Name = name; _completeFactor = _ownFactor.CombineLatest(parentNode.CompleteFactor, (own, parent) => own * parent).ToReactiveProperty(); }
public HammerTimeRunner() { Singleton <PropertyManager> .Instance.AddRootContext(this); SceneLoader instance = SceneLoader.Instance; ReactiveProperty <int> reactiveProperty = (from dur in PlayerData.Instance.BoostersEffect[5] select(int) dur + PersistentSingleton <GameSettings> .Instance.GoldenHammerInitialDuration).TakeUntilDestroy(instance).ToReactiveProperty(); ReactiveProperty <int> right = reactiveProperty.CombineLatest(PlayerData.Instance.HammerTimeBonusDuration, (int dura, int bonus) => dura + bonus).TakeUntilDestroy(instance).ToReactiveProperty(); TickerService.MasterTicks.Subscribe(delegate(long ticks) { if (PlayerData.Instance.HammerTimeElapsedTime.Value < 1728000000000L) { PlayerData.Instance.HammerTimeElapsedTime.Value += ticks; } }).AddTo(instance); UniRx.IObservable <int> source = PlayerData.Instance.HammerTimeElapsedTime.CombineLatest(right, (long ticks, int dur) => dur - (int)(ticks / 10000000)); Active = (from secs in source select secs > 0).TakeUntilDestroy(instance).ToReactiveProperty(); DurationLeft = (from seconds in source select TextUtils.FormatSecondsShort(seconds)).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty(); DurationString = (from dur in reactiveProperty select PersistentSingleton <LocalizationService> .Instance.Text("Attribute.Duration") + ": " + BoosterCollectionRunner.FormatSecondsForBoosters(dur)).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty(); HammerTimeEnded = (from act in Active select act && (HammerTimeActive = true) into sit select(!sit && HammerTimeActive) ? true : false).TakeUntilDestroy(instance).ToReactiveProperty(); (from elapsed in PlayerData.Instance.HammerTimeElapsedTime where elapsed < 0 select elapsed).CombineLatest(right, (long cheat, int dur) => dur).Subscribe(delegate(int dur) { PlayerData.Instance.HammerTimeElapsedTime.Value = dur; }).AddTo(instance); }
public Person(string givenName, string familyName) { GivenName = new ReactiveProperty <string>(givenName); FamilyName = new ReactiveProperty <string>(familyName); // If change the givenName or familyName, notify with fullName! FullName = GivenName.CombineLatest(FamilyName, (x, y) => x + " " + y).ToReadOnlyReactiveProperty(); }
/// <summary> /// /// </summary> /// <param name="manager"></param> public MainWindowViewModel(ApplicationManager manager) { _manager = manager; _manager.Error += manager_Error; _applications = _manager.Applications.ToSyncedSynchronizationContextCollection(x => new ApplicationViewModel(_manager, x), SynchronizationContext.Current); IsSettingsOpen = new ReactiveProperty <bool>(false); IsDetailsOpen = new ReactiveProperty <bool>(false); IsProgressActive = new ReactiveProperty <bool>(false); ShowWindowRightCommands = IsSettingsOpen.CombineLatest(IsDetailsOpen, (a, b) => !a && !b) .ToReactiveProperty(); InitialDirectory = _manager.Settings.ToReactivePropertyAsSynchronized(x => x.ApplicationRootDirectoryPath); ShowHelpCommand = new ReactiveCommand(); ShowHelpCommand.Subscribe(_ => ShowHelp()); RegisterApplicationCommand = IsProgressActive.Select(x => !x).ToReactiveCommand(); RegisterApplicationCommand.Subscribe(_ => RegisterApplication()); InstallApplicationCommand = IsProgressActive.Select(x => !x).ToReactiveCommand(); InstallApplicationCommand.Subscribe(_ => InstallApplication()); OpenSettingCommand = new ReactiveCommand(); OpenSettingCommand.Subscribe(_ => ShowSettings()); ShowDetailsCommand = new ReactiveCommand <ApplicationViewModel>(); ShowDetailsCommand.Subscribe(ShowDetails); CurrentItem = new ReactiveProperty <ApplicationViewModel>(); SettingsViewModel = new ReactiveProperty <SettingsViewModel>(); }
public CommandLocker() { CanExecute = new ReactiveProperty <bool>(true); canExcuteWithTrigger = new ReactiveProperty <bool>(true); CanExecuteWithTrigger = CanExecute .CombineLatest(canExcuteWithTrigger, (a, b) => a && b) .ToReactiveProperty(); }
public Program(ProgramTemplate template) { Template = template; CurrentVersion = new ReactiveProperty <ProgramVersion>(template.Versions[0]); InstalledPatches = new ReactiveCollection <PatchTemplate>(); MemorySize = CurrentVersion.CombineLatest(InstalledPatches.ObserveCountChanged(true), (version, _) => version.MemorySize + InstalledPatches.Sum(patch => patch.SizeDelta)).ToReactiveProperty(); Name = CurrentVersion.CombineLatest(InstalledPatches.ObserveCountChanged(true), (_, patchesCount) => GetName(GetCurrentVersionIndex(), patchesCount)).ToReactiveProperty(); LeakBytesPerSecond = CurrentVersion.CombineLatest(InstalledPatches.ObserveCountChanged(true), (version, _) => version.LeakBytesPerSecond + InstalledPatches.Sum(patch => patch.LeakDelta)).ToReactiveProperty(); ProduceBytesPerSecond = CurrentVersion.Select(x => x.ProduceBytesPerSecond).ToReactiveProperty(); }
public ShoppingCartItemViewModel(ShoppingItemModel source, int count, IShoppingCartService shoppingCartService, INavigationService navigationService) : base(source, navigationService) { _shoppingCartService = shoppingCartService; Count = new ReactiveProperty <int>(count); CountAndPriceLabel = Count.CombineLatest(PriceLabel, (cnt, pce) => $"{cnt}x @ {pce} ea.").ToReadOnlyReactiveProperty(); RemoveCommand = new ReactiveCommand(); _removeSubscription = RemoveCommand.Subscribe(RemoveItem); }
public GearViewRunner(int gearIndex) { SceneLoader instance = SceneLoader.Instance; GearConfig config = PersistentSingleton <Economies> .Instance.Gears[gearIndex]; LocalizedName = new ReactiveProperty <string>(PersistentSingleton <LocalizationService> .Instance.Text("Gear.Name." + gearIndex)); LocalizedDesc = new ReactiveProperty <string>(PersistentSingleton <LocalizationService> .Instance.Text("Gear.Name.Desc." + gearIndex)); GearRunner gearRunner = Singleton <GearCollectionRunner> .Instance.GetOrCreateGearRunner(gearIndex); int chunkUnlockLevel = PersistentSingleton <Economies> .Instance.GearSets[gearRunner.SetIndex].ChunkUnlockLevel; LocalizedChunkLevelRequirement = new ReactiveProperty <string>(PersistentSingleton <LocalizationService> .Instance.Text("Prestige.ChunkLevelRequirement", chunkUnlockLevel)); Boost1Text = (from amount in gearRunner.Boost1Amount select(gearRunner.Level.Value <= 0) ? config.Boost1.Mult.Amount : amount into amount select BonusTypeHelper.GetAttributeText(config.Boost1.Mult.BonusType, amount)).TakeUntilDestroy(instance).ToReactiveProperty(); Boost2Text = (from amount in gearRunner.Boost2Amount select(gearRunner.Level.Value <= 0) ? config.Boost2.Mult.Amount : amount into amount select BonusTypeHelper.GetAttributeText(config.Boost2.Mult.BonusType, amount)).TakeUntilDestroy(instance).ToReactiveProperty(); Show = (from show in Singleton <GearSetCollectionRunner> .Instance.MaxSetsToShow select show > gearRunner.SetIndex).TakeUntilDestroy(instance).ToReactiveProperty(); ShowPrestige = Show.CombineLatest(gearRunner.UpgradeAfterPrestigeAvailable, (bool show, bool avail) => show && avail).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty(); Boost1Step = new ReactiveProperty <string>(BonusTypeHelper.GetStepText(config.Boost1.Mult.BonusType, config.Boost1.LevelUpAmount)); Boost2Step = new ReactiveProperty <string>(BonusTypeHelper.GetStepText(config.Boost2.Mult.BonusType, config.Boost2.LevelUpAmount)); BundleBoost1 = (from comb in BundleBuyAmount.CombineLatest(gearRunner.Level, (int amount, int lvl) => new { amount, lvl }) select(comb.lvl != 0) ? GetBonusAmount(config.Boost1, comb.amount, initial: false) : GetBonusAmount(config.Boost1, comb.amount, initial: true) into amount select BonusTypeHelper.GetAttributeText(config.Boost1.Mult.BonusType, amount)).TakeUntilDestroy(instance).ToReactiveProperty(); BundleBoost2 = (from comb in BundleBuyAmount.CombineLatest(gearRunner.Level, (int amount, int lvl) => new { amount, lvl }) select(comb.lvl != 0) ? GetBonusAmount(config.Boost2, comb.amount, initial: false) : GetBonusAmount(config.Boost2, comb.amount, initial: true) into amount select BonusTypeHelper.GetAttributeText(config.Boost2.Mult.BonusType, amount)).TakeUntilDestroy(instance).ToReactiveProperty(); }
public GearRunner(int gearIndex) { SceneLoader instance = SceneLoader.Instance; GearIndex = gearIndex; Config = PersistentSingleton <Economies> .Instance.Gears[gearIndex]; GearState orCreateGearState = GearStateFactory.GetOrCreateGearState(gearIndex); Level = orCreateGearState.Level; Level.Skip(1).Subscribe(delegate { if (PersistentSingleton <GameAnalytics> .Instance != null) { PersistentSingleton <GameAnalytics> .Instance.GearUpgraded.Value = this; } }).AddTo(instance); SalvageRelicAmount = (from lvl in Level select GetSalvageAmount(GearIndex, lvl)).TakeUntilDestroy(instance).ToReactiveProperty(); SalvageGemCost = SalvageRelicAmount.Select(SalvageRelicsToGems.Evaluate).ToReactiveProperty(); Unlocked = (from lvl in Level select lvl >= 1).TakeUntilDestroy(instance).ToReactiveProperty(); (from pair in Unlocked.Pairwise() where pair.Current && !pair.Previous select pair).Subscribe(delegate { PlayerData.Instance.LifetimeGears.Value++; }).AddTo(instance); SalvageAvailable = PlayerData.Instance.Gems.CombineLatest(SalvageGemCost, (int gems, int cost) => gems >= cost).TakeUntilDestroy(instance).ToReactiveProperty(); UpgradeRequirement = (from lvl in Level select Singleton <EconomyHelpers> .Instance.GetGearUpgradeCost(GearIndex, lvl)).TakeUntilDestroy(instance).ToReactiveProperty(); MaxLevelReached = (from level in Level select level >= Config.MaxLevel).TakeUntilDestroy(instance).ToReactiveProperty(); UniRx.IObservable <CraftingRequirement> left = GearCollectionRunner.CreateBlocksObservable(); UpgradeAvailable = left.CombineLatest(UpgradeRequirement, (CraftingRequirement have, CraftingRequirement req) => have.Satisfies(req)).CombineLatest(MaxLevelReached, (bool sat, bool max) => sat && !max).TakeUntilDestroy(instance) .ToReactiveProperty(); UpgradeGemCost = left.CombineLatest(UpgradeRequirement, (CraftingRequirement have, CraftingRequirement req) => Singleton <EconomyHelpers> .Instance.GetCraftingGemCost(have, req)).TakeUntilDestroy(instance).ToReactiveProperty(); UpgradeAvailableWithGems = (from comb in UpgradeGemCost.CombineLatest(PlayerData.Instance.Gems, (int cost, int gems) => new { cost, gems }) select(comb.cost <= comb.gems) ? true : false).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty(); UniRx.IObservable <CraftingRequirement> left2 = GearCollectionRunner.CreateAfterPrestigeBlocksObservable(); UpgradeAfterPrestigeAvailable = left2.CombineLatest(UpgradeRequirement, (CraftingRequirement have, CraftingRequirement req) => have.Satisfies(req)).CombineLatest(MaxLevelReached, (bool sat, bool max) => sat && !max).TakeUntilDestroy(instance) .ToReactiveProperty(); Boost1Amount = Observable.Return(Config.Boost1.Mult.Amount).CombineLatest(CreateGearBonusObservable(Config.Boost1.Mult.BonusType, Config.Boost1.LevelUpAmount), (float sum, Func <float, float> f) => f(sum)).TakeUntilDestroy(instance) .ToReactiveProperty(); Boost2Amount = Observable.Return(Config.Boost2.Mult.Amount).CombineLatest(CreateGearBonusObservable(Config.Boost2.Mult.BonusType, Config.Boost2.LevelUpAmount), (float sum, Func <float, float> f) => f(sum)).TakeUntilDestroy(instance) .ToReactiveProperty(); }
public HeroCostRunner(int heroIndex) { SceneLoader instance = SceneLoader.Instance; HeroIndex = heroIndex; m_heroRunner = Singleton <HeroTeamRunner> .Instance.GetOrCreateHeroRunner(heroIndex); UniRx.IObservable <BigDouble> costOne = m_heroRunner.Level.CombineLatest(Singleton <CumulativeBonusRunner> .Instance.BonusMult[6], (int level, BigDouble mult) => Singleton <EconomyHelpers> .Instance.GetUpgradeCost(heroIndex, level)); UniRx.IObservable <BigDouble> costTen = m_heroRunner.Level.CombineLatest(Singleton <CumulativeBonusRunner> .Instance.BonusMult[6], (int level, BigDouble mult) => Singleton <EconomyHelpers> .Instance.GetUpgradeCostRepeat(heroIndex, level, 10 - level % 10)); UniRx.IObservable <BigDouble> costMax = m_heroRunner.Level.CombineLatest(PlayerData.Instance.Coins, Singleton <CumulativeBonusRunner> .Instance.BonusMult[6], (int lvl, BigDouble coins, BigDouble mult) => Singleton <EconomyHelpers> .Instance.GetUpgradeMaxCost(heroIndex, lvl, coins)); Cost = (from cost in Singleton <UpgradeRunner> .Instance.UpgradeStep.Select(delegate(UpgradeEnum step) { switch (step) { case UpgradeEnum.One: return(costOne); case UpgradeEnum.Ten: return(costTen); case UpgradeEnum.Max: return(costMax); default: return(costOne); } }).Switch() select(!(cost >= new BigDouble(1.0))) ? new BigDouble(1.0) : cost).TakeUntilDestroy(instance).ToReactiveProperty(); LevelsToUpgrade = Singleton <UpgradeRunner> .Instance.UpgradeStep.CombineLatest(PlayerData.Instance.Coins, m_heroRunner.Level, delegate(UpgradeEnum step, BigDouble coins, int lvl) { switch (step) { case UpgradeEnum.One: return(1); case UpgradeEnum.Ten: return(10 - lvl % 10); case UpgradeEnum.Max: return(Singleton <EconomyHelpers> .Instance.GetUpgradeMaxLevels(heroIndex, lvl, coins)); default: return(1); } }).TakeUntilDestroy(instance).ToReactiveProperty(); UpgradeAvailable = Cost.CombineLatest(PlayerData.Instance.Coins, (BigDouble cost, BigDouble coins) => cost <= coins).CombineLatest(m_heroRunner.Found, (bool cost, bool found) => cost && found).TakeUntilDestroy(instance) .ToReactiveProperty(); }
public ValidationViewModel() { WithDataAnnotations = new ReactiveProperty <string>() .SetValidateAttribute(() => WithDataAnnotations) .AddTo(Disposables); WithDataAnnotationsErrorMessage = WithDataAnnotations .ObserveValidationErrorMessage() .ToReadOnlyReactivePropertySlim() .AddTo(Disposables); WithCustomValidationLogic = new ReactiveProperty <string>() .SetValidateNotifyError(x => !string.IsNullOrEmpty(x) && x.Contains("-") ? null : "Require '-'") .AddTo(Disposables); WithCustomValidationLogicErrorMessage = WithCustomValidationLogic .ObserveValidationErrorMessage() .ToReadOnlyReactivePropertySlim() .AddTo(Disposables); HasValidationErrors = new[] { WithDataAnnotations.ObserveHasErrors, WithCustomValidationLogic.ObserveHasErrors, }.CombineLatest(x => x.Any(y => y)) .ToReadOnlyReactivePropertySlim() .AddTo(Disposables); SubmitCommand = new[] { WithDataAnnotations.ObserveHasErrors.Inverse(), WithCustomValidationLogic.ObserveHasErrors.Inverse(), }.CombineLatestValuesAreAllTrue() .ToReactiveCommand() .AddTo(Disposables); Message = WithDataAnnotations.CombineLatest(WithCustomValidationLogic, (x, y) => $"You submitted \'{x} & {y}\'") .Throttle(_ => SubmitCommand) .ToReadOnlyReactivePropertySlim(); IgnoreInitialValidationError = new ReactiveProperty <string>(mode: ReactivePropertyMode.Default | ReactivePropertyMode.IgnoreInitialValidationError) .SetValidateAttribute(() => IgnoreInitialValidationError) .AddTo(Disposables); FirstName = Poco.ToReactivePropertyAsSynchronized(x => x.FirstName, ignoreValidationErrorValue: true) .SetValidateAttribute(() => FirstName) .AddTo(Disposables); }
public GamblingAvailableRunner() { Singleton <PropertyManager> .Instance.AddRootContext(this); SceneLoader instance = SceneLoader.Instance; GamblingTime = (from _ in (UniRx.IObservable <long>)TickerService.MasterTicksSlow select Mathf.Max((float)PersistentSingleton <GameSettings> .Instance.GamblingCooldown - (float)new TimeSpan(ServerTimeService.NowTicks() - PlayerData.Instance.GamblingTimeStamp.Value).TotalSeconds, 0f)).DistinctUntilChanged().TakeUntilDestroy(instance).ToReactiveProperty(); GamblingAvailable = (from avail in GamblingTime.CombineLatest(PlayerData.Instance.Gambling, (float time, GamblingState state) => time <= 0.0 || state.CurrentGamblingLevel.Value >= 0) select(avail)).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty(); GamblingTimerAvailable = (from synced in ServerTimeService.IsSynced select(synced)).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty(); GamblingTimeLeft = (from seconds in GamblingTime select TextUtils.FormatSecondsShort((long)seconds)).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty(); SyncedOrNotFinished = (from synced in ServerTimeService.IsSynced.CombineLatest(PlayerData.Instance.Gambling, (bool synced, GamblingState state) => synced || state.CurrentGamblingLevel.Value >= 0) select(synced)).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty(); }
public GamblingRunner() { Singleton <PropertyManager> .Instance.AddRootContext(this); SceneLoader root = SceneLoader.Instance; GamblingBindingManager bind = GamblingBindingManager.Instance; LoadGamblingState(); SetButtonStatesAndAnimatorsToArrays(); MaxGamblingLevel.Value = Singleton <EconomyHelpers> .Instance.GetMaxGamblingLevel(); CurrentGamblingLevel.Subscribe(delegate(int lvl) { m_gambConf = Singleton <EconomyHelpers> .Instance.GetGamblingConfig(lvl); }).AddTo(root); FailPaid.Subscribe(delegate(bool paid) { bind.DrJellyStealPopup.SetActive(!paid); }).AddTo(root); (from states in m_buttonStates[0].CombineLatest(m_buttonStates[1], m_buttonStates[2], m_buttonStates[3], (int one, int two, int three, int four) => new int[4] { one, two, three, four }).Skip(1) where states[0] > 0 || states[1] > 0 || states[2] > 0 || states[3] > 0 select states).Subscribe(delegate { root.StartCoroutine(OpenRestCards()); }).AddTo(root); (from curr in CurrentGamblingLevel where curr > NextJackpotLevel.Value select curr).Subscribe(delegate(int lvl) { NextJackpotLevel.SetValueAndForceNotify(Singleton <EconomyHelpers> .Instance.GetNextGamblingJackpotLevel(lvl)); }).AddTo(root); CurrentGamblingLevel.Subscribe(delegate { root.StartCoroutine(CardSpawnAnimations()); }).AddTo(root); IsJackpotLevel = (from isJP in CurrentGamblingLevel.CombineLatest(NextJackpotLevel, (int lvl, int jp) => lvl == jp) select(isJP)).TakeUntilDestroy(root).ToReadOnlyReactiveProperty(); m_initialOpening = bind.StartCoroutine(OpenInitialCards()); }
public StopWatchModel() { Debug.WriteLine("StopWatchModel ctor"); IsRunning = _isRunning.ToReadOnlyReactiveProperty(); IsVisibleMillis = _isVisibleMillis.ToReadOnlyReactiveProperty(); _timeFormat = IsVisibleMillis .Select(v => v ? @"mm\:ss\.fff" : @"mm\:ss") .ToReactiveProperty(); FormattedTime = _time.CombineLatest(_timeFormat, (time, format) => TimeSpan.FromMilliseconds(time).ToString(format)) .ToReadOnlyReactiveProperty(); FormattedLaps = _laps.CombineLatest(_timeFormat, (laps, f) => laps.Select((x, i) => TimeSpan.FromMilliseconds(x).ToString(f))) .ToReadOnlyReactiveProperty(); }
public GoldBoosterRunner(int booster) { SceneLoader instance = SceneLoader.Instance; GoldBoosterIndex = booster; BoosterCost.Value = PersistentSingleton <GameSettings> .Instance.GoldBoosterPrices[GoldBoosterIndex]; BoosterName.Value = PersistentSingleton <LocalizationService> .Instance.Text("GemBooster.Title." + (GoldBoosterEnum)GoldBoosterIndex); BoosterDescription.Value = PersistentSingleton <LocalizationService> .Instance.Text("GemBooster.Desc." + (GoldBoosterEnum)GoldBoosterIndex); ReadOnlyReactiveProperty <BiomeConfig> source = (from chunk in PlayerData.Instance.LifetimeChunk select Singleton <EconomyHelpers> .Instance.GetBiomeConfig(chunk)).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty(); BoosterReward = (from biome in source select biome.BlockReward * PersistentSingleton <GameSettings> .Instance.GoldBoosterMultipliers[GoldBoosterIndex] into reward select BigDouble.Max(reward, PersistentSingleton <GameSettings> .Instance.GoldBoosterMinRewards[GoldBoosterIndex])).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty(); BoosterAvailable = BoosterCost.CombineLatest(PlayerData.Instance.Gems, (int cost, int gems) => cost <= gems).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty(); ActiveBooster = (from active in Singleton <GoldBoosterCollectionRunner> .Instance.ActiveBooster select active == GoldBoosterIndex).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty(); }
public Report() { OutputPath = new ReactiveProperty <string>(_settings.OutputPath) .SetValidateAttribute(() => OutputPath); FileName = new ReactiveProperty <string>(_settings.Name) .SetValidateAttribute(() => FileName); OutputFilePath = OutputPath .CombineLatest(FileName, (x, y) => GetReportSaveFilePath()) .ToReadOnlyReactiveProperty(); Title = new ReactiveProperty <string>(_settings.Title) .SetValidateAttribute(() => Title); Body = new ReactiveProperty <string>(_settings.Body) .SetValidateAttribute(() => Body); Message = new ReactiveProperty <string>(); }
public SettingsViewModel(TabsModel tabsModel) { Tabs = tabsModel; Instance = new ReactiveProperty <string>(Properties.Settings.Default.AppRegistration?.Instance); AccessToken = new ReactiveProperty <string>(Properties.Settings.Default.Auth?.AccessToken ?? ""); ShowHomeTimelineTab = new ReactiveProperty <bool>(tabsModel.OfType <TimelineTabParameters>()?.Any(x => x.Type == TimelineType.Home) ?? false); ShowLocalTimelineTab = new ReactiveProperty <bool>(tabsModel.OfType <TimelineTabParameters>()?.Any(x => x.Type == TimelineType.Local) ?? false); ShowFederatedTimelineTab = new ReactiveProperty <bool>(tabsModel.OfType <TimelineTabParameters>()?.Any(x => x.Type == TimelineType.Federated) ?? false); ShowNotificationsTab = new ReactiveProperty <bool>(tabsModel.OfType <NotificationTabParameters>()?.Any() ?? false); RequestTokenCommand = Instance .Select(x => !string.IsNullOrEmpty(x)) .ToAsyncReactiveCommand() .WithSubscribe(executeRequestTokenCommand); AuthorizeCommand = AccessToken .CombineLatest(WaitingForAuthCode, (token, waiting) => waiting && token.Length > 0) .ToAsyncReactiveCommand() .WithSubscribe(executeAuthorizeCommand); OkCommand = new ReactiveCommand().WithSubscribe(executeOkCommand); CancelCommand = new ReactiveCommand().WithSubscribe(executeCancelCommand); }
void Start() { var gm = GameManager.Instance; var drag = staffPanelUI.GetComponent <DragTrigger> (); var drop = dropAreaUI.GetComponent <DropTrigger> (); var panelOutLine = panelContentUI.GetComponent <Outline> (); var panelCG = panelContentUI.GetComponent <CanvasGroup>(); var staffPanelCG = staffPanelUI.GetComponent <CanvasGroup> (); var dropCG = dropAreaUI.GetComponent <CanvasGroup> (); var isDragged = gm.draggingNode .Select(n => n == this) .ToReactiveProperty(); isEmpty = isAssigned .CombineLatest(isDragged, (l, r) => !l || r) .ToReadOnlyReactiveProperty(); //show or hide staffpanel isEmpty .Subscribe(e => { staffPanelCG.alpha = e ? 0 : 1; staffPanelCG.blocksRaycasts = !e; emptyPanelUI.SetActive(e); }) .AddTo(this); //enable drop if other node is dragging gm.draggingNode .Select(n => n && n != this) .Subscribe(d => { panelCG.blocksRaycasts = !d; dropCG.blocksRaycasts = d; }) .AddTo(this); //destory if no content isDragged .CombineLatest(isAssigned, (l, r) => l || r) .CombineLatest(hasChild, (l, r) => l || r) .CombineLatest(isRoot, (l, r) => l || r) .Where(exist => !exist) .Subscribe(_ => Destroy(gameObject)) .AddTo(this); //drag trigger drag.OnBeginDragAsObservable() .Subscribe(_ => { //create cursor for drag var cursor = gm.createNode(staffModel.Value); var cursorCG = cursor.GetComponent <CanvasGroup>(); cursorCG.blocksRaycasts = false; cursorCG.alpha = .7f; cursor.tier.Value = tier.Value; //set drag node gm.draggingNode.Value = this; drag.OnDragAsObservable() .Subscribe(d => { (cursor.transform as RectTransform).position = Input.mousePosition; }) .AddTo(cursor); drag.OnEndDragAsObservable() .Subscribe(e => { //remove cursor Destroy(cursor.gameObject); //clear drag node gm.draggingNode.Value = null; }) .AddTo(cursor); }) .AddTo(this); //drop trigger drop.OnDropAsObservable() .Subscribe(e => { var dragNode = e.pointerDrag.GetComponentInParent <NodePresenter>(); //create child or copy value if (isAssigned.Value) { var child = gm.createNode(dragNode.staffModel.Value, childNodes); child.parentNode.Value = this; child.tier.Value = tier.Value + 1; } else { staffModel.Value = dragNode.staffModel.Value; } //clear pointer value dragNode.staffModel.Value = null; gm.draggingNode.Value = null; //highlight panelContentUI.transform.localScale = Vector3.one; panelOutLine.effectColor = Color.black; }) .AddTo(this); drop.OnPointerEnterAsObservable() .Subscribe(_ => { panelContentUI.transform.localScale = new Vector3(1.2f, 1.2f, 1f); panelOutLine.effectColor = Color.red; }) .AddTo(this); drop.OnPointerExitAsObservable() .Subscribe(_ => { panelContentUI.transform.localScale = Vector3.one; panelOutLine.effectColor = Color.black; }) .AddTo(this); }
public BossBattleRunner() { Singleton <PropertyManager> .Instance.AddRootContext(this); SceneLoader instance = SceneLoader.Instance; BossMaxDuration = (from duration in Singleton <CumulativeBonusRunner> .Instance.BonusMult[7] select PersistentSingleton <GameSettings> .Instance.BossDurationSeconds + duration.ToInt()).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty(); UniRx.IObservable <long> left2 = (from dead in (from health in BossCurrentHP select health <= BigDouble.ZERO).DistinctUntilChanged() select(!dead) ? TickerService.MasterTicks : Observable.Never <long>()).Switch(); (from tuple in left2.CombineLatest(BossBattlePaused, (long ticks, bool paused) => new { ticks, paused }) where !tuple.paused select tuple).Subscribe(tuple => { if (ElapsedTime.Value < 864000000000L) { ElapsedTime.Value += tuple.ticks; } }).AddTo(instance); BattleSecondsLeft = (from left in ElapsedTime.CombineLatest(BossMaxDuration, (long elapsed, int dur) => dur - (int)(elapsed / 10000000)) select Mathf.Max(0, left)).TakeUntilDestroy(instance).ToReactiveProperty(); BattleSecondsLeftNormalized = (from secs in BattleSecondsLeft select(float) secs / (float)BossMaxDuration.Value).ToReadOnlyReactiveProperty(); UniRx.IObservable <bool> source = from secs in BattleSecondsLeft.Skip(1) select secs <= 0 into ranOut where ranOut select ranOut; UniRx.IObservable <bool> observable = from killed in (from health in BossCurrentHP select health <= BigDouble.ZERO).DistinctUntilChanged() where killed select killed; observable.Subscribe(delegate { PlayerData.Instance.BossFailedLastTime.Value = false; PersistentSingleton <MainSaver> .Instance.PleaseSave("boss_killed_chunk_" + Singleton <WorldRunner> .Instance.CurrentChunk.Value.Index + "_prestige_" + PlayerData.Instance.LifetimePrestiges.Value); }).AddTo(instance); (from order in Singleton <PrestigeRunner> .Instance.PrestigeTriggered select order == PrestigeOrder.PrestigeStart).Subscribe(delegate { if (BossBattleActive.Value) { ElapsedTime.Value = 85536000000000L; } PlayerData.Instance.BossFailedLastTime.Value = false; }).AddTo(instance); (from seq in Singleton <WorldRunner> .Instance.MapSequence where seq select seq).Subscribe(delegate { PlayerData.Instance.BossFailedLastTime.Value = false; }).AddTo(instance); UniRx.IObservable <bool> observable2 = (from pair in Singleton <ChunkRunner> .Instance.AllBlockAmount.Pairwise() select pair.Current == 1 && pair.Previous > 1).CombineLatest(Singleton <ChunkRunner> .Instance.BossBlock, (bool cleared, BossBlockController boss) => cleared && boss != null).StartWith(value: false); (from activated in observable2 where activated select activated).Subscribe(delegate { StartCountdown(); }).AddTo(instance); BossBattleActive = (from secs in BattleSecondsLeft select secs > 0).CombineLatest(observable2, (bool time, bool block) => time && block).DistinctUntilChanged().TakeUntilDestroy(instance) .ToReadOnlyReactiveProperty(); BossLevelActive = (from boss in Singleton <ChunkRunner> .Instance.BossBlock select boss != null).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty(); (from pair in BossLevelActive.Pairwise() select pair.Current&& !pair.Previous into start where start select start).Subscribe(delegate { StartBossLevel(); }).AddTo(instance); BossPreludeActive = BossLevelActive.CombineLatest(Singleton <ChunkRunner> .Instance.AllBlockAmount, (bool level, int blocks) => level && blocks > 1).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty(); BossFailedActive = BossLevelActive.CombineLatest(BossPreludeActive, BossBattleActive, (bool level, bool prelude, bool battle) => level && !prelude && !battle).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty(); TryBossAvailable = PlayerData.Instance.BossFailedLastTime.CombineLatest(BossLevelActive, (bool failed, bool active) => failed && !active).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty(); BossBattlePending = TryBossAvailable.CombineLatest(BossLevelActive, (bool avail, bool level) => avail || level).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty(); BossSuccessNotification = (from _ in observable select Observable.Merge(new UniRx.IObservable <bool>[2] { Observable.Return <bool>(value: true), Observable.Return <bool>(value: false).Delay(TimeSpan.FromSeconds(10.0)) })).Switch().TakeUntilDestroy(instance).ToReadOnlyReactiveProperty(); BossFailedNotification = (from _ in source select Observable.Merge(new UniRx.IObservable <bool>[2] { Observable.Return <bool>(value: true), Observable.Return <bool>(value: false).Delay(TimeSpan.FromSeconds(10.0)) })).Switch().TakeUntilDestroy(instance).ToReadOnlyReactiveProperty(); BossBattleResult = (from _ in source select false).Merge(observable).StartWith(value: false).ToSequentialReadOnlyReactiveProperty(); BossFullHP = (from chunk in Singleton <WorldRunner> .Instance.CurrentChunk select ChunkRunner.IsLastChunkForNode(chunk.Index)).Select(delegate(bool last) { BiomeConfig value = Singleton <WorldRunner> .Instance.CurrentBiomeConfig.Value; return((!last) ? value.MiniBossHP : value.BossHP); }).CombineLatest(Singleton <DrJellyRunner> .Instance.DrJellyBattle, (BigDouble hp, bool dr) => (!dr) ? hp : (hp * PersistentSingleton <GameSettings> .Instance.DrJellyHpMult)).TakeUntilDestroy(instance) .ToReadOnlyReactiveProperty(); BossHealthNormalized = (from hp in BossFullHP select(!(hp > new BigDouble(1.0))) ? new BigDouble(1.0) : hp).CombineLatest(BossCurrentHP, (BigDouble full, BigDouble current) => (current / full).ToFloat()).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty(); (from result in BossBattleResult.Skip(1) where !result select result).Subscribe(delegate { AudioController.Instance.QueueEvent(new AudioEvent("BossSequenceFailed", AUDIOEVENTACTION.Play)); }).AddTo(instance); (from result in BossBattleResult.Skip(1) where result select result).Subscribe(delegate { PlayerData.Instance.RetryLevelNumber.Value = 0; }).AddTo(instance); if (PersistentSingleton <GameAnalytics> .Instance != null) { BossBattleResult.Subscribe(delegate(bool result) { PersistentSingleton <GameAnalytics> .Instance.BossBattleResult.Value = result; }).AddTo(instance); } }
public void LateInitialize() { if (ShouldLoginImmediately) { Login(); ShouldLoginImmediately = false; } if (base.Inited) { Singleton <CloudSyncRunner> .Instance.CloudSync("init_pf"); return; } UniRx.IObservable <bool> first = from should in ConnectivityService.InternetConnectionAvailable.CombineLatest(PlayerData.Instance.LifetimePrestiges, (bool net, int prestiges) => net && string.IsNullOrEmpty(LoggedOnPlayerId.Value) && prestiges > 0) where should select should; UniRx.IObservable <bool> observable = from should in ConnectivityService.InternetConnectionAvailable.CombineLatest(PersistentSingleton <FacebookAPIService> .Instance.IsLoggedToFB, (bool net, bool fb) => net && fb) where should select should; first.Merge(observable).Subscribe(delegate { Login(); }); MainThreadDispatcher.StartCoroutine(QueueRoutine()); (from chunk in PlayerData.Instance.LifetimeChunk select(chunk != 0) ? Observable.Never <bool>() : m_hasCommandsInFlight.AsObservable()).Switch().Subscribe(delegate(bool inFlight) { if (BindingManager.Instance != null) { BindingManager.Instance.SystemPopup.SetActive(inFlight); } }); LoggedOnPlayerId.Subscribe(delegate(string loggedID) { PlayerData.Instance.PFId.Value = loggedID; }); LoggedOnPlayerId.CombineLatest(PlayerData.Instance.DisplayName, (string id, string dn) => dn).Subscribe(delegate(string name) { PlayFabService playFabService = this; GetAccountInfo(delegate(JSONObject json) { string a = json.asJSONObject("AccountInfo").asJSONObject("TitleInfo").asString("DisplayName", () => string.Empty); if (name != string.Empty && a != name) { playFabService.UpdateUserDisplayName(name, null, null); } else if (name == string.Empty && a == string.Empty) { (from fbname in Singleton <FacebookRunner> .Instance.PlayerName.AsObservable().Take(1) where !string.IsNullOrEmpty(fbname) select fbname).Subscribe(delegate(string fbname) { playFabService.UpdateUserDisplayName(fbname, null, null); }); } }, null); }); base.Inited = true; }
public ColumnSettingSettingsFlyoutViewModel() { _resourceLoader = new ResourceLoader(); CanChangeSetting = new ReactiveProperty <bool>(true); Name = new ReactiveProperty <string>(); Filter = new ReactiveProperty <string>(); DisableStartupRefresh = new ReactiveProperty <bool>(); AutoRefresh = new ReactiveProperty <bool>(); AutoRefreshTimerInterval = new ReactiveProperty <double>(); FetchingNumberOfTweet = new ReactiveProperty <int>(); ErrorMessage = new ReactiveProperty <string>(); UpdateButtonEnabled = new ReactiveProperty <bool>(true); ColumnSetting = new ReactiveProperty <ColumnSetting>(); ColumnSetting.Subscribe(x => { if (x == null) { return; } Filter.Value = x.Filter; Name.Value = x.Name; DisableStartupRefresh.Value = x.DisableStartupRefresh; AutoRefresh.Value = x.AutoRefresh; AutoRefreshTimerInterval.Value = x.AutoRefreshTimerInterval; FetchingNumberOfTweet.Value = x.FetchingNumberOfTweet; if (ColumnSetting.Value.Action == SettingSupport.ColumnTypeEnum.Home || ColumnSetting.Value.Action == SettingSupport.ColumnTypeEnum.Mentions || ColumnSetting.Value.Action == SettingSupport.ColumnTypeEnum.DirectMessages || ColumnSetting.Value.Action == SettingSupport.ColumnTypeEnum.Events || ColumnSetting.Value.Action == SettingSupport.ColumnTypeEnum.Favorites) { CanChangeSetting.Value = false; } else { CanChangeSetting.Value = true; } }); Filter.CombineLatest(Name, (filter, name) => new { Filter = filter, Name = name }) .Subscribe(x => { if (string.IsNullOrEmpty(x.Name)) { ErrorMessage.Value = _resourceLoader.GetString("SettingsFlyout_Settings_Column_Name_NameIsEmpty"); UpdateButtonEnabled.Value = false; return; } if (string.IsNullOrWhiteSpace(x.Filter)) { ErrorMessage.Value = _resourceLoader.GetString("SettingsFlyout_Settings_Column_Filter_FilterIsEmpty"); UpdateButtonEnabled.Value = false; return; } try { Compiler.Compile(x.Filter, false); } catch (FilterCompileException e) { ErrorMessage.Value = _resourceLoader.GetString( "SettingsFlyout_Settings_Mute_MuteFilter_FilterCompileError") + "\n" + _resourceLoader.GetString("Filter_CompileError_" + e.Error.ToString()); UpdateButtonEnabled.Value = false; return; } catch (Exception e) { ErrorMessage.Value = _resourceLoader.GetString( "SettingsFlyout_Settings_Mute_MuteFilter_FilterCompileError") + "\n" + e.Message; UpdateButtonEnabled.Value = false; return; } ErrorMessage.Value = _resourceLoader.GetString("SettingsFlyout_Settings_Column_SaveOK"); UpdateButtonEnabled.Value = true; }); SaveColumnSettingCommand = new ReactiveCommand(); SaveColumnSettingCommand.Subscribe(async x => { ColumnSetting.Value.Name = Name.Value; ColumnSetting.Value.Filter = Filter.Value; ColumnSetting.Value.DisableStartupRefresh = DisableStartupRefresh.Value; ColumnSetting.Value.AutoRefresh = AutoRefresh.Value; ColumnSetting.Value.AutoRefreshTimerInterval = AutoRefreshTimerInterval.Value; ColumnSetting.Value.FetchingNumberOfTweet = FetchingNumberOfTweet.Value; await AdvancedSettingService.AdvancedSetting.SaveToAppSettings(); await Notice.Instance.ShowMessageDialogMessenger.Raise(new MessageDialogNotification { Message = _resourceLoader.GetString("ConfirmDialog_UpdateColumnSettingSuccessfully"), Title = "Message" }); }); }
public ValidationWindowViewModel() { WithDataAnnotations = new ReactiveProperty <string>() // 1) ReavtivePropertyを生成する .SetValidateAttribute(() => WithDataAnnotations) // 2) WithDataAnnotationsに割り当たっている属性を1)で作ったインスタンスにセットする .AddTo(Disposables); // 3) まとめてDisposeできるように登録 WithDataAnnotationsErrMessage = WithDataAnnotations // 1) 情報ソースから .ObserveValidationErrorMessage() // 2) ValidationエラーメッセージをObserveする .ToReadOnlyReactivePropertySlim() // 3) ReactivePropertyに変換 .AddTo(Disposables); // 4) まとめてDisposeできるように登録 WithCustomValidationLogic = new ReactiveProperty <string>() .SetValidateNotifyError(x => !string.IsNullOrEmpty(x) && x.Contains("-") ? null : "Require '-'") .AddTo(Disposables); WithCustomValidationLogicErrMessage = WithCustomValidationLogic .ObserveValidationErrorMessage() .ToReadOnlyReactivePropertySlim() .AddTo(Disposables); HasValidationErrors = new[] { WithDataAnnotations.ObserveHasErrors, WithCustomValidationLogic.ObserveHasErrors, }.CombineLatest(x => x.Any(y => y)) .ToReactiveProperty() .AddTo(Disposables); //HasValidationErrors = WithDataAnnotations.ObserveHasErrors // .CombineLatest(WithCustomValidationLogic.ObserveHasErrors, (x, y) => x | y) // .ToReactiveProperty() // .AddTo(Disposables); ////https://blog.okazuki.jp/entry/20120219/1329663635 SubmitCommand = new[] { WithDataAnnotations.ObserveHasErrors.Inverse(), // WithDataAnnotationsにエラーがないこと WithCustomValidationLogic.ObserveHasErrors.Inverse(), // WithCustomValidationLogicにエラーがないこと }.CombineLatestValuesAreAllTrue() // どちらかのイベントが発行されたときに、どちらもTrueであること .ToReactiveCommand() // コマンドに変更 .AddTo(Disposables); // コマンド処理処理の登録 SubmitCommand.Subscribe(_ => Trace.WriteLine("SubmitCommand")); Message = WithDataAnnotations.CombineLatest(WithCustomValidationLogic, (x, y) => $"You submitted \'{x} & {y}\'") //.Throttle(TimeSpan.FromMilliseconds(1000)) // 1000ms間値が変化しなかったら、それまでの値を流す。 .Throttle(_ => SubmitCommand) // SubmitCommandが実行されたときに、それまでの値を流す。。。?? .ToReadOnlyReactivePropertySlim(); // 最初のValidationエラーを無視してくれる IgnoreInitialValidationError = new ReactiveProperty <string>(mode: ReactivePropertyMode.Default | ReactivePropertyMode.IgnoreInitialValidationError) .SetValidateAttribute(() => IgnoreInitialValidationError) .AddTo(Disposables); // ModelとシンクしているプロパティのValidation FirstName = poco.ToReactivePropertyAsSynchronized(x => x.FirstName, ignoreValidationErrorValue: true) .SetValidateAttribute(() => FirstName) // ↑ ignoreValidationErrorValue: エラー時にModelに値を反映させるかどうかのフラグ .AddTo(Disposables); }
/// <summary> /// /// </summary> /// <param name="manager"></param> public MainWindowViewModel(ApplicationManager manager) { _manager = manager; _manager.Error += manager_Error; _applications = _manager.Applications.ToSyncedSynchronizationContextCollection(x => new ApplicationViewModel(_manager, x), SynchronizationContext.Current); IsSettingsOpen = new ReactiveProperty<bool>(false); IsDetailsOpen = new ReactiveProperty<bool>(false); IsProgressActive = new ReactiveProperty<bool>(false); ShowWindowRightCommands = IsSettingsOpen.CombineLatest(IsDetailsOpen, (a, b) => !a && !b) .ToReactiveProperty(); InitialDirectory = _manager.Settings.ToReactivePropertyAsSynchronized(x => x.ApplicationRootDirectoryPath); ShowHelpCommand = new ReactiveCommand(); ShowHelpCommand.Subscribe(_ => ShowHelp()); RegisterApplicationCommand = IsProgressActive.Select(x => !x).ToReactiveCommand(); RegisterApplicationCommand.Subscribe(_ => RegisterApplication()); InstallApplicationCommand = IsProgressActive.Select(x => !x).ToReactiveCommand(); InstallApplicationCommand.Subscribe(_ => InstallApplication()); OpenSettingCommand = new ReactiveCommand(); OpenSettingCommand.Subscribe(_ => ShowSettings()); ShowDetailsCommand = new ReactiveCommand<ApplicationViewModel>(); ShowDetailsCommand.Subscribe(ShowDetails); CurrentItem = new ReactiveProperty<ApplicationViewModel>(); SettingsViewModel = new ReactiveProperty<SettingsViewModel>(); }
public void PostInit() { SceneLoader root = SceneLoader.Instance; BindingManager bind = BindingManager.Instance; (from order in Singleton <PrestigeRunner> .Instance.PrestigeTriggered where order == PrestigeOrder.PrestigePost select order).Do(delegate { }).Subscribe(delegate { ResetChunks(); SpawnBaseCamp(); }).AddTo(root); BlocksClearTriggered.Do(delegate { }).Subscribe(delegate { if (!IsNextChunkBoss(Singleton <WorldRunner> .Instance.CurrentChunk.Value.Index)) { SpawnChunkIncrease(); } else if (PlayerData.Instance.BossFailedLastTime.Value) { SpawnChunkRetry(); } else { SpawnBoss(); } }).AddTo(root); (from _ in Singleton <BossSuccessRunner> .Instance.SequenceClosed where !ShouldGoToMap(Singleton <WorldRunner> .Instance.CurrentChunk.Value.Index, PlayerData.Instance.LifetimeChunk.Value) select _).Do(delegate { }).Subscribe(delegate { SpawnChunkIncrease(); }).AddTo(root); (from _ in Singleton <BossSuccessRunner> .Instance.SequenceClosed where ShouldGoToMap(Singleton <WorldRunner> .Instance.CurrentChunk.Value.Index, PlayerData.Instance.LifetimeChunk.Value) select _).Do(delegate { }).Subscribe(delegate { root.StartCoroutine(MapSequenceRoutine()); }).AddTo(root); (from win in Singleton <BossBattleRunner> .Instance.BossBattleResult.Skip(1) where !win select win).Delay(TimeSpan.FromSeconds(3.0)).Subscribe(delegate { if (PlayerData.Instance.BossFailedLastTime.Value) { SpawnChunkRetry(); } }).AddTo(root); (from tuple in Singleton <BossBattleRunner> .Instance.BossBattleActive.CombineLatest(Singleton <BossBattleRunner> .Instance.BossCurrentHP, (bool active, BigDouble hp) => new { active, hp }) where tuple.active select tuple).Subscribe(tuple => { ChunkMaxHealth.Value = Singleton <BossBattleRunner> .Instance.BossFullHP.Value; CurrentChunkHealth.Value = tuple.hp; }).AddTo(root); (from active in Singleton <BossBattleRunner> .Instance.BossBattleActive.Pairwise() where !active.Current && active.Previous select active).Subscribe(delegate { CurrentChunkHealth.Value = BigDouble.ZERO; }).AddTo(root); BlocksClearTriggered.Subscribe(delegate { CurrentChunkHealth.Value = BigDouble.ZERO; }).AddTo(root); (from _ in (from _ in TryBossAgainTriggered select(from moving in Singleton <CameraMoveRunner> .Instance.IsCameraMoving where !moving select moving).Take(1)).Switch() where !Singleton <BossBattleRunner> .Instance.BossLevelActive.Value select _).Subscribe(delegate { SpawnBossRetry(); }).AddTo(root); if (Singleton <WorldRunner> .Instance.CurrentChunk.Value.Index == 0) { SpawnBaseCamp(); } else { SpawnGameLoaded(); } if (PlayerData.Instance.LifetimeChunk.Value == 0 && PersistentSingleton <GameSettings> .Instance.IntroSequenceOn) { BindingManager.Instance.MapPanel.SetActive(value: true); BindingManager.Instance.MapCamera.IntroCameraDrive(); } Singleton <TntRunner> .Instance.TntTriggered.Subscribe(delegate(BigDouble damage) { CauseDamageToRandomBlocks(damage, (128L * Singleton <CumulativeBonusRunner> .Instance.BonusMult[12].Value).ToInt()); Vector3 position = bind.CameraCtrl.transform.position; CauseBlastWave(position.x0z(), 10f); }).AddTo(root); HeroDamageRunner mainHeroDamage = Singleton <HeroTeamRunner> .Instance.GetOrCreateHeroDamageRunner(0); Singleton <AutoMineRunner> .Instance.DamageTriggered.Subscribe(delegate { CauseDamageToClosestBlockOrBoss(mainHeroDamage.Damage.Value *PersistentSingleton <GameSettings> .Instance.AutoMineMultiplier, bind.TornadoDamageNode.position); }).AddTo(root); GoldBlockReward = BlocksInChunk.CombineLatest(Singleton <WorldRunner> .Instance.CurrentBiomeConfig, Singleton <GoldFingerRunner> .Instance.GoldFingerActive, GoldBlocks, (int blocks, BiomeConfig cnfg, bool goldFinger, int golds) => (!goldFinger) ? (new BigDouble(blocks) * cnfg.BlockReward / golds) : (cnfg.BlockReward * 13.5)).TakeUntilDestroy(root).ToReactiveProperty(); (from gf in Singleton <GoldFingerRunner> .Instance.GoldFingerActive.Pairwise() where !gf.Current && gf.Previous select gf).Subscribe(delegate { GoldBlockReward.SetValueAndForceNotify(Singleton <WorldRunner> .Instance.CurrentBiomeConfig.Value.BlockReward * 13.5); }).AddTo(root); CanBeHurt = Singleton <BossBattleRunner> .Instance.BossBattlePaused.CombineLatest(Singleton <PrestigeRunner> .Instance.SequenceDone, Singleton <WorldRunner> .Instance.MapSequence, (bool bossPause, bool prestigeDone, bool map) => !bossPause && prestigeDone && !map).TakeUntilDestroy(root).ToReadOnlyReactiveProperty(); TickerService.MasterTicksFast.Subscribe(delegate(long ticks) { m_timeSinceLastHitSound += ticks; m_timeSinceLastDestroySound += ticks; }).AddTo(root); (from triggered in BlocksClearTriggered where triggered select triggered).Subscribe(delegate { overflowChunk = false; }).AddTo(root); }
public TournamentRunner() { SceneLoader instance = SceneLoader.Instance; Singleton <PropertyManager> .Instance.AddRootContext(this); PFIDsUsed.Add("D1E872B9C9DA0648"); LoggedInPlayfab = (from id in PersistentSingleton <PlayFabService> .Instance.LoggedOnPlayerId.StartWith(string.Empty) select id != string.Empty).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty(); TimeTillTournament = TickerService.MasterTicksSlow.CombineLatest(ServerTimeService.IsSynced, (long tick, bool sync) => (!sync) ? (-1) : GetTimeTillTournament()).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty(); TimeTillTournamentClock = (from time in TimeTillTournament.DistinctUntilChanged() select(time <= 0) ? string.Empty : TextUtils.FormatSecondsShortWithDays(time)).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty(); (from till in TimeTillTournament where till == 0 select till).Subscribe(delegate { ResetIfDifferentDevice(); }).AddTo(instance); TournamentAccessable = TimeTillTournament.CombineLatest(PlayerData.Instance.TournamentIdCurrent, TournamentFetched, ConnectivityService.InternetConnectionAvailable, (long time, int id, bool fetched, bool connected) => connected && time == 0 && id < 0 && fetched).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty(); CurrentlyInTournament = (from id in PlayerData.Instance.TournamentIdCurrent select id >= 0 && CheckIfSameDevice()).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty(); (from should in TournamentFetched.CombineLatest(TimeTillTournament, FetchAttempt, LoggedInPlayfab, (bool fetched, long till, int attempt, bool loggedIn) => !fetched && attempt == 0 && till == 0) where should select should).Subscribe(delegate { TryToFetchTournament(); }).AddTo(instance); (from timestamp in PlayerData.Instance.TournamentTimeStamp where timestamp + 10000000L * (long)PersistentSingleton <GameSettings> .Instance.TournamentDurationSeconds >= ServerTimeService.NowTicks() && ServerTimeService.NowTicks() >= timestamp && CheckIfSameDevice() select timestamp).Subscribe(delegate { TournamentRuns.SetValueAndForceNotify(LoadTournamentRuns()); TournamentActive.SetValueAndForceNotify(value: true); }).AddTo(instance); TimeTillTournamentEnd = (from should in TickerService.MasterTicks.CombineLatest(ServerTimeService.IsSynced, PlayerData.Instance.TournamentIdCurrent, (long tick, bool sync, int id) => sync && id >= 0 && CheckIfSameDevice()) where should select should into _ select GetTimeTillTournamentEnd()).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty(); TournamentEndClock = (from time in TimeTillTournamentEnd.DistinctUntilChanged() select(time <= 0) ? string.Empty : TextUtils.FormatSecondsShort(time)).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty(); TournamentEnded = TimeTillTournamentEnd.CombineLatest(PlayerData.Instance.TournamentIdCurrent, (long time, int id) => time < 0 && id >= 0).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty(); (from ended in TournamentEnded where ended select ended).Subscribe(delegate { LoadTournamentEndedValues(); }).AddTo(instance); TournamentWorldReached = (from world in PlayerData.Instance.MainChunk select world >= 70).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty(); DisplayNameGiven = (from name in PlayerData.Instance.DisplayName select name != string.Empty).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty(); TournamentsUnlocked = PlayerData.Instance.LifetimePrestiges.CombineLatest(PlayerData.Instance.LifetimeChunk, (int prest, int chunk) => prest > 0 || chunk >= 45).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty(); (from unlocked in TournamentsUnlocked.Pairwise() where !unlocked.Previous && unlocked.Current select unlocked).Subscribe(delegate { BindingManager.Instance.TournamentUnlockedParent.ShowInfo(); }).AddTo(instance); PlayerData.Instance.Medals.Take(1).Subscribe(delegate { TryToBuyTrophy(showUnlocking: false); }).AddTo(instance); PlayerData.Instance.Trophies.Subscribe(delegate(int trophies) { CalculateTrophiesMultiplier(trophies); }).AddTo(instance); InternetConnectionAvailable = (from avail in ConnectivityService.InternetConnectionAvailable select(avail)).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty(); }
public GetAppInstallFilesBlobDialogViewModel() { // Show/Hide Blob ShowHideBlobSectionCommand.Subscribe(_ => { ShowHideBlobSectionButtonLabel.Value = ShowBlobSectionVisibility.Value == Visibility.Collapsed ? ExpandButtonLabel : CollapseButtonLabel; ShowBlobSectionVisibility.Value = ShowBlobSectionVisibility.Value == Visibility.Collapsed ? Visibility.Visible : Visibility.Collapsed; }) .AddTo(disposable); // Storage Credential Input StorageConnectionInput = new ReactiveProperty <string>(blobConnectionUseCase.Read <string>("blob_connection_string")); StorageConnectionInput.Subscribe(x => blobConnectionUseCase.Save("blob_connection_string", x)).AddTo(disposable); StorageContainerInput = new ReactiveProperty <string>(blobConnectionUseCase.Read <string>("container")); StorageContainerInput.Subscribe(x => blobConnectionUseCase.Save("container", x)).AddTo(disposable); // Copy Button CopyButtonContent = new ReactiveProperty <string>("Copy SasUrl"); CopyButtonEnabled = ArtifactUrl.Select(x => !string.IsNullOrWhiteSpace(x)).ToReactiveProperty(); OnClickCopyCommand = CopyButtonEnabled.ToReactiveCommand(); OnClickCopyCommand .Do(_ => blobSasUrlUseCase.CopySasUrl(ArtifactUrl.Value, StorageConnectionInput.Value, StorageContainerInput.Value, SelectedArtifact.Value.Name)) .SelectMany(x => TemporaryDisableCopyButtonAsObservable(TimeSpan.FromMilliseconds(500), "Copy SasUrl")) .Subscribe() .AddTo(disposable); // Download Button blobArtifactUsecase.DownloadStatus.Subscribe(x => DownloadStatus.Value = x).AddTo(disposable); OnClickDownloadCommand = CopyButtonEnabled.ToAsyncReactiveCommand(); OnClickDownloadCommand .Subscribe(async _ => await blobArtifactUsecase.DownloadHoloLensPackagesAsync(StorageConnectionInput.Value, StorageContainerInput.Value, SelectedArtifact.Value.Name, SelectedArtifact.Value.Size, SelectedArtifact.Value.FileName)) .AddTo(disposable); // OpenFolder Button OnClickOpenDownloadFolderCommand.Subscribe(_ => blobArtifactUsecase.OpenFolderAsync()).AddTo(disposable); OnClickOpenDownloadBlobFolderCommand.Subscribe(_ => blobArtifactUsecase.OpenDownloadFolderAsync()).AddTo(disposable); // Initialize by obtain artifact informations blobArtifactUsecase.Artifacts .Where(x => x != null) .Do(x => { Projects.Add(x); BlobResult.Value = $"Found {Projects.Count} projects."; }) .Subscribe() .AddTo(disposable); blobArtifactUsecase.RequestFailedMessage .Do(x => BlobResult.Value = x) .Subscribe() .AddTo(disposable); // Blob Download ComboBoxEnabled = Projects.CollectionChangedAsObservable().Any().ToReactiveProperty(); IsEnableCheckBlobButton = StorageConnectionInput .CombineLatest(StorageContainerInput, (r, l) => !string.IsNullOrWhiteSpace(r) && !string.IsNullOrWhiteSpace(l)) .ToReadOnlyReactiveProperty(); OnClickCheckBlobCommand = IsEnableCheckBlobButton.ToAsyncReactiveCommand(); OnClickCheckBlobCommand.Subscribe(async _ => { var task = blobArtifactUsecase.RequestHoloLensPackagesAsync(StorageConnectionInput.Value, StorageContainerInput.Value); IsBlobChecking.Value = true; Projects.Clear(); Branches?.Clear(); Artifacts?.Clear(); BlobResult.Value = "Trying obtain project infomations."; await task; IsBlobChecking.Value = false; }) .AddTo(disposable); OnClickCancelBlobCommand = IsBlobChecking.Select(x => x).ToReactiveCommand(); OnClickCancelBlobCommand .Do(_ => Projects.Clear()) .Subscribe(_ => blobArtifactUsecase.CancelRequest()) .AddTo(disposable); // Update Collection with Clear existing collection when selected. Branches = SelectedProject.Where(x => x != null) .Do(_ => Branches?.Clear()) .Do(_ => Artifacts?.Clear()) .SelectMany(x => blobArtifactUsecase.GetArtifactCache(x.Project)) .ToReactiveCollection(); Artifacts = SelectedBranch.Where(x => x != null) .Do(x => Artifacts?.Clear()) .SelectMany(x => blobArtifactUsecase.GetArtifactCache(SelectedProject.Value?.Project, x.Branch)) .ToReactiveCollection(); SelectedArtifact .Where(x => x != null) .Do(x => { ArtifactName.Value = x.Name; ArtifactCaption.Value = $"(Size: {x.Size}, MD5: {x.MD5}, LeaseState: {x.LeaseState})"; ArtifactUrl.Value = x.Uri.AbsoluteUri; }) .ToReactiveProperty(); }