public QuickImportOption(string _name){
			option_name = _name;
			dropdown_option = new Dropdown.OptionData();
			
			rx_display_text = LanguageController.controller.rx_get_filename_label(_name);
			
			sub = rx_display_text.Subscribe(t=>{
				dropdown_option.text = t;
			});
		}
	void Start() {
		if (slider != null){
			rx_value = slider.OnValueChangedAsObservable().Select<float, float>(
				clamp_value).ToReadOnlyReactiveProperty<float>(clamp_value(slider.value));
			rx_value.Subscribe(
				value => {
					if (icon != null)
						icon.color = StrawberryColor.color_gradient.Evaluate(value);
				}
			);
		}
	}
Ejemplo n.º 3
0
        public ARLessonAccess()
        {
            ReadOnlyReactiveProperty <ARSessionState> currentARSessionState = Observable
                                                                              .FromEvent <ARSessionStateChangedEventArgs>(
                h => ARSession.stateChanged += h,
                h => ARSession.stateChanged -= h)
                                                                              .Select(args => args.state)
                                                                              .ToReadOnlyReactiveProperty(ARSession.state);

            AddDisposable(currentARSessionState);
            AddDisposable(currentARSessionState.Subscribe(OnARSessionStateChanged));
        }
    /// <summary>
    /// Data binding method.
    /// </summary>
    /// <typeparam name="TView">View type</typeparam>
    /// <typeparam name="TProperty">Property type</typeparam>
    /// <param name="self">View</param>
    /// <param name="setter">Target value setter</param>
    /// <param name="source">Source property</param>
    /// <returns>Data binding token</returns>
    public static IDisposable SetBindingTableViewDataSource <TView, TProperty>(
        this TView self,
        Action <TView, TProperty> setter,
        ReadOnlyReactiveProperty <TProperty> source)
        where TView : IUITableViewDataSource
    {
        var d = new CompositeDisposable();

        source
        .Subscribe(x => setter(self, x))
        .AddTo(d);

        return(d);
    }
    /// <summary>
    /// Data binding method.
    /// </summary>
    /// <typeparam name="TView">View type</typeparam>
    /// <typeparam name="TProperty">Property type</typeparam>
    /// <param name="self">View</param>
    /// <param name="setter">Target value setter</param>
    /// <param name="source">Source property</param>
    /// <returns>Data binding token</returns>
    public static IDisposable SetBindingGestureRecognizer <TView, TProperty>(
        this TView self,
        Action <TView, TProperty> setter,
        ReadOnlyReactiveProperty <TProperty> source)
        where TView : UIGestureRecognizer
    {
        var d = new CompositeDisposable();

        source
        .Subscribe(x => setter(self, x))
        .AddTo(d);

        return(d);
    }
Ejemplo n.º 6
0
    /// <summary>
    /// 1秒に1回、現在時刻を通知する
    /// </summary>
    private void ToReadOnlyReactivePropertyTimer()
    {
        ReadOnlyReactiveProperty <string> timer = Observable
                                                  .Interval(TimeSpan.FromSeconds(1))
                                                  .Select(_ => DateTime.Now.ToString())
                                                  .ToReadOnlyReactiveProperty();

        timer
        .Subscribe(x => {
            Debug.Log("Now Time : " + x);
        }, () => {
            Debug.Log("Timer onCompleted");
        }).AddTo(this);
    }
    /// <summary>
    /// Data binding method.
    /// </summary>
    /// <typeparam name="TView">View type</typeparam>
    /// <typeparam name="TProperty">Property type</typeparam>
    /// <param name="self">View</param>
    /// <param name="propertySelector">Target property selector</param>
    /// <param name="source">Source property</param>
    /// <returns>Data binding token</returns>
    public static IDisposable SetBindingTableViewDataSource <TView, TProperty>(
        this TView self,
        Expression <Func <TView, TProperty> > propertySelector,
        ReadOnlyReactiveProperty <TProperty> source)
        where TView : IUITableViewDataSource
    {
        var d = new CompositeDisposable();

        var setter = AccessorCache <TView> .LookupSet(propertySelector, out var propertyName);

        source
        .Subscribe(x => setter(self, x))
        .AddTo(d);
        return(d);
    }
