Exemple #1
0
 private void Awake()
 {
     canvasGroup.alpha = 0;
     collapseButton.onPointerClick.AddListener(_ =>
     {
         if (!isCollapsed)
         {
             isCollapsed         = true;
             collapseIcon.sprite = expandSprite;
             contentHolder.Leave();
         }
         else
         {
             isCollapsed         = false;
             collapseIcon.sprite = compressSprite;
             contentHolder.Enter();
         }
     });
     autoplayRadioGroup.onSelect.AddListener(it =>
     {
         var value = bool.Parse(it);
         if (value)
         {
             game.State.Mods.Add(Mod.Auto);
         }
         else
         {
             game.State.Mods.Remove(Mod.Auto);
         }
     });
     decreaseMoreButton.onPointerClick.AddListener(it => ChangeGameNoteOffset(-0.05f));
     decreaseButton.onPointerClick.AddListener(it => ChangeGameNoteOffset(-0.01f));
     increaseButton.onPointerClick.AddListener(it => ChangeGameNoteOffset(+0.01f));
     increaseMoreButton.onPointerClick.AddListener(it => ChangeGameNoteOffset(+0.05f));
     game.onGameLoaded.AddListener(it =>
     {
         if (game.State.Mode != GameMode.Calibration)
         {
             Destroy(gameObject);
         }
         else
         {
             offset = game.Level.Record.RelativeNoteOffset;
             UpdateOffsetText();
             canvasGroup.alpha = 1;
             transitionElement.UseCurrentStateAsDefault();
             transitionElement.Enter();
             contentHolder.UseCurrentStateAsDefault();
             contentHolder.Enter();
             game.onGameCompleted.AddListener(_ => transitionElement.Leave());
             game.onGameAborted.AddListener(_ => transitionElement.Leave());
             game.onGameRetried.AddListener(_ => transitionElement.Leave());
             autoplayRadioGroup.Select("true", false);
             game.State.Mods.Add(Mod.Auto);
             transform.RebuildLayout();
         }
     });
 }
    public override async void OnScreenBecameActive()
    {
        base.OnScreenBecameActive();
        ProfileWidget.Instance.Enter();
        ScreenCenter = new Vector2(UnityEngine.Screen.width / 2f, UnityEngine.Screen.height / 2f);
        var height  = RectTransform.rect.height;
        var padding = scrollRectContentLayoutGroup.padding;

        padding.top = padding.bottom = (int)((height - 576) / 2f);  // TODO: Un-hardcode tier card height but I'm lazy lol
        scrollRectContentLayoutGroup.padding = padding;

        if (LoadedContent == null)
        {
            SpinnerOverlay.Show();
            await Context.LevelManager.LoadLevelsOfType(LevelType.Tier);

            RestClient.Get(new RequestHelper
            {
                Uri     = $"{Context.ApiUrl}/seasons/alpha",
                Headers = Context.OnlinePlayer.GetRequestHeaders(),
                Timeout = 5,
            }).Then(res =>
            {
                print("TierSelection: " + res.Text);
                var season    = JsonConvert.DeserializeObject <SeasonMeta>(res.Text);
                LoadedContent = new Content {
                    Season = season
                };
                OnContentLoaded(LoadedContent);
                Run.After(0.4f, () =>
                {
                    icons.Enter();
                    SpinnerOverlay.Hide();
                });
            }).CatchRequestError(error =>
            {
                if (!error.IsNetworkError)
                {
                    throw error;
                }

                SpinnerOverlay.Hide();
                Dialog.PromptGoBack("DIALOG_COULD_NOT_CONNECT_TO_SERVER".Get());
            });
        }
        else
        {
            SpinnerOverlay.Show();
            OnContentLoaded(LoadedContent);
            Run.After(0.4f, () =>
            {
                icons.Enter();
                SpinnerOverlay.Hide();
            });
        }
    }
Exemple #3
0
    private async void EnterControls()
    {
        lowerLeftColumn.Enter();
        lowerRightColumn.Enter();

        if (Context.Distribution == Distribution.TapTap && Context.Player.ShouldOneShot("Tips: Calibration"))
        {
            Dialog.PromptAlert("<b>提示:</b>\n如果感觉手感不对劲的话,有可能需要设置谱面偏移。可以在准备界面的设置菜单中进入校正模式。");
        }
        else if (ScoreGrades.From(gameState.Score) >= ScoreGrade.A)
        {
            Context.Player.BoostStoreReviewConfidence();
        }
    }
Exemple #4
0
 public void OnScreenBecameActive()
 {
     switch (this.GetScreenParent().GetId())
     {
     case ResultScreen.Id:
         // TODO: Big refactors needed lol
         if (!Context.Player.Settings.PlayRanked)
         {
             image.color = "#F953C6".ToColor().WithAlpha(0.7f);
             text.text   = "RESULT_MODE_PRACTICE".Get();
             transitionElement.Enter();
         }
         break;
     }
 }
