using System.Collections; using System.Collections.Generic; using System.IO; using UnityEngine; using UnityEngine.Networking; using UnityEngine.UI; // 選歌:左右切換曲包、選難度、看個人最高分 / 排行榜、開始 // 格子:(0,5) 分數 (1..3,5) 難度 (4,5) 排行 | (2,3) 目前難度 | (1,2) 上一首 (2,2) 開始 (3,2) 下一首 // 上方:返回、代碼下載、管理(刪除曲包、資料夾位置) public class ChoosePage : Page, ILibraryListener { private readonly string downloadCode; // 由網站連結(rhyculator://pack/)開啟時自動下載 private IReadOnlyList songs; private int index, level; private string selectId; // 下載完成後要選的曲包 private RectTransform songView, emptyView; private RawImage cover; private Text nameText, artistText, countText; private readonly Dictionary covers = new Dictionary(); private AudioClip previewClip; private int previewGen; private float previewStart, previewEnd; private Dialog download; public ChoosePage(string downloadCode = null) { this.downloadCode = downloadCode; } private SongInfo Song => songs != null && songs.Count > 0 ? songs[index] : null; public override void Enter() { App.Music.Stop(); SongClock.Stop(); var back = Ui.Button(Top, "返回", () => App.Go(new MainPage()), 40); Ui.Place((RectTransform)back.transform, new Vector2(0, 1), new Vector2(40, -30), new Vector2(200, 100)); var dl = Ui.Button(Top, "代碼下載", () => ShowDownload(""), 40); Ui.Place((RectTransform)dl.transform, new Vector2(1, 1), new Vector2(-260, -30), new Vector2(260, 100)); var more = Ui.Button(Top, "管理", ShowManage, 40); Ui.Place((RectTransform)more.transform, new Vector2(1, 1), new Vector2(-40, -30), new Vector2(200, 100)); BuildSongView(); BuildEmptyView(); level = PlayerPrefs.GetInt(Prefs.Level, 1); LibraryChanged(); if (!string.IsNullOrEmpty(downloadCode)) ShowDownload(downloadCode, autoStart: true); } void BuildSongView() { songView = Ui.Stretch(Ui.Rect(Top, "Song")); countText = Ui.Label(songView, "", 34, Ui.Muted); Ui.Place(countText.rectTransform, new Vector2(0.5f, 1), new Vector2(-60, -55), new Vector2(300, 50)); // 封面:在按鈕列與文字之間,保持正方形 var box = Ui.Stretch(Ui.Rect(songView, "CoverBox"), 40, 150, 40, 160); cover = Ui.Rect(box, "Cover").gameObject.AddComponent(); cover.raycastTarget = false; var fit = cover.gameObject.AddComponent(); fit.aspectMode = AspectRatioFitter.AspectMode.FitInParent; fit.aspectRatio = 1; nameText = Ui.Label(songView, "", 50, Color.white); nameText.fontStyle = FontStyle.Bold; nameText.horizontalOverflow = HorizontalWrapMode.Wrap; nameText.resizeTextForBestFit = true; nameText.resizeTextMinSize = 30; nameText.resizeTextMaxSize = 50; nameText.verticalOverflow = VerticalWrapMode.Truncate; Ui.Place(nameText.rectTransform, new Vector2(0.5f, 0), new Vector2(0, 70), new Vector2(1000, 75)); artistText = Ui.Label(songView, "", 36, Ui.Muted); Ui.Place(artistText.rectTransform, new Vector2(0.5f, 0), new Vector2(0, 15), new Vector2(1000, 55)); } void BuildEmptyView() { emptyView = Ui.Stretch(Ui.Rect(Top, "Empty"), 60, 0, 60, 150); var col = Ui.Column(emptyView, 30); Ui.Stretch(col); col.GetComponent().childAlignment = TextAnchor.MiddleCenter; Ui.Label(col, "還沒有任何曲包", 56, Color.white); Ui.Label(col, $"把曲包 .zip 放進\n{DisplayPath(PackStorage.PackageDir)}\n或輸入曲包網站上的代碼下載", 36, Ui.Muted); var row = Ui.Height(Ui.Row(col, 30), 110); Ui.Button(row, "輸入代碼", () => ShowDownload(""), 40, primary: true); Ui.Button(row, "曲包網站", () => Application.OpenURL(ServerConfig.GameServerUrl + "/"), 40); } // 手機路徑顯示成使用者在檔案管理員看到的樣子 public static string DisplayPath(string path) { const string sd = "/storage/emulated/0/"; return path.StartsWith(sd) ? "內部儲存空間/" + path.Substring(sd.Length) : path; } public void LibraryChanged() { string keep = selectId ?? Song?.id ?? Library.Current?.id; songs = Library.Songs; index = 0; for (int i = 0; i < songs.Count; i++) if (songs[i].id == keep) index = i; if (selectId != null && Library.Find(selectId) != null) selectId = null; ShowSong(); } void ShowSong() { var song = Song; songView.gameObject.SetActive(song != null); emptyView.gameObject.SetActive(song == null && Library.Loaded); Grid.ClearAll(); StopPreview(); if (song == null) return; Library.Current = song; if (!song.HasLevel(level)) level = song.FirstLevel(); PlayerPrefs.SetInt(Prefs.Level, level); countText.text = songs.Count > 1 ? $"{index + 1} / {songs.Count}" : ""; nameText.text = song.name; artistText.text = string.IsNullOrEmpty(song.charter) ? song.artist : $"{song.artist} · 譜面 {song.charter}"; cover.texture = LoadCover(song); cover.enabled = cover.texture != null; bool many = songs.Count > 1; Grid.SetIcon(1, 2, many ? Sprites.Get("ArrowLeft") : null); Grid.SetIcon(3, 2, many ? Sprites.Get("ArrowRight") : null); Grid.SetIcon(2, 2, Sprites.Get("Start")); Grid.SetIcon(0, 5, Sprites.Get("Score")); Grid.SetIcon(4, 5, Sprites.Get("Rank")); for (int l = 1; l <= SongInfo.LevelCount; l++) Grid.SetLabel(l, 5, song.HasLevel(l) ? LevelText(song, l) : null, Ui.LevelColors[l]); ShowLevel(); App.StartCoroutine(PlayPreview(song)); } void ShowLevel() { Grid.SetLabel(2, 3, LevelText(Song, level), Ui.LevelColors[level], 0.6f); } static string LevelText(SongInfo song, int l) => song.levelNum[l] > 0 ? song.levelNum[l].ToString() : "?"; Texture2D LoadCover(SongInfo song) { string key = song.dir; if (covers.TryGetValue(key, out var cached)) return cached; Texture2D tex = null; try { if (File.Exists(song.ImagePath)) { tex = new Texture2D(2, 2, TextureFormat.RGBA32, false); if (!tex.LoadImage(File.ReadAllBytes(song.ImagePath))) { Object.Destroy(tex); tex = null; } } } catch (System.Exception e) { Debug.LogWarning($"[Choose] 封面讀取失敗 {song.id}:{e.Message}"); } covers[key] = tex; return tex; } // ---------- 試聽 ---------- IEnumerator PlayPreview(SongInfo song) { int gen = ++previewGen; yield return new WaitForSecondsRealtime(0.25f); // 快速切換時不必每首都載入 string path = song.MusicPath; if (gen != previewGen || path == null) yield break; AudioClip clip; using (var www = PlayPage.LoadAudio(path)) { yield return www.SendWebRequest(); if (gen != previewGen) yield break; if (www.result != UnityWebRequest.Result.Success) { Debug.LogWarning("[Choose] 試聽載入失敗:" + www.error); yield break; } clip = DownloadHandlerAudioClip.GetContent(www); } if (clip == null) yield break; StopPreview(destroyOnly: true); previewClip = clip; previewStart = Mathf.Clamp(song.previewStartMs / 1000f, 0f, Mathf.Max(0f, clip.length - 1f)); previewEnd = song.previewLengthMs > 0 ? Mathf.Min(clip.length, previewStart + song.previewLengthMs / 1000f) : clip.length; var music = App.Music; music.clip = clip; music.loop = true; music.time = previewStart; music.Play(); } void StopPreview(bool destroyOnly = false) { if (!destroyOnly) previewGen++; App.Music.Stop(); if (previewClip != null) { if (App.Music.clip == previewClip) App.Music.clip = null; Object.Destroy(previewClip); previewClip = null; } } // ---------- 操作 ---------- public override void Tick(List touches) { // 試聽片段循環 var music = App.Music; if (previewClip != null && music.isPlaying && previewEnd > previewStart && music.time >= previewEnd) music.time = previewStart; foreach (var t in touches) { if (!t.OnCell) continue; Grid.Flash(t.x, t.y, CellFlash.White); if (t.began) Tap(t.x, t.y); } } void Tap(int x, int y) { var song = Song; if (song == null) return; if (y == 2 && (x == 1 || x == 3) && songs.Count > 1) { index = (index + (x == 1 ? songs.Count - 1 : 1)) % songs.Count; ShowSong(); } else if (y == 5 && x >= 1 && x <= SongInfo.LevelCount && song.HasLevel(x)) { level = x; PlayerPrefs.SetInt(Prefs.Level, level); ShowLevel(); } else if (y == 5 && x == 0) App.StartCoroutine(ShowScore(song, level)); else if (y == 5 && x == 4) App.StartCoroutine(ShowRank(song, level)); else if (y == 2 && x == 2) { Grid.Flash(x, y, CellFlash.Blue); App.Go(new PlayPage(song, level)); } } IEnumerator ShowScore(SongInfo song, int lv) { if (!Prefs.LoggedIn) { Info("個人最高分", "登入後才會記錄成績"); yield break; } Api.Response r = null; yield return Api.Game(new Dictionary { ["request"] = "score", ["uid"] = Prefs.UserId, ["song"] = song.id, ["level"] = lv, }, x => r = x); Info($"個人最高分 · {SongInfo.LevelName(lv)}", r.error ?? r.Int("score").ToString()); } IEnumerator ShowRank(SongInfo song, int lv) { Api.Response r = null; yield return Api.Game(new Dictionary { ["request"] = "rank", ["song"] = song.id, ["level"] = lv, }, x => r = x); if (r.error != null) { Info("排行榜", r.error); yield break; } // 伺服器以 null 表示該名次無人 var sb = new System.Text.StringBuilder(); for (int i = 1; i <= 5; i++) { string name = r.Str($"name_{i}"); if (string.IsNullOrEmpty(name)) break; sb.Append($"{i}. {name} {r.Int($"score_{i}")}\n"); } Info($"排行榜 · {SongInfo.LevelName(lv)}", sb.Length > 0 ? sb.ToString().TrimEnd() : "尚無紀錄"); } void Info(string title, string text) { var d = new Dialog(App.Overlay, title, text); d.message.fontSize = 48; d.AddClose("關閉"); } // ---------- 下載 ---------- void ShowDownload(string code, bool autoStart = false) { if (download != null && download.IsOpen) download.Close(); var d = download = new Dialog(App.Overlay, "以代碼下載曲包", "輸入曲包網站上的 8 碼代碼"); var input = Ui.Height(Ui.Input(d.body, "例如 e4hfbqcg", UnityEngine.UI.InputField.ContentType.Alphanumeric, 56), 120); input.characterLimit = 8; input.text = code; var status = Ui.Label(d.body, "", 38, Ui.Muted); Button go = null; d.AddClose("取消"); go = d.AddButton("下載", () => App.StartCoroutine(RunDownload(d, input, status, go)), primary: true); if (autoStart && code.Length > 0) App.StartCoroutine(RunDownload(d, input, status, go)); } IEnumerator RunDownload(Dialog d, InputField input, Text status, Button go) { string code = input.text.Trim().ToLowerInvariant(); if (code.Length != 8) { status.text = "代碼是 8 個英數字"; yield break; } go.interactable = false; input.interactable = false; d.cancellable = false; string error = null, title = null; yield return Api.DownloadPack(code, p => status.text = $"下載中… {p * 100:0}%", (e, t) => { error = e; title = t; }); d.cancellable = true; go.interactable = true; input.interactable = true; if (error != null) { status.text = $"{error}"; yield break; } selectId = code; d.Close(); Toast.Show($"已下載「{title}」"); } // ---------- 管理 ---------- void ShowManage() { var song = Song; var d = new Dialog(App.Overlay, "曲包管理", $"曲包資料夾:\n{DisplayPath(PackStorage.PackageDir)}\n共 {songs.Count} 個曲包"); if (song != null) { Ui.Height(Ui.Button(d.body, $"刪除「{song.name}」", () => ConfirmDelete(d, song), 40), 110); } Ui.Height(Ui.Button(d.body, "開啟曲包網站", () => Application.OpenURL(ServerConfig.GameServerUrl + "/"), 40), 110); d.AddClose("關閉"); } void ConfirmDelete(Dialog manage, SongInfo song) { var d = new Dialog(App.Overlay, "刪除曲包?", $"「{song.name}」\n{Path.GetFileName(song.source)}\n會從曲包資料夾刪除"); d.AddClose("取消"); d.AddClose("刪除", () => { manage.Close(); if (PackStorage.DeleteSource(song)) { Toast.Show($"已刪除「{song.name}」"); Library.Rescan(); } else Toast.Show("刪除失敗"); }, primary: true); } public override void Back() => App.Go(new MainPage()); public override void Exit() { StopPreview(); foreach (var t in covers.Values) if (t != null) Object.Destroy(t); covers.Clear(); } }