Ejemplo n.º 8
0
    public DrJellyRunner()
    {
        SceneLoader instance = SceneLoader.Instance;

        Singleton <PropertyManager> .Instance.AddRootContext(this);

        SpawningLevel = (from lvl in PlayerData.Instance.DrJellySpawningLevel
                         select(lvl)).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty();
        DrJellyAppeared = PlayerData.Instance.MainChunk.CombineLatest(PlayerData.Instance.DrJellySpawningLevel, (int chunk, int lvl) => chunk == lvl).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty();
        DrJellyLevel    = (from lvl in PlayerData.Instance.DrJellyLevel
                           select(lvl)).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty();
        DrJellyBattle = PlayerData.Instance.MainChunk.CombineLatest(PlayerData.Instance.DrJellyLevel, (int chunk, int lvl) => chunk == lvl).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty();
        DrJellyLevel.Subscribe(delegate
        {
            ForceJellyHeliAsBiome();
        }).AddTo(instance);
    }
	void Start(){
		if (ui_texts.Count == 0)
			ui_texts.AddRange(GetComponents<Text>());
		if (mesh_texts.Count == 0)
			mesh_texts.AddRange(GetComponents<TextMesh>());
		//Stopgap solution until I can get dependency injection working.
		if (controller == null){
			controller = LanguageController.controller;
		}
		rx_value = controller.rx_get_language_label(rx_language);
		sub = rx_value.Subscribe((t)=>{
			foreach(Text ui in ui_texts){
				if (ui != null){
					ui.text = t;
				}
			}
			foreach(TextMesh mesh in mesh_texts){
				if (mesh != null){
					mesh.text = t;
				}
			}
		});
	}
	void Awake () {
		rx_score.Subscribe((s)=>{
			if (s != null){
				date_time.text = s.time.date_recorded_local().ToString();
				score_text.text = s.final_score().ToString("0.00");
			}
		});
		
		rx_player_name = rx_score.SelectMany(s=>{
			if (s == null)
				return Observable.Never<String>();
			return s.rx_player_name.AsObservable();
		}).CombineLatest(LanguageController.controller.rx_load_text("score_default_name"), (name, default_name)=>{
			if (IsNullOrWhiteSpace(name))
				return default_name;
			return name;
		}).ToReadOnlyReactiveProperty<string>();
		
		rx_player_name.Subscribe(t=>{
			if (player_name != null)
				player_name.text = t;
		});
	}
Ejemplo n.º 11
0
    public void PostInit()
    {
        SceneLoader instance = SceneLoader.Instance;

        IAPCompleted = (from completed in PersistentSingleton <IAPService> .Instance.IAPCompleted
                        select(completed)).TakeUntilDestroy(instance).ToSequentialReadOnlyReactiveProperty();
        IAPCompleted.Subscribe(delegate
        {
            if (IAPCompleted.Value.Config.Reward.Type != 0)
            {
                RewardForPurchase(IAPCompleted.Value.Config);
                PurchaseSuccess.SetValueAndForceNotify(value: true);
            }
        }).AddTo(instance);
        IAPNotCompleted = (from notCompleted in PersistentSingleton <IAPService> .Instance.IAPNotCompleted
                           where notCompleted.Status == "Failed" || notCompleted.Status == "Cancelled"
                           select(notCompleted)).TakeUntilDestroy(instance).ToSequentialReadOnlyReactiveProperty();
        IAPNotCompleted.Do(delegate
        {
        }).Subscribe(delegate
        {
            PurchaseFail.SetValueAndForceNotify(value: true);
        }).AddTo(instance);
    }
	void Start(){
		if (ui_texts.Count == 0)
			ui_texts.AddRange(GetComponents<Text>());
		if (mesh_texts.Count == 0)
			mesh_texts.AddRange(GetComponents<TextMesh>());
		//Stopgap solution until I can get dependency injection working.
		if (controller == null){
			controller = LanguageController.controller;
		}
		rx_value = controller.rx_load_text(rx_key);
		subscription = rx_value.Subscribe((t)=>{
			string full_text = prefix + t + suffix;
			foreach(Text ui in ui_texts){
				if (ui != null){
					ui.text = full_text;
				}
			}
			foreach(TextMesh mesh in mesh_texts){
				if (mesh != null){
					mesh.text = full_text;
				}
			}
		});
	}