Exemple #5
0
 protected void Awake()
 {
     canvasGroup.alpha        = normalOpacity;
     canvasGroup.interactable = false;
     game.onGameLoaded.AddListener(game =>
     {
         if (game.State.Mode != GameMode.Tier)
         {
             canvasGroup.interactable = true;
             game.onGameCompleted.AddListener(_ =>
             {
                 transitionElement.leaveTo = Transition.Default;
                 transitionElement.Leave();
             });
             game.onGamePaused.AddListener(_ =>
             {
                 transitionElement.leaveTo = Transition.Default;
                 transitionElement.Leave();
             });
             game.onGameUnpaused.AddListener(_ =>
             {
                 canvasGroup.alpha           = normalOpacity;
                 transitionElement.enterFrom = Transition.Default;
                 transitionElement.Enter();
             });
             interactableMonoBehavior.onPointerClick.AddListener(_ =>
             {
                 if (!highlighted)
                 {
                     Highlight();
                 }
                 else
                 {
                     Unhighlight();
                     Context.Haptic(HapticTypes.LightImpact, true);
                     game.Pause();
                 }
             });
         }
         else
         {
             canvasGroup.alpha        = 0;
             canvasGroup.interactable = false;
         }
     });
 }
    protected override void OnRendered()
    {
        base.OnRendered();

        scrollRect.GetComponent <TransitionElement>()
        .Let(it =>
        {
            it.Leave(false, true);
            it.Enter();
        });

        icons.Leave(false, true);
        if (LoadedPayload.Collection.owner.Uid != Context.OfficialAccountId)
        {
            icons.Enter();
        }

        if (coverImage.sprite == null || coverImage.sprite.texture == null)
        {
            AddTask(async token =>
            {
                Sprite sprite;
                try
                {
                    sprite = await Context.AssetMemory.LoadAsset <Sprite>(LoadedPayload.Collection.cover.CoverUrl,
                                                                          AssetTag.CollectionCover, cancellationToken: token);
                }
                catch
                {
                    return;
                }

                if (sprite != null)
                {
                    coverImage.sprite = sprite;
                    coverImage.FitSpriteAspectRatio();
                    coverImage.DOColor(new Color(0.2f, 0.2f, 0.2f, 1), 0.4f);
                }
            });
        }
        else
        {
            coverImage.DOColor(new Color(0.2f, 0.2f, 0.2f, 1), 0.4f);
        }
    }
Exemple #7
0
 public void Enter()
 {
     if (transitionElement != null && enterTransitionElementOnEnter)
     {
         transitionElement.Leave(false, true);
         transitionElement.Enter();
     }
     loadedGameObject.GetComponent <AnimatedCharacter>()?.OnEnter();
     if (interactable)
     {
         var isInteracting = false;
         interactableMonoBehavior.onPointerClick.SetListener(async data =>
         {
             if (isInteracting || OnInteract == null)
             {
                 return;
             }
             isInteracting = true;
             await OnInteract.Invoke(data);
             isInteracting = false;
         });
     }
 }
    public void OnTierSelected(TierData tier)
    {
        SelectedTier = tier;
        print("Selected tier " + tier.Meta.name);

        if (tier.Meta.character != null)
        {
            lowerLeftColumn.Enter();
            rewardCharacterName.text = tier.Meta.character.Name;
        }

        if (!tier.locked)
        {
            lowerRightColumn.Enter();
            startButton.State = tier.StagesValid ? CircleButtonState.Start : CircleButtonState.Download;
            startButton.StartPulsing();
        }

        rankingsTab.UpdateTierRankings(SelectedTier.Id);
        initializedSettingsTab = false;

        LoadCover();
        LoadPreview();
    }
Exemple #9
0
    protected override async void Awake()
    {
        base.Awake();
        while (this != null)
        {
            await UniTask.WaitUntil(() => this == null || messages.Count > 0);

            if (this == null)
            {
                return;
            }

            if (transitionElement.IsShown)
            {
                transitionElement.Leave();
                await UniTask.WaitUntil(() => !transitionElement.IsInTransition);
            }
            var message = messages.Dequeue();
            text.text = message;

            transitionElement.Enter();
            await UniTask.WaitUntil(() => !transitionElement.IsInTransition);
        }
    }
