- One empty scene; App builds the canvas, safe-area layout and a shared 5x6 Grid in code. Pages (Intro, Main, Choose, Play, Account, Settings) replace 5 scenes, 5 prefabs and the per-cell spawner/display components. - Packs: the game reads Rhyculator/package/ (with All files access) or the app folder, like a plugged-in USB stick. Zips stay where they are and are extracted to a cache keyed by name/size/mtime; folders are read directly. Scans run every second on a background thread. Old songs/ imports and inbox zips are migrated automatically. - Download packs by 8-char code from the new pack website, or via rhyculator://pack/<code> links; opened/shared zips go into the package folder. - Play: pause/resume/retry, auto-pause on background, combo and progress bar; judging and scoring unchanged. Choose page fits 9:16 screens; empty state, pack delete. Android back key handled everywhere. - Slimming: removed TextMesh Pro, unused 2D/Timeline/VisualScripting/etc. packages and modules, scene template, unused sprites; menu theme wav (20MB) -> ogg (2.3MB). Build profile replaced by explicit settings in BuildAndroid. - Tests: PackLibrary/PackReader/migration/serializer tests (39 passing). Co-Authored-By: Claude Opus 5.5 <[email protected]>
394 lines
14 KiB
C#
394 lines
14 KiB
C#
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/<code>)開啟時自動下載
|
||
|
||
private IReadOnlyList<SongInfo> songs;
|
||
private int index, level;
|
||
private string selectId; // 下載完成後要選的曲包
|
||
|
||
private RectTransform songView, emptyView;
|
||
private RawImage cover;
|
||
private Text nameText, artistText, countText;
|
||
private readonly Dictionary<string, Texture2D> covers = new Dictionary<string, Texture2D>();
|
||
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<RawImage>();
|
||
cover.raycastTarget = false;
|
||
var fit = cover.gameObject.AddComponent<AspectRatioFitter>();
|
||
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<VerticalLayoutGroup>().childAlignment = TextAnchor.MiddleCenter;
|
||
Ui.Label(col, "還沒有任何曲包", 56, Color.white);
|
||
Ui.Label(col, $"把曲包 .zip 放進\n<color=#FF66C4>{DisplayPath(PackStorage.PackageDir)}</color>\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<GridTouch> 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<string, object>
|
||
{
|
||
["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<string, object>
|
||
{
|
||
["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} <color=#FFFFFF>{r.Int($"score_{i}")}</color>\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 = "<color=#FF6060>代碼是 8 個英數字</color>";
|
||
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 = $"<color=#FF6060>{error}</color>";
|
||
yield break;
|
||
}
|
||
selectId = code;
|
||
d.Close();
|
||
Toast.Show($"已下載「{title}」");
|
||
}
|
||
|
||
// ---------- 管理 ----------
|
||
|
||
void ShowManage()
|
||
{
|
||
var song = Song;
|
||
var d = new Dialog(App.Overlay, "曲包管理",
|
||
$"曲包資料夾:\n<color=#FF66C4>{DisplayPath(PackStorage.PackageDir)}</color>\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();
|
||
}
|
||
}
|