Ejemplo n.º 13
0
 public IDisposable Subscribe(IObserver <bool> observer)
 {
     return(IsActiveObservable.Subscribe(observer));
 }
Ejemplo n.º 14
0
 protected SinglePresenterControl()
 {
     View = _view.ToReadOnlyReactiveProperty();
     View.Subscribe(x => MutableFirstView.Value = x);
 }
Ejemplo n.º 15
0
    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);
    }
Ejemplo n.º 16
0
    public HeroRunner(int heroIndex)
    {
        SceneLoader           instance            = SceneLoader.Instance;
        UIIngameNotifications IngameNotifications = BindingManager.Instance.IngameNotifications;

        HeroIndex = heroIndex;
        BerryIndex.SetValueAndForceNotify(HeroIndex % 5);
        m_heroConfig  = PersistentSingleton <Economies> .Instance.Heroes[HeroIndex];
        m_heroState   = HeroStateFactory.GetOrCreateHeroState(HeroIndex);
        Level         = m_heroState.Level;
        LifetimeLevel = m_heroState.LifetimeLevel;
        Tier          = m_heroState.Tier;
        Berries       = m_heroState.Berries;
        UnusedBerries = m_heroState.UnusedBerries;
        (from lvl in Level
         where lvl > LifetimeLevel.Value
         select lvl).Subscribe(delegate(int lvl)
        {
            LifetimeLevel.Value = lvl;
        }).AddTo(instance);
        Rank = (from tier in Tier
                select(int) Singleton <EconomyHelpers> .Instance.GetRank(tier)).TakeUntilDestroy(instance).ToReactiveProperty();
        LocalizedName      = new ReactiveProperty <string>(PersistentSingleton <LocalizationService> .Instance.Text("Companion.Name." + HeroIndex));
        LocalizedNameDesc  = new ReactiveProperty <string>(PersistentSingleton <LocalizationService> .Instance.Text("Companion.Name.Desc." + HeroIndex));
        MiniMilestoneTitle = new ReactiveProperty <string>(LocalizedName + " " + PersistentSingleton <LocalizationService> .Instance.Text("Attribute.Milestone") + "!");
        ChunkIndex         = new ReactiveProperty <int>(m_heroConfig.UnlockAtChunk);
        FoundOnce          = (from level in LifetimeLevel
                              select level >= 1).TakeUntilDestroy(instance).ToReactiveProperty();
        Found = (from level in Level
                 select level >= 1).TakeUntilDestroy(instance).ToReactiveProperty();
        IsNextLevelMilestone = (from lvl in Level
                                select Singleton <EconomyHelpers> .Instance.IsMilestone(heroIndex, lvl + 1)).TakeUntilDestroy(instance).ToReactiveProperty();
        UnlockedPerkCount = (from heroLevel in Level
                             select Singleton <EconomyHelpers> .Instance.GetUnlockedPerkCount(heroLevel)).TakeUntilDestroy(instance).ToReactiveProperty();
        PerkUnlockTriggered = (from pair in UnlockedPerkCount.Pairwise()
                               where pair.Previous != pair.Current
                               where pair.Current > 0
                               select new PerkUnlockedInfo(HeroIndex, pair.Current - 1)).TakeUntilDestroy(instance).ToSequentialReadOnlyReactiveProperty();
        if (heroIndex > 0)
        {
            (from _ in PerkUnlockTriggered
             where LifetimeLevel.Value > Level.Value
             select _).Subscribe(delegate(PerkUnlockedInfo perk)
            {
                IngameNotifications.InstantiatePerkNotification(perk);
            }).AddTo(instance);
        }
        MiniMilestoneTriggered = (from lvl in Level.Pairwise()
                                  select Singleton <EconomyHelpers> .Instance.GetMiniMilestoneOrNull(HeroIndex, lvl.Previous, lvl.Current) into cfg
                                  where cfg != null
                                  select cfg).TakeUntilDestroy(instance).ToSequentialReadOnlyReactiveProperty();
        MiniMilestoneText = MiniMilestoneTriggered.Select(delegate(BonusMultConfig cfg)
        {
            if (IngameNotifications.CurrentHeroIndex == HeroIndex && IngameNotifications.CurrentNotification != null && IngameNotifications.CurrentNotification.activeSelf)
            {
                m_currentMiniMilestoneMultiplier *= cfg.Amount;
                return(GetMilestoneString(cfg.BonusType, m_currentMiniMilestoneMultiplier));
            }
            m_currentMiniMilestoneMultiplier = cfg.Amount;
            return(GetMilestoneString(cfg.BonusType, m_currentMiniMilestoneMultiplier));
        }).TakeUntilDestroy(instance).ToSequentialReadOnlyReactiveProperty();
        MiniMilestoneText.Subscribe(delegate
        {
            IngameNotifications.InstantiateMiniMilestoneNotification(this);
        }).AddTo(instance);
        HeroTierUpgradeTriggered = (from pair in Tier.Pairwise()
                                    where pair.Previous != pair.Current
                                    select HeroIndex).TakeUntilDestroy(instance).ToSequentialReadOnlyReactiveProperty();
        MilestoneProgress = (from level in Level
                             select Singleton <EconomyHelpers> .Instance.GetMilestoneProgress(level)).TakeUntilDestroy(instance).ToReactiveProperty();
        BerryProgress = (from tier_berry in Tier.CombineLatest(Berries, (int tier, int berries) => new
        {
            tier,
            berries
        })
                         select Singleton <EconomyHelpers> .Instance.GetBerryProgress(tier_berry.tier, tier_berry.berries)).TakeUntilDestroy(instance).ToReactiveProperty();
        BerryRequirement = (from tier_berry in Tier.CombineLatest(Berries, (int tier, int berries) => new
        {
            tier,
            berries
        })
                            select Singleton <EconomyHelpers> .Instance.GetBerryRequirementText(tier_berry.tier, tier_berry.berries)).TakeUntilDestroy(instance).ToReactiveProperty();
        TierUpAvailable = (from berry_tier in Berries.CombineLatest(UnusedBerries, (int berries, int unused) => berries + unused).CombineLatest(Tier, (int berries, int tier) => new
        {
            berries,
            tier
        })
                           select berry_tier.berries >= Singleton <EconomyHelpers> .Instance.GetTierBerryDeltaReq(berry_tier.tier)).TakeUntilDestroy(instance).ToReactiveProperty();
        NextMilestoneText = (from lvl in Level
                             where lvl >= 1
                             select Singleton <EconomyHelpers> .Instance.GetNextMilestoneText(HeroIndex, lvl)).TakeUntilDestroy(instance).ToReactiveProperty();
    }