Exemple #10
0
    public async void LoadCharacter(CharacterMeta meta)
    {
        ParallaxHolder.WillDelaySet = true;

        var isNewCharacter = Context.CharacterManager.ActiveCharacterBundleId != meta.AssetId;

        if (isNewCharacter)
        {
            SpinnerOverlay.Show();

            infoCard.Leave(false);
            characterTransitionElement.Leave(false);
        }

        var character = await Context.CharacterManager.SetActiveCharacter(meta.AssetId);

        if (character == null)
        {
            throw new Exception("Character not downloaded or corrupted");
        }

        if (isNewCharacter)
        {
            await UniTask.Delay(TimeSpan.FromSeconds(0.4f));
        }

        nameText.text = meta.Name;
        nameGradient.SetGradient(character.nameGradient.GetGradient());
        descriptionText.text = meta.Description;
        levelCard.SetModel(meta.Level.ToLevel(LevelType.User));
        illustratorText.text = meta.Illustrator.Name;
        illustratorProfileButton.onPointerClick.SetListener(_ => Application.OpenURL(meta.Illustrator.Url));
        if (meta.CharacterDesigner != null && !meta.CharacterDesigner.Name.IsNullOrEmptyTrimmed())
        {
            characterDesignerHolder.gameObject.SetActive(true);
            characterDesignerText.text = meta.CharacterDesigner.Name;
            characterDesignerProfileButton.onPointerClick.SetListener(_ =>
                                                                      Application.OpenURL(meta.CharacterDesigner.Url));
        }
        else
        {
            characterDesignerHolder.gameObject.SetActive(false);
        }
        infoCard.transform.RebuildLayout();

        if (character.musicAudio == null)
        {
            muteButtonImage.sprite = volumeSprite;
            muteButtonImage.SetAlpha(0.3f);
            muteButton.scaleOnClick = false;
            muteButton.onPointerClick.RemoveAllListeners();
        }
        else
        {
            muteButtonImage.sprite = Context.Player.Settings.PlayCharacterTheme ? volumeSprite : volumeMuteSprite;
            muteButtonImage.SetAlpha(1f);
            muteButton.scaleOnClick = true;
            muteButton.onPointerClick.SetListener(_ =>
            {
                Context.Player.Settings.PlayCharacterTheme = !Context.Player.Settings.PlayCharacterTheme;
                Context.Player.SaveSettings();
                LoopAudioPlayer.Instance.SetMainAudio(Context.Player.Settings.PlayCharacterTheme ? character.musicAudio : LoopAudioPlayer.Instance.defaultLoopAudio);
                muteButtonImage.sprite = Context.Player.Settings.PlayCharacterTheme ? volumeSprite : volumeMuteSprite;
            });
        }

        await characterDisplay.Load(CharacterAsset.GetTachieBundleId(meta.AssetId));

        NavigationBackdrop.Instance.UpdateBlur();

        infoCard.Enter();
        characterTransitionElement.Leave(false, true);
        characterTransitionElement.Enter();
        characterTransitionElement.Apply(it =>
        {
            it.enterMultiplier = 0.4f;
            it.enterDelay      = 0.4f;
            it.enterDuration   = 0.8f;
        });

        if (Context.IsOffline())
        {
            SpinnerOverlay.Hide();
        }
        else
        {
            RestClient.Post(new RequestHelper
            {
                Uri         = $"{Context.ApiUrl}/profile/{Context.Player.Id}/character",
                Headers     = Context.OnlinePlayer.GetRequestHeaders(),
                EnableDebug = true,
                Body        = new CharacterPostData
                {
                    characterId = meta.Id
                }
            })
            .CatchRequestError(error =>
            {
                Debug.LogError(error);
                Toast.Next(Toast.Status.Failure, "TOAST_FAILED_TO_UPDATE_PROFILE_CHARACTER".Get());
            })
            .Finally(() =>
            {
                SpinnerOverlay.Hide();
            });
        }

        ParallaxHolder.WillDelaySet = false;
    }
Exemple #11
0
    public void OnAction(Action action)
    {
        var prev            = CurrentActionIndex == -1 ? closeAction : Actions[CurrentActionIndex];
        var enterTransition = action.index < CurrentActionIndex ? Transition.Right : Transition.Left;
        var leaveTransition = action.index < CurrentActionIndex ? Transition.Left : Transition.Right;

        if (action.index == -1)
        {
            // Close
            tabBackground.Leave();
            Actions.ForEach(it =>
            {
                DOFade(it.icon, 1f, animationDuration);
                it.tabIndicator.leaveTo = leaveTransition;
                it.tabIndicator.Leave();
            });
            tabs.ForEach(it =>
            {
                it.leaveTo = Transition.Right; // TODO: Customize?
                it.Leave();
            });

            DOFade(closeAction.icon, 0, animationDuration);

            closeDetectionArea.DetectionEnabled      = false;
            tabBackground.canvasGroup.blocksRaycasts = false;
        }
        else
        {
            // Enter
            tabBackground.Enter();
            DOFade(action.icon, 1f, animationDuration);

            action.tabIndicator.enterFrom = enterTransition;
            action.tabIndicator.Enter();
            Actions.ForEach(it =>
            {
                if (it.index != action.index)
                {
                    DOFade(it.icon, 0.3f, animationDuration);
                    it.tabIndicator.leaveTo = leaveTransition;
                    it.tabIndicator.Leave();
                }
            });
            tabs[action.index].canvasGroup.blocksRaycasts = true;
            tabs[action.index].Enter();
            for (var index = 0; index < tabs.Count; index++)
            {
                if (index != action.index)
                {
                    tabs[index].canvasGroup.blocksRaycasts = false;
                    tabs[index].Leave();
                }
            }

            DOFade(closeAction.icon, 0.3f, animationDuration);

            closeDetectionArea.DetectionEnabled      = true;
            tabBackground.canvasGroup.blocksRaycasts = true;
        }
        CurrentActionIndex = action.index;
        onTabChanged.Invoke(prev, action);
    }
Exemple #12
0
    public override async void OnScreenBecameActive()
    {
        base.OnScreenBecameActive();

        tierState = Context.TierState;
        if (tierState == null)
        {
            tierState = new TierState(MockData.Season.tiers[0])
            {
                Combo             = 1,
                CurrentStageIndex = 0,
                Health            = 1000.0,
                IsFailed          = false,
                MaxCombo          = 1,
                Stages            = new[]
                {
                    new GameState()
                }
            };
            tierState.OnComplete();
        }
        Context.TierState = null;

        nextButton.State = CircleButtonState.Next;
        nextButton.StartPulsing();
        nextButton.interactableMonoBehavior.onPointerClick.SetListener(_ =>
        {
            Context.Haptic(HapticTypes.SoftImpact, true);
            nextButton.StopPulsing();
            Done();
        });
        retryButton.State = CircleButtonState.Retry;
        retryButton.interactableMonoBehavior.onPointerClick.SetListener(_ =>
        {
            Context.Haptic(HapticTypes.SoftImpact, true);
            retryButton.StopPulsing();
            Retry();
        });

        // Update performance info
        scoreText.text    = (Mathf.Floor((float)tierState.Completion * 100 * 100) / 100).ToString("0.00") + "%";
        accuracyText.text = "RESULT_X_ACCURACY".Get((Math.Floor(tierState.AverageAccuracy * 100 * 100) / 100).ToString("0.00"));
        if (Mathf.Approximately((float)tierState.AverageAccuracy, 1))
        {
            accuracyText.text = "RESULT_FULL_ACCURACY".Get();
        }
        maxComboText.text = "RESULT_X_COMBO".Get(tierState.MaxCombo);
        if (tierState.GradeCounts[NoteGrade.Bad] == 0 && tierState.GradeCounts[NoteGrade.Miss] == 0)
        {
            maxComboText.text = "RESULT_FULL_COMBO".Get();
        }

        var scoreGrade = ScoreGrades.FromTierCompletion(tierState.Completion);

        gradeText.text = scoreGrade.ToString();
        gradeText.GetComponent <GradientMeshEffect>().SetGradient(scoreGrade.GetGradient());
        if (scoreGrade == ScoreGrade.MAX || scoreGrade == ScoreGrade.SSS)
        {
            scoreText.GetComponent <GradientMeshEffect>().SetGradient(scoreGrade.GetGradient());
        }
        else
        {
            scoreText.GetComponent <GradientMeshEffect>().enabled = false;
        }

        standardMetricText.text = $"<b>Perfect</b> {tierState.GradeCounts[NoteGrade.Perfect]}    " +
                                  $"<b>Great</b> {tierState.GradeCounts[NoteGrade.Great]}    " +
                                  $"<b>Good</b> {tierState.GradeCounts[NoteGrade.Good]}    " +
                                  $"<b>Bad</b> {tierState.GradeCounts[NoteGrade.Bad]}    " +
                                  $"<b>Miss</b> {tierState.GradeCounts[NoteGrade.Miss]}";
        advancedMetricText.text = $"<b>Early</b> {tierState.EarlyCount}    " +
                                  $"<b>Late</b> {tierState.LateCount}    " +
                                  $"<b>{"RESULT_AVG_TIMING_ERR".Get()}</b> {tierState.AverageTimingError:0.000}s    " +
                                  $"<b>{"RESULT_STD_TIMING_ERR".Get()}</b> {tierState.StandardTimingError:0.000}s";
        if (!Context.Player.Settings.DisplayEarlyLateIndicators)
        {
            advancedMetricText.text = "";
        }

        newBestText.text = "";
        if (tierState.Completion >= 1)
        {
            if (tierState.Tier.completion < 1)
            {
                newBestText.text = "TIER_CLEARED".Get();
            }
            else
            {
                var historicBest = tierState.Tier.completion;
                var newBest      = tierState.Completion;
                if (newBest > historicBest)
                {
                    tierState.Tier.completion = tierState.Completion; // Update cached tier json
                    newBestText.text          =
                        $"+{(Mathf.FloorToInt((float) (newBest - historicBest) * 100 * 100) / 100f):0.00}%";
                }
            }
        }

        shareButton.onPointerClick.SetListener(_ => StartCoroutine(Share()));

        gradientPane.SetModel(tierState.Tier);
        for (var index = 0; index < Math.Min(tierState.Tier.Meta.parsedStages.Count, 3); index++)
        {
            var widget      = stageResultWidgets[index];
            var level       = tierState.Tier.Meta.parsedStages[index];
            var stageResult = tierState.Stages[index];
            widget.difficultyBall.SetModel(Difficulty.Parse(level.Meta.charts.Last().type), level.Meta.charts.Last().difficulty);
            widget.titleText.text = level.Meta.title;
            widget.performanceWidget.SetModel(new LevelRecord.Performance
            {
                Score = (int)stageResult.Score, Accuracy = stageResult.Accuracy
            });
        }

        ProfileWidget.Instance.Enter();
        upperRightColumn.Enter();

        UploadRecord();
    }