Ejemplo n.º 17
0
    public AdRunner()
    {
        Singleton <PropertyManager> .Instance.AddRootContext(this);

        SceneLoader instance = SceneLoader.Instance;

        AdReady = PersistentSingleton <AdService> .Instance.AdReady;
        PersistentSingleton <AdService> .Instance.AdResults.Do(delegate
        {
        }).Subscribe(delegate
        {
            ShowPending.Value = false;
        }).AddTo(instance);

        AdFailed = (from res in PersistentSingleton <AdService> .Instance.AdResults
                    where res.result == AdService.V2PShowResult.Failed
                    select res into _
                    select true).ToSequentialReadOnlyReactiveProperty();
        AdSkipped = (from res in PersistentSingleton <AdService> .Instance.AdResults
                     where res.result == AdService.V2PShowResult.Skipped
                     select res into _
                     select true).ToSequentialReadOnlyReactiveProperty();
        AdFinished = (from res in PersistentSingleton <AdService> .Instance.AdResults
                      where res.result == AdService.V2PShowResult.Finished
                      select res into _
                      select true).ToSequentialReadOnlyReactiveProperty();
        AdPlacementFailed = (from res in PersistentSingleton <AdService> .Instance.AdResults
                             where res.result == AdService.V2PShowResult.Failed
                             select res into ad
                             select ad.placement).ToSequentialReadOnlyReactiveProperty();
        AdPlacementSkipped = (from res in PersistentSingleton <AdService> .Instance.AdResults
                              where res.result == AdService.V2PShowResult.Skipped
                              select res into ad
                              select ad.placement).ToSequentialReadOnlyReactiveProperty();
        AdPlacementFinished = (from res in PersistentSingleton <AdService> .Instance.AdResults
                               where res.result == AdService.V2PShowResult.Finished
                               select res into ad
                               select ad.placement).ToSequentialReadOnlyReactiveProperty();
        AdPlacementFinished.Subscribe(delegate(AdPlacement watched)
        {
            PlayerData.Instance.AdsInSession++;
            PlayerData.Instance.AdsInLifetime++;
            AdFrequencyConfig adFrequencyConfig = PersistentSingleton <Economies> .Instance.AdFrequencies.Find((AdFrequencyConfig s) => s.Placement == watched);
            if (adFrequencyConfig != null && (adFrequencyConfig.DailyCap < 100 || adFrequencyConfig.Cooldown > 0))
            {
                if (adFrequencyConfig.DailyCap >= 100)
                {
                    for (int num = PlayerData.Instance.AdsWatched.Count - 1; num >= 0; num--)
                    {
                        if (PlayerData.Instance.AdsWatched[num].Placement == watched)
                        {
                            PlayerData.Instance.AdsWatched.RemoveAt(num);
                        }
                    }
                }
                PlayerData.Instance.AdsWatched.Add(new AdHistory(ServerTimeService.NowTicks(), watched));
            }
        }).AddTo(instance);
        PersistentSingleton <SessionService> .Instance.newSession.Subscribe(delegate
        {
            PlayerData.Instance.AdsInSession = 0;
        }).AddTo(instance);
    }