Exemple #13
0
 private void EnterControls()
 {
     lowerLeftColumn.Enter();
     lowerRightColumn.Enter();
 }
    public void LoadEvent(EventMeta meta)
    {
        async UniTask LoadCover(CancellationToken token)
        {
            Assert.IsNotNull(meta.cover);

            var tasks = new List <UniTask>();

            if (coverImage.sprite != null)
            {
                coverImage.DOKill();
                coverImage.DOColor(Color.black, 0.4f);
                tasks.Add(UniTask.Delay(TimeSpan.FromSeconds(0.4f), cancellationToken: token));
            }

            Sprite sprite = null;

            tasks.Add(Context.AssetMemory.LoadAsset <Sprite>(meta.cover.OriginalUrl, AssetTag.EventCover, cancellationToken: token).ContinueWith(result => sprite = result));

            try
            {
                await tasks;
            }
            catch (OperationCanceledException)
            {
                return;
            }

            coverImage.sprite = sprite;
            coverImage.FitSpriteAspectRatio();
            coverImage.DOColor(Color.white, 2f).SetDelay(0.8f);
        }

        async UniTask LoadLogo(CancellationToken token)
        {
            Assert.IsNotNull(meta.logo);

            var tasks = new List <UniTask>();

            if (logoImage.sprite != null)
            {
                logoImage.DOKill();
                logoImage.DOFade(0, 0.4f);
                tasks.Add(UniTask.Delay(TimeSpan.FromSeconds(0.4f), cancellationToken: token));
            }

            Sprite sprite = null;

            tasks.Add(Context.AssetMemory.LoadAsset <Sprite>(meta.logo.OriginalUrl, AssetTag.EventLogo, cancellationToken: token).ContinueWith(result => sprite = result));

            try
            {
                await tasks;
            }
            catch (OperationCanceledException)
            {
                return;
            }

            logoImage.sprite = sprite;
            logoImage.DOFade(1, 0.8f).SetDelay(0.4f);
        }

        AddTask(LoadCover);
        AddTask(LoadLogo);

        Context.Player.Settings.SeenEvents.Add(meta.uid);
        Context.Player.SaveSettings();

        infoBanner.Leave(onComplete: () =>
        {
            if (!Context.Player.Settings.ReadEventDetails.Contains(meta.uid))
            {
                viewDetailsNotification.Show();
            }
            viewDetailsButton.onPointerClick.SetListener(_ =>
            {
                Context.Player.Settings.ReadEventDetails.Add(meta.uid);
                Context.Player.SaveSettings();
                viewDetailsNotification.Hide();
                if (meta.url.IsNullOrEmptyTrimmed())
                {
                    Application.OpenURL($"{Context.WebsiteUrl}/posts/{meta.uid}");
                }
                else
                {
                    WebViewOverlay.Show(meta.url,
                                        onFullyShown: () =>
                    {
                        LoopAudioPlayer.Instance.FadeOutLoopPlayer();
                    },
                                        onFullyHidden: async() =>
                    {
                        AudioSettings.Reset(AudioSettings.GetConfiguration());
                        Context.AudioManager.Dispose();
                        Context.AudioManager.Initialize();
                        await UniTask.DelayFrame(5);
                        LoopAudioPlayer.Instance.Apply(it =>
                        {
                            it.FadeInLoopPlayer();
                            it.PlayAudio(it.PlayingAudio, forceReplay: true);
                        });
                    });
                }
            });
            const string dateFormat = "yyyy/MM/dd HH:mm";
            durationText.text       = (meta.startDate.HasValue ? meta.startDate.Value.LocalDateTime.ToString(dateFormat) : "")
                                      + "~"
                                      + (meta.endDate.HasValue ? meta.endDate.Value.LocalDateTime.ToString(dateFormat) : "");
            enterButton.onPointerClick.SetListener(_ =>
            {
                if (meta.locked)
                {
                    Context.Haptic(HapticTypes.Failure, true);
                    // TODO
                    return;
                }
                Context.Haptic(HapticTypes.SoftImpact, true);
                if (meta.levelId != null)
                {
                    SpinnerOverlay.Show();

                    RestClient.Get <OnlineLevel>(new RequestHelper
                    {
                        Uri = $"{Context.ApiUrl}/levels/{meta.levelId}"
                    }).Then(level =>
                    {
                        Context.ScreenManager.ChangeScreen(
                            GamePreparationScreen.Id, ScreenTransition.In, 0.4f,
                            transitionFocus: GetComponent <RectTransform>().GetScreenSpaceCenter(),
                            payload: new GamePreparationScreen.Payload {
                            Level = level.ToLevel(LevelType.User)
                        }
                            );
                    }).CatchRequestError(error =>
                    {
                        Debug.LogError(error);
                        Dialog.PromptAlert("DIALOG_COULD_NOT_CONNECT_TO_SERVER".Get());
                    }).Finally(() => SpinnerOverlay.Hide());
                }
                else if (meta.collectionId != null)
                {
                    Context.ScreenManager.ChangeScreen(
                        CollectionDetailsScreen.Id, ScreenTransition.In, 0.4f,
                        transitionFocus: GetComponent <RectTransform>().GetScreenSpaceCenter(),
                        payload: new CollectionDetailsScreen.Payload
                    {
                        CollectionId = meta.collectionId, Type = LevelType.User
                    }
                        );
                }
            });
            infoBanner.transform.RebuildLayout();
            infoBanner.Enter();
        });
    }