Ejemplo n.º 18
0
    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);
        }
    }
Ejemplo n.º 19
0
 public void Init(IObservable <string> obs)
 {
     _property = new ReadOnlyReactiveProperty <string> (obs);
     _property.Subscribe(_ => _history.PushText(_));
 }
Ejemplo n.º 20
0
        // FIXME: VMでやることじゃない
        public AxisStandardViewModel(
            INativeWindowManager nativeWindowManager,
            IScreenManager screenManager,
            IAudioManager audioManager,
            IVersionRepository versionRepository,
            ISettingService settingService)
        {
            settings              = settingService.Instance();
            Vertical              = BindSettings(settings.Vertical, nameof(settings.Vertical));
            Horizontal            = BindSettings(settings.Horizontal, nameof(settings.Horizontal));
            WindowFittingStandard = BindSettings(settings.WindowFittingStandard, nameof(settings.WindowFittingStandard));
            MuteCondition         = BindSettings(settings.MuteCondition, nameof(settings.MuteCondition));
            TargetApplicationName = BindSettings(settings.TargetApplicationName, nameof(TargetApplicationName));
            LatestVersion         = new ReactiveProperty <string>("");

            UseCurrentVerticalUserSetting   = BindSettings(settings.UseCurrentVerticalUserSetting, nameof(settings.UseCurrentVerticalUserSetting), ReactivePropertyMode.RaiseLatestValueOnSubscribe);
            UseCurrentHorizontalUserSetting = BindSettings(settings.UseCurrentHorizontalUserSetting, nameof(settings.UseCurrentHorizontalUserSetting), ReactivePropertyMode.RaiseLatestValueOnSubscribe);
            UserDefinedVerticalWindowRect   = BindSettings(settings.UserDefinedVerticalWindowRect, nameof(settings.UserDefinedVerticalWindowRect));
            UserDefinedHorizontalWindowRect = BindSettings(settings.UserDefinedHorizontalWindowRect, nameof(settings.UserDefinedHorizontalWindowRect));
            IsMostTop      = BindSettings(settings.IsMostTop, nameof(settings.IsMostTop));
            IsRemoveBorder = BindSettings(settings.IsRemoveBorder, nameof(settings.IsRemoveBorder));

            // FIXME: PollingじゃなくてGlobalHookとかでやりたい
            targetWindowHandle = Observable.Interval(TimeSpan.FromSeconds(5))
                                 .CombineLatest(TargetApplicationName)
                                 .Select(x => nativeWindowManager.GetWindowHandle(x.Second))
                                 .Distinct()
                                 .ToReadOnlyReactiveProperty();

            // FIXME: TargetApplicationNameが変わってもThreadが変わって動かなくなるわ…
            Disposable.Add(TargetApplicationName.Subscribe(x => nativeWindowManager.SetHook(x)));
            Disposable.Add(targetWindowHandle.Subscribe(x => nativeWindowManager.SetTargetProcessHandler(x)));

            var observableBorderChanged = Observable.FromEventPattern(nativeWindowManager, nameof(nativeWindowManager.OnBorderChanged)).StartWith(new object[] { null });
            var observableOnMoveChanged = Observable.FromEventPattern(nativeWindowManager, nameof(nativeWindowManager.OnMoveOrSizeChanged)).Throttle(TimeSpan.FromMilliseconds(200)).StartWith(new object[] { null });

            var windowRect = targetWindowHandle
                             .CombineLatest(
                observableOnMoveChanged,
                observableBorderChanged.Delay(TimeSpan.FromMilliseconds(500))
                )
                             .Select(x =>
            {
                if (x.First == IntPtr.Zero)
                {
                    return(WindowRect.Empty, WindowRect.Empty);
                }
                var windowClientRectPair = nativeWindowManager.GetWindowRect(x.First);
                var(r, _) = windowClientRectPair;
                if (r.IsEmpty)
                {
                    return(WindowRect.Empty, WindowRect.Empty);
                }
                return(windowClientRectPair);
            });

            Disposable.Add(UseCurrentHorizontalUserSetting.Subscribe(x =>
            {
                if (!x)
                {
                    return;
                }
                var handle = targetWindowHandle.Value;
                if (handle == IntPtr.Zero)
                {
                    return;
                }
                var(r, _) = nativeWindowManager.GetWindowRect(handle);
                if (r.IsEmpty)
                {
                    UserDefinedHorizontalWindowRect.Value = WindowRect.Empty;
                    return;
                }
                UserDefinedHorizontalWindowRect.Value = r;
                return;
            }));

            Disposable.Add(UseCurrentVerticalUserSetting.Subscribe(x =>
            {
                if (!x)
                {
                    return;
                }
                var handle = targetWindowHandle.Value;
                if (handle == IntPtr.Zero)
                {
                    return;
                }
                var(r, _) = nativeWindowManager.GetWindowRect(handle);
                if (r.IsEmpty)
                {
                    UserDefinedVerticalWindowRect.Value = WindowRect.Empty;
                    return;
                }
                UserDefinedVerticalWindowRect.Value = r;
                return;
            }));

            Disposable.Add(targetWindowHandle.CombineLatest(
                               MuteCondition,
                               Observable.CombineLatest(
                                   Observable.FromEventPattern <bool>(nativeWindowManager, nameof(nativeWindowManager.OnForeground))
                                   .Select(x => x.EventArgs.ToDefaultableBooleanLike()).StartWith(DefaultableBooleanLike.Default),
                                   Observable.FromEventPattern <bool>(nativeWindowManager, nameof(nativeWindowManager.OnMinimized))
                                   .Select(x => x.EventArgs.ToDefaultableBooleanLike()).StartWith(DefaultableBooleanLike.Default)
                                   )
                               .DistinctUntilChanged()
                               .Select(x =>
            {
                var maybeForeground = x[0];
                var maybeMinimized  = x[1];
                return((maybeForeground, maybeMinimized) switch
                {
                    (DefaultableBooleanLike.Default, DefaultableBooleanLike.Default) => ApplicationState.Foreground,
                    (DefaultableBooleanLike.Default, DefaultableBooleanLike.True) => ApplicationState.Minimized,
                    (DefaultableBooleanLike.Default, DefaultableBooleanLike.False) => ApplicationState.Background,
                    (DefaultableBooleanLike.True, DefaultableBooleanLike.Default) => ApplicationState.Foreground,
                    (DefaultableBooleanLike.True, DefaultableBooleanLike.True) => ApplicationState.Minimized,
                    (DefaultableBooleanLike.True, DefaultableBooleanLike.False) => ApplicationState.Foreground,
                    (DefaultableBooleanLike.False, DefaultableBooleanLike.Default) => ApplicationState.Background,
                    (DefaultableBooleanLike.False, DefaultableBooleanLike.True) => ApplicationState.Minimized,
                    (DefaultableBooleanLike.False, DefaultableBooleanLike.False) => ApplicationState.Background
                });
            })
	void Awake () {
		select_subscription = selected_scores.Subscribe((s)=>{
			if (s != null){
				if (date_time != null)
					date_time.text = s.time.date_recorded_local().ToString();
				//Yeah, it's ugly abuse of static variables, but I'll fix it later.
				score = s;
				MenuStateMachine.fsm.trigger_transition("scores->details");
			}
		});
		
		rx_player_name = rx_score.SelectMany(s=>{
			if (s == null)
				return Observable.Never<String>();
			return s.rx_player_name.AsObservable();
		}).CombineLatest(LanguageController.controller.rx_load_text("score_default_name"), (name, default_name)=>{
			if (IsNullOrWhiteSpace(name))
				return default_name;
			return name;
		}).ToReadOnlyReactiveProperty<string>();
		
		rx_player_name.Subscribe(t=>{
			if (player_name != null)
				player_name.text = t;
		});
	}
	void Start () {
		if (component != null)
			score = component.score_data;
		if (win == null)
			win = GameSettingsComponent.working_rules.win_condition;
			
		if (id_text != null || id_text_3d != null){
			rx_id_text = LanguageController.controller.rx_load_text("basket_single")
				.CombineLatest(rx_score.SelectMany(rx_score.SelectMany(s=>s.rx_id)), (text, id)=>{
					return text+" #"+id.ToString();
				}).ToReadOnlyReactiveProperty<string>();
			rx_id_text.Subscribe((text)=>{
				if (id_text != null)
					id_text.text = text;
				if (id_text_3d != null)
					id_text_3d.text = text;
			});
		}
		
		if (count != null || count_3d != null){
			rx_count_text = rx_score
				.SelectMany(s=>s.rx_count)
				.Select(value=>value.ToString())
				.ToReadOnlyReactiveProperty<string>();
			rx_count_text.Subscribe((text)=>{
				if (count != null)
					count.text = text;
				if (count_3d != null)
					count_3d.text = text;
			});
		}
		
		if (weight != null || weight_3d != null){
			rx_weight_text = rx_score
				.SelectMany(s=>s.rx_weight)
				.Select(value=>value.ToString("0.00"))
				.ToReadOnlyReactiveProperty<string>();
			rx_weight_text.Subscribe((text)=>{
				if (weight != null)
					weight.text = text;
				if (weight_3d != null)
					weight_3d.text = text;
			});
		}
		
		condition = rx_score.SelectMany(s=>{
			return s.rx_weight.CombineLatest(s.rx_overflow, (w,overflow)=>{
				return new UniRx.Tuple<float,bool>(w,overflow);
			});
		}).CombineLatest (rx_win, (tuple, wc) => {
			float w = tuple.Item1;
			bool overflow = tuple.Item2;
			if (overflow){
				return BasketCondition.Overflow;
			}
			if (wc.basket_weight.is_accept(w)){
				return BasketCondition.Accepted;
			} else {
				if (wc.basket_weight.is_over(w)){
					return BasketCondition.Overweight;
				} else {
					return BasketCondition.Underweight;
				}
			}
		}).ToReadOnlyReactiveProperty<BasketCondition>();
		
		rx_with_win = rx_score.CombineLatest(rx_win, (s, w)=>{
			return new UniRx.Tuple<BasketSingleScore, GameSettings.WinCondition>(s,w);
		});
		rx_with_win.Subscribe((tuple)=>{
			if (flat_score_text != null){
				ScoreDetailedForm.format_score_text(flat_score_text, tuple.Item2.evaluate_basket_flat(tuple.Item1));
			}
			if (range_score_text != null){
				ScoreDetailedForm.format_score_text(range_score_text, tuple.Item2.evaluate_basket_range(tuple.Item1));
			}
			if (total_score_text != null){
				ScoreDetailedForm.format_score_text(total_score_text, tuple.Item2.evaluate_basket(tuple.Item1));
			}
		});
		
		rx_tooltip_text = condition.Select(c=>language_keys[c]).ToReadOnlyReactiveProperty<string>();
		rx_tooltip_text.Subscribe((key)=>{
			if (tooltip != null){
				tooltip.key = key;
			}
		});
		
		rx_sprite = condition.Select(c=>sprites[c]).ToReadOnlyReactiveProperty<Sprite>();
		rx_sprite.Subscribe ((sprite) => {
			if (icon != null)
				icon.sprite = sprite;
			if (icon_3d != null)
				icon_3d.sprite = sprite;
		});
		
		if (opacity != null){
			opacity.opacity = off_opacity;
		}
	}
Ejemplo n.º 23
0
 public IDisposable Subscribe(IObserver <T> observer)
 {
     return(m_Inner.Subscribe(observer));
 }