Exemple #15
0
    public override async void OnScreenBecameActive()
    {
        base.OnScreenBecameActive();

        gameState = Context.GameState;
        if (gameState == null)
        {
            // Test mode
            Debug.Log("Result not set, entering test mode...");

            gameState = new GameState(GameMode.Practice, Context.SelectedLevel, Context.SelectedDifficulty);
            Context.OnlinePlayer.OnAuthenticated.AddListener(() =>
            {
                rankingsTab.UpdateRankings(Context.SelectedLevel.Id, Context.SelectedDifficulty.Id);
                ratingTab.UpdateLevelRating(Context.SelectedLevel.Id);
                UploadRecord();
            });
        }

        Context.GameState = null;

        nextButton.State = CircleButtonState.Next;
        nextButton.StartPulsing();
        nextButton.interactableMonoBehavior.onPointerClick.SetListener(_ =>
        {
            Context.Haptic(HapticTypes.SoftImpact, true);
            nextButton.StopPulsing();
            Done();
        });
        retryButton.State = CircleButtonState.Retry;
        retryButton.interactableMonoBehavior.onPointerClick.SetListener(_ =>
        {
            Context.Haptic(HapticTypes.SoftImpact, true);
            retryButton.StopPulsing();
            Retry();
        });

        // Load translucent cover
        var path = "file://" + Context.SelectedLevel.Path + Context.SelectedLevel.Meta.background.path;

        TranslucentCover.Set(await Context.AssetMemory.LoadAsset <Sprite>(path, AssetTag.GameCover));
        NavigationBackdrop.Instance.Apply(it =>
        {
            it.IsBlurred = true;
            it.FadeBrightness(1, 0.8f);
        });

        // Update performance info
        scoreText.text    = Mathf.FloorToInt((float)gameState.Score).ToString("D6");
        accuracyText.text =
            "RESULT_X_ACCURACY".Get((Math.Floor(gameState.Accuracy * 100 * 100) / 100).ToString("0.00"));
        if (Mathf.Approximately((float)gameState.Accuracy, 1))
        {
            accuracyText.text = "RESULT_FULL_ACCURACY".Get();
        }

        maxComboText.text = "RESULT_X_COMBO".Get(gameState.MaxCombo);
        if (gameState.GradeCounts[NoteGrade.Bad] == 0 && gameState.GradeCounts[NoteGrade.Miss] == 0)
        {
            maxComboText.text = "RESULT_FULL_COMBO".Get();
        }

        var scoreGrade = ScoreGrades.From(gameState.Score);

        gradeText.text = scoreGrade.ToString();
        gradeText.GetComponent <GradientMeshEffect>().SetGradient(scoreGrade.GetGradient());
        if (scoreGrade == ScoreGrade.MAX || scoreGrade == ScoreGrade.SSS)
        {
            scoreText.GetComponent <GradientMeshEffect>().SetGradient(scoreGrade.GetGradient());
        }
        else
        {
            scoreText.GetComponent <GradientMeshEffect>().enabled = false;
        }

        standardMetricText.text = $"<b>Perfect</b> {gameState.GradeCounts[NoteGrade.Perfect]}    " +
                                  $"<b>Great</b> {gameState.GradeCounts[NoteGrade.Great]}    " +
                                  $"<b>Good</b> {gameState.GradeCounts[NoteGrade.Good]}    " +
                                  $"<b>Bad</b> {gameState.GradeCounts[NoteGrade.Bad]}    " +
                                  $"<b>Miss</b> {gameState.GradeCounts[NoteGrade.Miss]}";
        advancedMetricText.text = $"<b>Early</b> {gameState.EarlyCount}    " +
                                  $"<b>Late</b> {gameState.LateCount}    " +
                                  $"<b>{"RESULT_AVG_TIMING_ERR".Get()}</b> {gameState.AverageTimingError:0.000}s    " +
                                  $"<b>{"RESULT_STD_TIMING_ERR".Get()}</b> {gameState.StandardTimingError:0.000}s";
        if (!Context.Player.Settings.DisplayEarlyLateIndicators)
        {
            advancedMetricText.text = "";
        }

        var record = gameState.Level.Record;

        record.IncrementPlayCountByOne(gameState.Difficulty);
        newBestText.text = record.TrySaveBestPerformance(gameState.Mode, gameState.Difficulty, (int)gameState.Score, gameState.Accuracy);
        gameState.Level.SaveRecord();

        shareButton.onPointerClick.SetListener(_ => StartCoroutine(Share()));

        ProfileWidget.Instance.Enter();
        upperRightColumn.Enter();

        if (Context.IsOnline() && Context.OnlinePlayer.IsAuthenticated)
        {
            UploadRecord();
        }
        else
        {
            EnterControls();
        }

        if (Context.IsOnline())
        {
            rankingsIcon.SetActive(true);
            ratingIcon.SetActive(true);
            if (gameState.Mode == GameMode.Standard && !Context.OnlinePlayer.IsAuthenticated)
            {
                rankingsTab.UpdateRankings(gameState.Level.Id, gameState.Difficulty.Id);
            }
            ratingTab.UpdateLevelRating(gameState.Level.Id)
            .Then(it =>
            {
                if (it == null)
                {
                    return;
                }
                if (Context.OnlinePlayer.IsAuthenticated && it.rating <= 0 &&
                    ScoreGrades.From(gameState.Score) >= ScoreGrade.A)
                {
                    // Invoke the rate dialog
                    ratingTab.rateLevelElement.rateButton.onPointerClick.Invoke(null);
                }
            });
        }
        else
        {
            rankingsIcon.SetActive(false);
            ratingIcon.SetActive(false);
        }
    }
Exemple #16
0
    public async void SetModel(FullProfile profile)
    {
        Profile = profile;
        characterTransitionElement.Leave(false, true);
        characterTransitionElement.enterDuration = 1.2f;
        characterTransitionElement.enterDelay    = 0.4f;
        characterTransitionElement.onEnterStarted.SetListener(() =>
        {
            characterTransitionElement.enterDuration = 0.4f;
            characterTransitionElement.enterDelay    = 0;
        });

        avatar.SetModel(profile.User);
        levelProgressImage.fillAmount = (profile.Exp.TotalExp - profile.Exp.CurrentLevelExp)
                                        / (profile.Exp.NextLevelExp - profile.Exp.CurrentLevelExp);
        uidText.text = profile.User.Uid;

        void MarkOffline()
        {
            statusCircleImage.color = "#757575".ToColor();
            statusText.text         = "PROFILE_STATUS_OFFLINE".Get();
        }

        void MarkOnline()
        {
            statusCircleImage.color = "#47dc47".ToColor();
            statusText.text         = "PROFILE_STATUS_ONLINE".Get();
        }

        if (profile.User.Uid == Context.OnlinePlayer.LastProfile?.User.Uid)
        {
            if (Context.IsOffline())
            {
                MarkOffline();
            }
            else
            {
                MarkOnline();
            }
        }
        else
        {
            if (profile.LastActive == null)
            {
                MarkOffline();
            }
            else
            {
                var lastActive = profile.LastActive.Value.LocalDateTime;
                if (DateTime.Now - lastActive <= TimeSpan.FromMinutes(30))
                {
                    MarkOnline();
                }
                else
                {
                    statusCircleImage.color = "#757575".ToColor();
                    statusText.text         = "PROFILE_STATUS_LAST_SEEN_X".Get(lastActive.Humanize());
                }
            }
        }

        if (profile.Tier == null)
        {
            tierText.transform.parent.gameObject.SetActive(false);
        }
        else
        {
            tierText.transform.parent.gameObject.SetActive(true);
            tierText.text = profile.Tier.name;
            tierGradient.SetGradient(new ColorGradient(profile.Tier.colorPalette.background));
        }
        ratingText.text            = $"{"PROFILE_WIDGET_RATING".Get()} {profile.Rating:0.00}";
        levelText.text             = $"{"PROFILE_WIDGET_LEVEL".Get()} {profile.Exp.CurrentLevel}";
        expText.text               = $"{"PROFILE_WIDGET_EXP".Get()} {(int) profile.Exp.TotalExp}/{(int) profile.Exp.NextLevelExp}";
        totalRankedPlaysText.text  = profile.Activities.TotalRankedPlays.ToString("N0");
        totalClearedNotesText.text = profile.Activities.ClearedNotes.ToString("N0");
        highestMaxComboText.text   = profile.Activities.MaxCombo.ToString("N0");
        avgRankedAccuracyText.text = ((profile.Activities.AverageRankedAccuracy ?? 0) * 100).ToString("0.00") + "%";
        totalRankedScoreText.text  = (profile.Activities.TotalRankedScore ?? 0).ToString("N0");
        totalPlayTimeText.text     = TimeSpan.FromSeconds(profile.Activities.TotalPlayTime)
                                     .Let(it => it.ToString(it.Days > 0 ? @"d\d\ h\h\ m\m\ s\s" : @"h\h\ m\m\ s\s"));

        chartRadioGroup.onSelect.SetListener(type => UpdateChart((ChartType)Enum.Parse(typeof(ChartType), type, true)));
        UpdateChart(ChartType.AvgRating);

        pillRows.ForEach(it => LayoutFixer.Fix(it));
        if (Context.IsOnline())
        {
            var eventBadges = profile.GetEventBadges();
            if (eventBadges.Any())
            {
                badgeGrid.gameObject.SetActive(true);
                badgeGrid.SetModel(eventBadges);
            }
            else
            {
                badgeGrid.gameObject.SetActive(false);
            }
        }

        foreach (Transform child in recordSection.recordCardHolder)
        {
            Destroy(child.gameObject);
        }
        foreach (Transform child in levelSection.levelCardHolder)
        {
            Destroy(child.gameObject);
        }
        foreach (Transform child in collectionSection.collectionCardHolder)
        {
            Destroy(child.gameObject);
        }

        if (profile.RecentRecords.Count > 0)
        {
            recordSection.gameObject.SetActive(true);
            foreach (var record in profile.RecentRecords.Take(6))
            {
                var recordCard = Instantiate(recordCardPrefab, recordSection.recordCardHolder);
                recordCard.SetModel(new RecordView {
                    DisplayOwner = false, Record = record
                });
            }
        }
        else
        {
            recordSection.gameObject.SetActive(false);
        }

        if (profile.LevelCount > 0)
        {
            levelSection.gameObject.SetActive(true);
            foreach (var level in profile.Levels.Take(6))
            {
                var levelCard = Instantiate(levelCardPrefab, levelSection.levelCardHolder);
                levelCard.SetModel(new LevelView {
                    DisplayOwner = false, Level = level.ToLevel(LevelType.User)
                });
            }

            viewAllLevelsButton.GetComponentInChildren <Text>().text = "PROFILE_VIEW_ALL_X".Get(profile.LevelCount);
            viewAllLevelsButton.onPointerClick.SetListener(_ =>
            {
                Context.ScreenManager.ChangeScreen(CommunityLevelSelectionScreen.Id, ScreenTransition.In, 0.4f,
                                                   transitionFocus: ((RectTransform)viewAllLevelsButton.transform).GetScreenSpaceCenter(),
                                                   payload: new CommunityLevelSelectionScreen.Payload
                {
                    Query = new OnlineLevelQuery {
                        owner = profile.User.Uid, category = "all", sort = "creation_date", order = "desc"
                    },
                });
            });
            if (profile.FeaturedLevelCount > 0)
            {
                viewAllFeaturedLevelsButton.gameObject.SetActive(true);
                viewAllFeaturedLevelsButton.GetComponentInChildren <Text>().text =
                    "PROFILE_VIEW_FEATURED_X".Get(profile.FeaturedLevelCount);
                viewAllFeaturedLevelsButton.onPointerClick.SetListener(_ =>
                {
                    Context.ScreenManager.ChangeScreen(CommunityLevelSelectionScreen.Id, ScreenTransition.In, 0.4f,
                                                       transitionFocus: ((RectTransform)viewAllFeaturedLevelsButton.transform).GetScreenSpaceCenter(),
                                                       payload: new CommunityLevelSelectionScreen.Payload
                    {
                        Query = new OnlineLevelQuery {
                            owner = profile.User.Uid, category = "featured", sort = "creation_date", order = "desc"
                        },
                    });
                });
            }
            else
            {
                viewAllFeaturedLevelsButton.gameObject.SetActive(false);
            }

            viewAllLevelsButton.transform.parent.RebuildLayout();
        }
        else
        {
            levelSection.gameObject.SetActive(false);
        }

        if (profile.CollectionCount > 0)
        {
            collectionSection.gameObject.SetActive(true);
            foreach (var collection in profile.Collections.Take(6))
            {
                var collectionCard = Instantiate(collectionCardPrefab, collectionSection.collectionCardHolder);
                collectionCard.SetModel(collection);
            }
        }
        else
        {
            collectionSection.gameObject.SetActive(false);
        }

        LayoutFixer.Fix(sectionParent);

        await UniTask.DelayFrame(5);

        transform.RebuildLayout();

        await UniTask.DelayFrame(0);

        characterTransitionElement.Enter();
    }