Rebuild the game as a single code-driven scene with a package-folder pack source

- 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]>
This commit is contained in:
SahikandClaude Opus 5.5 committed 2026-10-24 14:18:54 +08:00
1 parent 6d5f66ac6a
commit ddd5fdc28b
295 files changed
+3854 -82126

No files matched your search

+8
View File
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 2f79f2e28cd6f3d47bd5cc15aabb36a9
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
+25
View File
@@ -0,0 +1,25 @@
using System.Collections.Generic;
// 延遲校正的計算(純函式,方便測試)
public static class CalibrationMath
{
// 點擊時間對最近一拍的偏差;超出半拍或屬於暖身拍則回傳 false
public static bool TryBeatDelta(double tapTime, double firstBeat, double interval, int beatCount, int warmupBeats, out double delta)
{
delta = 0;
int i = (int)System.Math.Round((tapTime - firstBeat) / interval);
if (i < warmupBeats || i >= beatCount) return false;
delta = tapTime - (firstBeat + i * interval);
return System.Math.Abs(delta) < interval / 2;
}
// 中位數(比平均值不受誤觸影響)
public static double Median(List<double> values)
{
if (values == null || values.Count == 0) return 0;
var sorted = new List<double>(values);
sorted.Sort();
int n = sorted.Count;
return n % 2 == 1 ? sorted[n / 2] : (sorted[n / 2 - 1] + sorted[n / 2]) / 2;
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 21855371daac8a148b883bb46c4b43ce
+80
View File
@@ -0,0 +1,80 @@
using System;
using System.Collections.Generic;
using System.IO;
// 譜面展開後的一個事件(slide 的每一格各是一個事件)
public struct ChartEvent
{
public double hitTime; // 判定時間(秒,已含曲包的 offset)
public string type; // tap / hold / slide
public int x, y;
public int holdMs;
}
// 讀取 Maker 統一格式的譜面:
// {"format":1,"divisor":4,"notes":[{"t":1216,"lane":"L","type":"tap","pos":{"x":0,"y":3}}, ...]}
// lane / locked 是製譜用的欄位,遊戲忽略;沒有座標、座標超出格子、型別不認識的音符略過並計入 skipped
public static class ChartLoader
{
public const int Columns = 5;
public const int Rows = 6;
public static List<ChartEvent> LoadFile(string path, int offsetMs, out int skipped)
=> Parse(File.ReadAllText(path), offsetMs, out skipped);
public static List<ChartEvent> Parse(string json, int offsetMs, out int skipped)
{
skipped = 0;
var events = new List<ChartEvent>();
object root = MiniJson.Parse(json);
// 也接受只有 notes 陣列的檔案
var notes = MiniJson.AsList(root) ?? MiniJson.AsList(MiniJson.Get(MiniJson.AsObject(root), "notes"));
if (notes == null) throw new FormatException("譜面缺少 notes 陣列");
double offset = offsetMs / 1000.0;
foreach (var item in notes)
{
var n = MiniJson.AsObject(item);
if (n == null || !MiniJson.TryGetNumber(n, "t", out double tMs)) { skipped++; continue; }
string type = MiniJson.GetString(n, "type", "tap");
double t = tMs / 1000.0 + offset;
bool hasEnd = MiniJson.TryGetNumber(n, "end", out double endMs);
if (type == "slide")
{
var cells = new List<(int x, int y)>();
var path = MiniJson.AsList(MiniJson.Get(n, "path"));
if (path != null)
foreach (var p in path)
if (TryCell(MiniJson.AsObject(p), out int cx, out int cy)) cells.Add((cx, cy));
if (cells.Count == 0) { skipped++; continue; }
// 路徑的格子平均分布在 t ~ end:第一格在 t、最後一格在 end
double end = hasEnd ? endMs / 1000.0 + offset : t;
double interval = cells.Count > 1 ? (end - t) / (cells.Count - 1) : 0;
for (int i = 0; i < cells.Count; i++)
events.Add(new ChartEvent { hitTime = t + interval * i, type = "slide", x = cells[i].x, y = cells[i].y });
}
else if (type == "tap" || type == "hold")
{
if (!TryCell(MiniJson.AsObject(MiniJson.Get(n, "pos")), out int x, out int y)) { skipped++; continue; }
int holdMs = type == "hold" && hasEnd ? (int)Math.Max(0, endMs - tMs) : 0;
events.Add(new ChartEvent { hitTime = t, type = type, x = x, y = y, holdMs = holdMs });
}
else skipped++;
}
events.Sort((a, b) => a.hitTime.CompareTo(b.hitTime));
return events;
}
private static bool TryCell(Dictionary<string, object> pos, out int x, out int y)
{
x = y = 0;
if (pos == null) return false;
if (!MiniJson.TryGetNumber(pos, "x", out double dx) || !MiniJson.TryGetNumber(pos, "y", out double dy)) return false;
x = (int)dx;
y = (int)dy;
return x >= 0 && x < Columns && y >= 0 && y < Rows;
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: a41b742a3c95c084a8044f32b0692b89
+239
View File
@@ -0,0 +1,239 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
// 精簡 JSON 讀取器:物件 → Dictionary<string, object>、陣列 → List<object>、
// 數字 → double、字串 → string、true/false → bool、null → null
// 曲包譜面的 pos / path / end / locked 都是「可有可無」的欄位,JsonUtility 會把缺少的巢狀物件
// 填成預設值,分不出「沒有座標」和「座標 (0,0)」,所以自己解析
public static class MiniJson
{
public static object Parse(string json)
{
if (json == null) throw new FormatException("JSON 為空");
var p = new Parser(json);
p.SkipWhitespace();
object v = p.ParseValue();
p.SkipWhitespace();
if (!p.AtEnd) throw p.Error("結尾有多餘的內容");
return v;
}
public static Dictionary<string, object> AsObject(object v) => v as Dictionary<string, object>;
public static List<object> AsList(object v) => v as List<object>;
public static object Get(Dictionary<string, object> obj, string key)
=> obj != null && obj.TryGetValue(key, out var v) ? v : null;
public static string GetString(Dictionary<string, object> obj, string key, string fallback = null)
=> Get(obj, key) is string s ? s : fallback;
public static bool TryGetNumber(Dictionary<string, object> obj, string key, out double value)
{
if (Get(obj, key) is double d) { value = d; return true; }
value = 0;
return false;
}
public static double GetNumber(Dictionary<string, object> obj, string key, double fallback = 0)
=> TryGetNumber(obj, key, out var d) ? d : fallback;
public static int GetInt(Dictionary<string, object> obj, string key, int fallback = 0)
=> TryGetNumber(obj, key, out var d) ? (int)Math.Round(d) : fallback;
public static bool GetBool(Dictionary<string, object> obj, string key, bool fallback = false)
=> Get(obj, key) is bool b ? b : fallback;
// 輸出 JSON(伺服器請求用):支援 Dictionary、IList、字串、數字、bool、null
public static string Serialize(object value)
{
var sb = new StringBuilder();
Write(sb, value);
return sb.ToString();
}
private static void Write(StringBuilder sb, object v)
{
switch (v)
{
case null: sb.Append("null"); break;
case string s: WriteString(sb, s); break;
case bool b: sb.Append(b ? "true" : "false"); break;
case int or long or short: sb.Append(Convert.ToInt64(v).ToString(CultureInfo.InvariantCulture)); break;
case float or double: sb.Append(Convert.ToDouble(v).ToString("R", CultureInfo.InvariantCulture)); break;
case IDictionary<string, object> d:
sb.Append('{');
bool first = true;
foreach (var kv in d)
{
if (!first) sb.Append(',');
first = false;
WriteString(sb, kv.Key);
sb.Append(':');
Write(sb, kv.Value);
}
sb.Append('}');
break;
case System.Collections.IList list:
sb.Append('[');
for (int i = 0; i < list.Count; i++)
{
if (i > 0) sb.Append(',');
Write(sb, list[i]);
}
sb.Append(']');
break;
default: WriteString(sb, v.ToString()); break;
}
}
private static void WriteString(StringBuilder sb, string s)
{
sb.Append('"');
foreach (char c in s)
{
switch (c)
{
case '"': sb.Append("\\\""); break;
case '\\': sb.Append("\\\\"); break;
case '\n': sb.Append("\\n"); break;
case '\r': sb.Append("\\r"); break;
case '\t': sb.Append("\\t"); break;
default:
if (c < 0x20) sb.Append("\\u").Append(((int)c).ToString("x4"));
else sb.Append(c);
break;
}
}
sb.Append('"');
}
private class Parser
{
private readonly string s;
private int i;
public Parser(string s) { this.s = s; }
public bool AtEnd => i >= s.Length;
public FormatException Error(string msg) => new FormatException($"JSON 第 {i} 個字元:{msg}");
public void SkipWhitespace()
{
while (i < s.Length && (s[i] == ' ' || s[i] == '\t' || s[i] == '\n' || s[i] == '\r')) i++;
}
public object ParseValue()
{
if (AtEnd) throw Error("內容不完整");
char c = s[i];
switch (c)
{
case '{': return ParseObject();
case '[': return ParseArray();
case '"': return ParseString();
case 't': Expect("true"); return true;
case 'f': Expect("false"); return false;
case 'n': Expect("null"); return null;
default:
if (c == '-' || (c >= '0' && c <= '9')) return ParseNumber();
throw Error($"無法解析 '{c}'");
}
}
private void Expect(string word)
{
if (string.CompareOrdinal(s, i, word, 0, word.Length) != 0) throw Error($"預期 {word}");
i += word.Length;
}
private Dictionary<string, object> ParseObject()
{
var obj = new Dictionary<string, object>();
i++; // {
SkipWhitespace();
if (i < s.Length && s[i] == '}') { i++; return obj; }
while (true)
{
SkipWhitespace();
if (AtEnd || s[i] != '"') throw Error("物件的鍵必須是字串");
string key = ParseString();
SkipWhitespace();
if (AtEnd || s[i] != ':') throw Error("缺少 ':'");
i++;
SkipWhitespace();
obj[key] = ParseValue();
SkipWhitespace();
if (AtEnd) throw Error("物件未結束");
if (s[i] == ',') { i++; continue; }
if (s[i] == '}') { i++; return obj; }
throw Error("物件內預期 ',' 或 '}'");
}
}
private List<object> ParseArray()
{
var list = new List<object>();
i++; // [
SkipWhitespace();
if (i < s.Length && s[i] == ']') { i++; return list; }
while (true)
{
SkipWhitespace();
list.Add(ParseValue());
SkipWhitespace();
if (AtEnd) throw Error("陣列未結束");
if (s[i] == ',') { i++; continue; }
if (s[i] == ']') { i++; return list; }
throw Error("陣列內預期 ',' 或 ']'");
}
}
private string ParseString()
{
i++; // 開頭的引號
var sb = new StringBuilder();
while (true)
{
if (AtEnd) throw Error("字串未結束");
char c = s[i++];
if (c == '"') return sb.ToString();
if (c != '\\') { sb.Append(c); continue; }
if (AtEnd) throw Error("字串未結束");
char e = s[i++];
switch (e)
{
case '"': sb.Append('"'); break;
case '\\': sb.Append('\\'); break;
case '/': sb.Append('/'); break;
case 'b': sb.Append('\b'); break;
case 'f': sb.Append('\f'); break;
case 'n': sb.Append('\n'); break;
case 'r': sb.Append('\r'); break;
case 't': sb.Append('\t'); break;
case 'u':
if (i + 4 > s.Length) throw Error("\\u 跳脫不完整");
sb.Append((char)int.Parse(s.Substring(i, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture));
i += 4;
break;
default: throw Error($"不支援的跳脫 \\{e}");
}
}
}
private double ParseNumber()
{
int start = i;
if (s[i] == '-') i++;
while (i < s.Length && IsNumberChar(s[i])) i++;
string token = s.Substring(start, i - start);
if (!double.TryParse(token, NumberStyles.Float, CultureInfo.InvariantCulture, out double d))
throw Error($"數字格式錯誤 '{token}'");
return d;
}
private static bool IsNumberChar(char c)
=> (c >= '0' && c <= '9') || c == '.' || c == 'e' || c == 'E' || c == '+' || c == '-';
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 756aef3f2685f5641bfea1d649343619
+39
View File
@@ -0,0 +1,39 @@
// 判定:以「按下時間 - 音符時間」決定結果(秒)
// 時間窗沿用舊版以動畫縮放判定時的手感:Perfect ±50ms、Fast/Slow ±130ms、Bad ±200ms
public enum Judgement
{
None, // 不在判定範圍內(太早),不處理
Perfect,
Fast,
Slow,
Bad,
Miss // 音符過期沒按到
}
public static class NoteJudge
{
public const double PerfectWindow = 0.050;
public const double GreatWindow = 0.130;
public const double BadWindow = 0.200;
public static Judgement Evaluate(double delta)
{
double abs = System.Math.Abs(delta);
if (abs <= PerfectWindow) return Judgement.Perfect;
if (abs <= GreatWindow) return delta < 0 ? Judgement.Fast : Judgement.Slow;
if (abs <= BadWindow) return Judgement.Bad;
return delta > 0 ? Judgement.Miss : Judgement.None;
}
public static int Score(Judgement j)
{
switch (j)
{
case Judgement.Perfect: return 212;
case Judgement.Fast:
case Judgement.Slow: return 159;
case Judgement.Bad: return 53;
default: return 0;
}
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: f85fc10a56e03644bb72ae9bbecbc66d
+157
View File
@@ -0,0 +1,157 @@
using System;
using System.Collections.Generic;
using System.IO;
// 曲包來源:package 資料夾(像插上的隨身碟一樣,裡面有什麼就玩什麼)
// package/*.zip 曲包 zip:解壓到快取資料夾再讀取,zip 本身不動
// package/<資料夾>/ 已解開的曲包(資料夾內直接有 config.json),直接讀取
// 快取以「檔名 + 大小 + 修改時間」區分,zip 被換掉或刪掉時快取跟著更新 / 清除
// 不使用 UnityEngine,可在背景執行緒與 EditMode 測試中使用
public static class PackLibrary
{
public class ScanResult
{
public readonly List<SongInfo> songs = new List<SongInfo>();
public readonly List<string> errors = new List<string>(); // 這次新發現的錯誤(同一個檔案只回報一次)
public readonly List<SongInfo> added = new List<SongInfo>(); // 和上次相比新出現的曲包
public bool changed; // 曲包清單有變
public bool pending; // 有檔案還在寫入,晚點再掃
}
// 剛修改過的 zip 可能還在複製中(USB、瀏覽器下載),先跳過
public static TimeSpan SettleTime = TimeSpan.FromSeconds(2);
private static readonly HashSet<string> reported = new HashSet<string>();
private static string lastSignature = "";
private static HashSet<string> lastSources = null;
public static ScanResult Scan(string packageDir, string cacheDir)
{
var r = new ScanResult();
Directory.CreateDirectory(packageDir);
Directory.CreateDirectory(cacheDir);
var found = new List<SongInfo>();
var usedCache = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var nowReported = new HashSet<string>();
foreach (var zip in Directory.GetFiles(packageDir, "*.zip"))
{
var fi = new FileInfo(zip);
if (DateTime.UtcNow - fi.LastWriteTimeUtc < SettleTime) { r.pending = true; continue; }
string key = CacheKey(fi);
string dir = Path.Combine(cacheDir, key);
usedCache.Add(key);
try
{
SongInfo s = File.Exists(Path.Combine(dir, SongInfo.ConfigName))
? SongInfo.FromDir(dir)
: PackReader.Extract(zip, dir);
s.source = zip;
found.Add(s);
}
catch (Exception e)
{
Report(r, nowReported, key, $"{fi.Name}:{PackReader.Describe(e)}");
}
}
foreach (var dir in Directory.GetDirectories(packageDir))
{
if (!File.Exists(Path.Combine(dir, SongInfo.ConfigName))) continue;
string name = Path.GetFileName(dir);
try
{
var s = SongInfo.FromDir(dir);
if (s.MusicPath == null) throw new PackReader.PackException("缺少音樂");
if (s.FirstLevel() == 0) throw new PackReader.PackException("沒有任何難度的譜面");
s.source = dir;
found.Add(s);
}
catch (Exception e)
{
Report(r, nowReported, "dir:" + dir + Directory.GetLastWriteTimeUtc(dir).Ticks, $"{name}:{PackReader.Describe(e)}");
}
}
// 同一個 id 只留最新的來源
found.Sort((a, b) => LastWrite(b.source).CompareTo(LastWrite(a.source)));
var ids = new Dictionary<string, SongInfo>();
foreach (var s in found)
{
if (ids.TryGetValue(s.id, out var kept))
{
Report(r, nowReported, "dup:" + s.source, $"{Path.GetFileName(s.source)} 和 {Path.GetFileName(kept.source)} 的 id 相同({s.id}),只使用較新的");
continue;
}
ids[s.id] = s;
r.songs.Add(s);
}
r.songs.Sort((a, b) => string.Compare(a.name, b.name, StringComparison.OrdinalIgnoreCase));
// 只保留仍有錯誤的紀錄:檔案修好或刪掉後再壞掉會再回報一次
reported.IntersectWith(nowReported);
// 清掉沒用到的快取
foreach (var dir in Directory.GetDirectories(cacheDir))
{
string name = Path.GetFileName(dir);
if (name.EndsWith(".tmp") || !usedCache.Contains(name))
{
try { Directory.Delete(dir, true); } catch { }
}
}
var sources = new HashSet<string>();
var sig = new System.Text.StringBuilder();
foreach (var s in r.songs)
{
sources.Add(s.source);
sig.Append(s.source).Append('|').Append(s.dir).Append('\n');
}
r.changed = sig.ToString() != lastSignature;
if (lastSources != null)
foreach (var s in r.songs)
if (!lastSources.Contains(s.source)) r.added.Add(s);
lastSignature = sig.ToString();
lastSources = sources;
return r;
}
// 重設「上次掃描」的紀錄(換了 package 資料夾、測試用)
public static void ResetState()
{
reported.Clear();
lastSignature = "";
lastSources = null;
}
private static void Report(ScanResult r, HashSet<string> nowReported, string key, string message)
{
nowReported.Add(key);
if (reported.Add(key)) r.errors.Add(message);
}
private static DateTime LastWrite(string path)
=> File.Exists(path) ? File.GetLastWriteTimeUtc(path) : Directory.GetLastWriteTimeUtc(path);
// 快取資料夾名稱:檔名(去掉不安全字元)+ 大小與修改時間的雜湊
public static string CacheKey(FileInfo fi)
{
string name = Path.GetFileNameWithoutExtension(fi.Name);
var safe = new System.Text.StringBuilder();
foreach (char c in name)
safe.Append(char.IsLetterOrDigit(c) && c < 128 ? char.ToLowerInvariant(c) : '-');
string s = safe.ToString();
if (s.Length > 32) s = s.Substring(0, 32);
ulong h = 14695981039346656037UL; // FNV-1a
foreach (char c in $"{fi.Name}|{fi.Length}|{fi.LastWriteTimeUtc.Ticks}")
{
h ^= c;
h *= 1099511628211UL;
}
return $"{s}-{h:x16}";
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 7ff7d094ad9b04649a25edb101c020e3
+107
View File
@@ -0,0 +1,107 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
// 曲包(.zip)檢查與解壓。曲包格式見 RhyculatorMaker 的 README
// 不使用 UnityEngine,可在背景執行緒與 EditMode 測試中使用
public static class PackReader
{
public class PackException : Exception
{
public PackException(string message) : base(message) { }
}
// 只解出這些檔名;zip 內其他東西一律忽略(也避免 zip 內的路徑寫到別處)
private static readonly HashSet<string> Allowed = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
SongInfo.ConfigName, SongInfo.ImageName, SongInfo.VideoName,
"easy.json", "normal.json", "hard.json",
"music.ogg", "music.wav", "music.mp3",
};
private const long MaxEntryBytes = 512L * 1024 * 1024;
// 檢查 zip 並解壓到 destDir(先解到暫存資料夾,全部成功才取代 destDir)
public static SongInfo Extract(string zipPath, string destDir)
{
using var fs = File.OpenRead(zipPath);
return Extract(fs, destDir);
}
public static SongInfo Extract(Stream zipStream, string destDir)
{
using var zip = new ZipArchive(zipStream, ZipArchiveMode.Read, leaveOpen: true);
var files = Collect(zip, out string configText);
SongInfo info;
try { info = SongInfo.FromConfig(configText, null); }
catch (FormatException e) { throw new PackException(e.Message); }
bool hasChart = false;
foreach (var n in SongInfo.LevelNames) if (files.ContainsKey(n + ".json")) hasChart = true;
if (!hasChart) throw new PackException("曲包沒有任何難度的譜面");
bool hasMusic = false;
foreach (var n in SongInfo.MusicNames) if (files.ContainsKey(n)) hasMusic = true;
if (!hasMusic) throw new PackException("曲包沒有音樂(music.ogg / wav / mp3)");
if (!files.ContainsKey(SongInfo.ImageName)) throw new PackException("曲包沒有封面 image.png");
string temp = destDir.TrimEnd('/', '\\') + ".tmp";
if (Directory.Exists(temp)) Directory.Delete(temp, true);
Directory.CreateDirectory(temp);
try
{
foreach (var kv in files)
{
using var src = kv.Value.Open();
using var dst = File.Create(Path.Combine(temp, kv.Key));
src.CopyTo(dst);
}
if (Directory.Exists(destDir)) Directory.Delete(destDir, true);
Directory.Move(temp, destDir);
}
catch
{
if (Directory.Exists(temp)) Directory.Delete(temp, true);
throw;
}
return SongInfo.FromDir(destDir);
}
// 白名單內的檔案(檔名小寫 → entry);允許整個資料夾被壓進去:以最淺的 config.json 所在位置為根
private static Dictionary<string, ZipArchiveEntry> Collect(ZipArchive zip, out string configText)
{
ZipArchiveEntry config = null;
foreach (var e in zip.Entries)
{
if (!string.Equals(e.Name, SongInfo.ConfigName, StringComparison.OrdinalIgnoreCase)) continue;
if (config == null || e.FullName.Length < config.FullName.Length) config = e;
}
if (config == null) throw new PackException("zip 裡沒有 config.json,不是曲包");
string prefix = config.FullName.Substring(0, config.FullName.Length - config.Name.Length);
var files = new Dictionary<string, ZipArchiveEntry>();
foreach (var e in zip.Entries)
{
if (!e.FullName.StartsWith(prefix, StringComparison.Ordinal)) continue;
string rel = e.FullName.Substring(prefix.Length);
if (rel.Length == 0 || rel.IndexOf('/') >= 0 || rel.IndexOf('\\') >= 0) continue; // 目錄項目、子資料夾
if (!Allowed.Contains(rel)) continue;
if (e.Length > MaxEntryBytes) throw new PackException($"{rel} 太大");
files[rel.ToLowerInvariant()] = e;
}
using var reader = new StreamReader(config.Open(), System.Text.Encoding.UTF8);
configText = reader.ReadToEnd();
return files;
}
// 給玩家看的錯誤訊息
public static string Describe(Exception e)
{
if (e is PackException || e is FormatException) return e.Message;
if (e is InvalidDataException) return "不是有效的 zip 檔";
if (e is IOException) return "檔案讀取失敗(可能還在複製中)";
if (e is UnauthorizedAccessException) return "沒有讀取權限";
return e.GetType().Name + ": " + e.Message;
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: c0876d2a8cc58b346b9007f5ca830a23
+30
View File
@@ -0,0 +1,30 @@
// 一次遊玩的統計,給結算/上傳使用
public class PlayResult
{
public int score;
public int perfect, fast, slow, bad, miss;
public int maxCombo;
public int combo;
public static PlayResult Last { get; set; }
public void Add(Judgement j, int points)
{
score += points;
switch (j)
{
case Judgement.Perfect: perfect++; break;
case Judgement.Fast: fast++; break;
case Judgement.Slow: slow++; break;
case Judgement.Bad: bad++; break;
case Judgement.Miss: miss++; break;
}
if (j == Judgement.Miss) combo = 0;
else if (j != Judgement.None) combo++;
if (combo > maxCombo) maxCombo = combo;
}
public override string ToString() =>
$"score={score} P={perfect} F={fast} S={slow} B={bad} M={miss} maxCombo={maxCombo}";
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 48d770f32e4d63d48ac02109441a84af
+36
View File
@@ -0,0 +1,36 @@
using UnityEngine;
// 所有 PlayerPrefs 的鍵集中在這裡(沿用舊版的鍵名,更新後登入狀態與設定不會消失)
public static class Prefs
{
public const string Uid = "UID";
public const string Token = "Token";
public const string LegacyPassword = "Password"; // 舊版存的密碼,登入成功後刪除
public const string Name = "Name";
public const string Email = "Email";
public const string AccountType = "Type";
public const string CreateTime = "CreateTime";
public const string EmailVerified = "EmailVerified";
public const string Song = "NowPlayingSong";
public const string Level = "NowPlayingLevel";
public const string AudioOffsetMs = "AudioOffsetMs";
public const string VideoBackground = "VideoBackground";
public const string StorageAsked = "StorageAsked";
public static int UserId => PlayerPrefs.GetInt(Uid, 0);
public static bool LoggedIn => UserId != 0 && (PlayerPrefs.HasKey(Token) || PlayerPrefs.HasKey(LegacyPassword));
// UID 顯示格式:帳號類型字元 + x + 8 位十六進位
public static string UidText()
{
int uid = UserId;
string type = PlayerPrefs.GetString(AccountType, "");
if (uid == 0 || type == "") return "0x00000000";
char c = type switch { "R" => '0', "A" => 'a', "B" => 'b', "D" => 'f', _ => '?' };
return $"{c}x{uid:X8}";
}
public static void SetBool(string key, bool value) => PlayerPrefs.SetInt(key, value ? 1 : 0);
public static bool GetBool(string key, bool fallback) => PlayerPrefs.GetInt(key, fallback ? 1 : 0) == 1;
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: ea45d9721b0788c45a674896e69e971e
+88
View File
@@ -0,0 +1,88 @@
using System;
using System.IO;
using System.Text.RegularExpressions;
// 一個已匯入曲包的資訊(來自 config.json 與資料夾內的檔案)
// 曲包格式見 RhyculatorMaker 的 README
public class SongInfo
{
public const int LevelCount = 3;
public static readonly string[] LevelNames = { "easy", "normal", "hard" }; // level 1..3
public static readonly string[] MusicNames = { "music.ogg", "music.wav", "music.mp3" };
public const string ConfigName = "config.json";
public const string ImageName = "image.png";
public const string VideoName = "video.mp4";
private static readonly Regex IdPattern = new Regex("^[a-z0-9][a-z0-9-]{1,63}$");
public string id;
public string name;
public string artist;
public string charter;
public double bpm;
public int beatOffsetMs;
public int offsetMs; // 判定時間微調:正值 = 所有音符的判定點往後移
public int previewStartMs;
public int previewLengthMs;
public readonly int[] levelNum = new int[LevelCount + 1]; // [1..3] 難度數字,0 = 未填
public string dir; // 解開後的檔案所在(zip 曲包是快取資料夾)
public string source; // package 資料夾裡的來源:zip 檔或資料夾
public static string LevelName(int level) => level >= 1 && level <= LevelCount ? LevelNames[level - 1] : "normal";
public static bool IsValidId(string id) => id != null && IdPattern.IsMatch(id);
public bool HasLevel(int level) => level >= 1 && level <= LevelCount && File.Exists(ChartPath(level));
public string ChartPath(int level) => Path.Combine(dir, LevelName(level) + ".json");
public string ImagePath => Path.Combine(dir, ImageName);
public string VideoPath
{
get { string p = Path.Combine(dir, VideoName); return File.Exists(p) ? p : null; }
}
public string MusicPath
{
get
{
foreach (var n in MusicNames)
{
string p = Path.Combine(dir, n);
if (File.Exists(p)) return p;
}
return null;
}
}
// 第一個有譜面的難度,沒有則 0
public int FirstLevel()
{
for (int l = 1; l <= LevelCount; l++) if (HasLevel(l)) return l;
return 0;
}
// 解析 config.json;缺必要欄位時丟 FormatException
public static SongInfo FromConfig(string configJson, string dir)
{
var cfg = MiniJson.AsObject(MiniJson.Parse(configJson));
if (cfg == null) throw new FormatException("config.json 不是 JSON 物件");
var s = new SongInfo { dir = dir };
s.id = MiniJson.GetString(cfg, "id", "").Trim();
if (!IsValidId(s.id)) throw new FormatException("config.json 的 id 無效(只能用小寫英數字與 -)");
s.name = MiniJson.GetString(cfg, "name", "").Trim();
if (s.name == "") throw new FormatException("config.json 缺少 name");
s.artist = MiniJson.GetString(cfg, "artist", "");
s.charter = MiniJson.GetString(cfg, "charter", "");
s.bpm = MiniJson.GetNumber(cfg, "bpm", 0);
s.beatOffsetMs = MiniJson.GetInt(cfg, "beat_offset", 0);
s.offsetMs = MiniJson.GetInt(cfg, "offset", 0);
s.previewStartMs = MiniJson.GetInt(cfg, "preview_start", 0);
s.previewLengthMs = MiniJson.GetInt(cfg, "preview_length", 15000);
for (int l = 1; l <= LevelCount; l++)
s.levelNum[l] = MiniJson.GetInt(cfg, LevelNames[l - 1] + "_num", 0);
return s;
}
public static SongInfo FromDir(string dir)
=> FromConfig(File.ReadAllText(Path.Combine(dir, ConfigName)), dir);
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 662e3c38dfd560f41a15cfe5a56b4cd2
+8
View File
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 56da2600844fc6546af0dcc00dccb278
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
+37
View File
@@ -0,0 +1,37 @@
using System.Collections.Generic;
// 依 SongClock 把譜面事件放到格子上(遊玩與主畫面的背景譜面共用)
public class ChartPlayer
{
private readonly List<ChartEvent> events;
private int next;
public int Count => events.Count;
public ChartPlayer(List<ChartEvent> events)
{
this.events = events;
}
// 從某個時間點開始(之前的事件略過,例如主畫面音樂已經在播)
public void Seek(double time)
{
next = 0;
while (next < events.Count && events[next].hitTime < time) next++;
}
public void Tick(Grid grid, double now)
{
double until = now + Grid.AppearLead;
while (next < events.Count && events[next].hitTime <= until)
{
var e = events[next++];
switch (e.type)
{
case "tap": grid.ShowNote(e.x, e.y, NoteType.Tap, e.hitTime); break;
case "hold": grid.ShowNote(e.x, e.y, NoteType.Hold, e.hitTime, e.holdMs); break;
case "slide": grid.ShowNote(e.x, e.y, NoteType.Slide, e.hitTime); break;
}
}
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: ad11e114219d549499dbd8005be48111
+325
View File
@@ -0,0 +1,325 @@
using System;
using UnityEngine;
using UnityEngine.UI;
public enum NoteType { Tap, Hold, Slide }
public enum CellFlash { White, Blue, Green, Orange, Red }
// 5x6 的格子:所有畫面共用一個,畫面只設定格子上的圖示、文字與音符
// 每格由下而上:外框(判定閃色)、圖示、音符、長按進度環、文字
// 音符動畫完全由 SongClock 決定,保證在判定時間時縮放剛好為 1
public class Grid : MonoBehaviour
{
public const int Columns = 5;
public const int Rows = 6;
// 1080 寬的畫布單位
public const float CellSize = 180f;
public const float Spacing = 20f;
public const float Width = Columns * CellSize + (Columns - 1) * Spacing;
public const float Height = Rows * CellSize + (Rows - 1) * Spacing;
// 音符在判定點前多久出現(秒);與 Maker 的 zones.APPEAR_MS 一致
public const double AppearLead = 0.5;
private const double FillDuration = 0.2; // 出現時的圓形填滿動畫
private const double GrowHalf = 0.2; // 判定點前後的縮放區間:0.5 → 1 → 1.5
private const float FlashDuration = 0.3f;
private const float RingScale = 1.2f;
// 音符超過判定時間仍未被處理(x, y, 種類)
public event Action<int, int, NoteType> NoteExpired;
private class Cell
{
public RectTransform rt;
public Image frame, icon, note, ring;
public Text label;
public bool hasNote;
public NoteType type;
public double hitTime;
public int holdMs;
public float flashEnd;
public bool flashColored; // 目前是判定色(優先於按住時的白色)
public float ringStart, ringLength;
}
private readonly Cell[,] cells = new Cell[Columns, Rows];
private RectTransform area;
private Sprite frameDefault, noteTap, noteHold, noteSlide;
private Sprite[] flashSprites;
private Font font;
public static Grid Create(RectTransform parent, Font font)
{
var go = new GameObject("Grid", typeof(RectTransform));
go.transform.SetParent(parent, false);
var g = go.AddComponent<Grid>();
g.Build(font);
return g;
}
void Build(Font f)
{
font = f;
frameDefault = Sprites.Get("Grid_dgray");
noteTap = Sprites.Get("TapNote");
noteHold = Sprites.Get("HoldNote");
noteSlide = Sprites.Get("SlideNote");
flashSprites = new[]
{
Sprites.Get("Grid_white"), Sprites.Get("Grid_blue"), Sprites.Get("Grid_green"),
Sprites.Get("Grid_orange"), Sprites.Get("Grid_red"),
};
Sprite ringSprite = Sprites.Get("LongPressHint");
area = (RectTransform)transform;
area.anchorMin = area.anchorMax = area.pivot = new Vector2(0.5f, 0f);
area.sizeDelta = new Vector2(Width, Height);
for (int y = 0; y < Rows; y++)
for (int x = 0; x < Columns; x++)
{
var c = new Cell();
var go = new GameObject($"Cell {x},{y}", typeof(RectTransform));
go.transform.SetParent(area, false);
c.rt = (RectTransform)go.transform;
c.rt.anchorMin = c.rt.anchorMax = Vector2.zero;
c.rt.pivot = new Vector2(0.5f, 0.5f);
c.rt.sizeDelta = new Vector2(CellSize, CellSize);
c.rt.anchoredPosition = new Vector2(x * (CellSize + Spacing) + CellSize / 2, y * (CellSize + Spacing) + CellSize / 2);
c.frame = Layer(c.rt, "Frame", frameDefault);
c.icon = Layer(c.rt, "Icon", null);
c.icon.preserveAspect = true;
c.note = Layer(c.rt, "Note", null);
c.note.type = Image.Type.Filled;
c.note.fillMethod = Image.FillMethod.Radial360;
c.note.fillOrigin = 2;
c.note.fillClockwise = true;
c.ring = Layer(c.rt, "Ring", ringSprite);
c.ring.type = Image.Type.Filled;
c.ring.fillMethod = Image.FillMethod.Radial360;
c.ring.fillOrigin = 2;
c.ring.rectTransform.localScale = Vector3.one * RingScale;
c.ring.enabled = false;
var lgo = new GameObject("Label", typeof(RectTransform));
lgo.transform.SetParent(c.rt, false);
c.label = lgo.AddComponent<Text>();
c.label.font = font;
c.label.fontStyle = FontStyle.Bold;
c.label.alignment = TextAnchor.MiddleCenter;
c.label.horizontalOverflow = HorizontalWrapMode.Overflow;
c.label.verticalOverflow = VerticalWrapMode.Overflow;
c.label.raycastTarget = false;
Stretch(c.label.rectTransform);
c.label.enabled = false;
cells[x, y] = c;
}
}
static Image Layer(RectTransform parent, string name, Sprite sprite)
{
var go = new GameObject(name, typeof(RectTransform));
go.transform.SetParent(parent, false);
var img = go.AddComponent<Image>();
img.sprite = sprite;
img.raycastTarget = false; // 格子不擋觸控判斷(UIHitTest 只看面板、按鈕)
img.enabled = sprite != null;
Stretch(img.rectTransform);
return img;
}
static void Stretch(RectTransform rt)
{
rt.anchorMin = Vector2.zero;
rt.anchorMax = Vector2.one;
rt.offsetMin = rt.offsetMax = Vector2.zero;
}
public static bool InBounds(int x, int y) => x >= 0 && y >= 0 && x < Columns && y < Rows;
// 由 App 每幀呼叫:在畫面處理完觸控(判定)之後、生成新音符之前
public void Tick()
{
double now = SongClock.Now;
float t = Time.unscaledTime;
for (int y = 0; y < Rows; y++)
for (int x = 0; x < Columns; x++)
{
var c = cells[x, y];
if (c.hasNote)
{
double d = now - c.hitTime;
if (d > NoteJudge.BadWindow)
{
var type = c.type;
ClearNote(x, y);
NoteExpired?.Invoke(x, y, type);
}
else UpdateNote(c, d);
}
if (c.flashEnd > 0 && t >= c.flashEnd)
{
c.frame.sprite = frameDefault;
c.flashEnd = 0;
}
if (c.ring.enabled)
{
float p = c.ringLength > 0 ? (t - c.ringStart) / c.ringLength : 1f;
if (p >= 1f) c.ring.enabled = false;
else c.ring.fillAmount = 1f - p;
}
}
}
// ---------- 圖示與文字 ----------
public void SetIcon(int x, int y, Sprite sprite)
{
if (!InBounds(x, y)) return;
var c = cells[x, y];
c.icon.sprite = sprite;
c.icon.enabled = sprite != null;
}
public void SetLabel(int x, int y, string text, Color color, float fontScale = 0.55f)
{
if (!InBounds(x, y)) return;
var l = cells[x, y].label;
l.enabled = !string.IsNullOrEmpty(text);
l.text = text ?? "";
l.color = color;
l.fontSize = Mathf.RoundToInt(CellSize * fontScale);
}
// 清除所有圖示、文字、音符與進度環(換畫面時)
public void ClearAll()
{
for (int y = 0; y < Rows; y++)
for (int x = 0; x < Columns; x++)
{
var c = cells[x, y];
ClearNote(x, y);
SetIcon(x, y, null);
c.label.enabled = false;
c.ring.enabled = false;
c.frame.sprite = frameDefault;
c.flashEnd = 0;
}
}
// ---------- 音符 ----------
public void ShowNote(int x, int y, NoteType type, double hitTime, int holdMs = 0)
{
if (!InBounds(x, y)) return;
var c = cells[x, y];
// 同格還有未處理的音符:視為 Miss,避免音符無聲消失造成統計少算
if (c.hasNote)
{
var old = c.type;
ClearNote(x, y);
NoteExpired?.Invoke(x, y, old);
}
c.hasNote = true;
c.type = type;
c.hitTime = hitTime;
c.holdMs = holdMs;
c.note.sprite = type == NoteType.Tap ? noteTap : type == NoteType.Hold ? noteHold : noteSlide;
c.note.enabled = true;
UpdateNote(c, SongClock.Now - hitTime);
}
// d = 目前時間 - 判定時間
static void UpdateNote(Cell c, double d)
{
float fill = (float)Math.Min(1.0, Math.Max(0.0, (d + AppearLead) / FillDuration));
float scale = d < -GrowHalf ? 0.5f : (float)(1.0 + d / (2 * GrowHalf));
float alpha = scale > 1f ? Mathf.Clamp01(1f - (scale - 1f) / 0.5f) : 1f;
c.note.fillAmount = fill;
c.note.color = new Color(1, 1, 1, alpha);
c.note.rectTransform.localScale = Vector3.one * scale;
}
public bool HasNote(int x, int y) => InBounds(x, y) && cells[x, y].hasNote;
public NoteType NoteTypeAt(int x, int y) => cells[x, y].type;
public double HitTime(int x, int y) => cells[x, y].hitTime;
public int HoldMs(int x, int y) => cells[x, y].holdMs;
public void ClearNote(int x, int y)
{
if (!InBounds(x, y)) return;
var c = cells[x, y];
c.hasNote = false;
c.note.enabled = false;
c.note.rectTransform.localScale = Vector3.one;
}
// ---------- 回饋 ----------
public void Flash(int x, int y, CellFlash color)
{
if (!InBounds(x, y)) return;
var c = cells[x, y];
bool colored = color != CellFlash.White;
// 按住時的白色不覆蓋判定色
if (!colored && c.flashEnd > 0 && c.flashColored) return;
c.frame.sprite = flashSprites[(int)color];
c.flashColored = colored;
c.flashEnd = Time.unscaledTime + FlashDuration;
}
public void StartRing(int x, int y, float seconds)
{
if (!InBounds(x, y) || seconds <= 0) return;
var c = cells[x, y];
c.ring.enabled = true;
c.ring.fillAmount = 1f;
c.ringStart = Time.unscaledTime;
c.ringLength = seconds;
}
public void StopRing(int x, int y)
{
if (InBounds(x, y)) cells[x, y].ring.enabled = false;
}
// 螢幕座標 → 格子;在格子外(含間距)回傳 false
public bool CellAt(Vector2 screenPos, out int x, out int y)
{
x = y = -1;
if (!isActiveAndEnabled) return false;
if (!RectTransformUtility.ScreenPointToLocalPointInRectangle(area, screenPos, null, out Vector2 local)) return false;
// area 的 pivot 在下方中央
Vector2 p = local + new Vector2(Width / 2, 0);
const float step = CellSize + Spacing;
int cx = Mathf.FloorToInt(p.x / step);
int cy = Mathf.FloorToInt(p.y / step);
if (!InBounds(cx, cy)) return false;
if (p.x - cx * step > CellSize || p.y - cy * step > CellSize) return false;
x = cx;
y = cy;
return true;
}
}
// Resources/Sprites 的圖片(快取)
public static class Sprites
{
private static readonly System.Collections.Generic.Dictionary<string, Sprite> cache =
new System.Collections.Generic.Dictionary<string, Sprite>();
public static Sprite Get(string name)
{
if (!cache.TryGetValue(name, out var s))
{
s = Resources.Load<Sprite>("Sprites/" + name);
if (s == null) Debug.LogWarning("[Sprites] 找不到 " + name);
cache[name] = s;
}
return s;
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: d019d349bdba3bd4da6179077b905f3d
+91
View File
@@ -0,0 +1,91 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem.EnhancedTouch;
using Touch = UnityEngine.InputSystem.EnhancedTouch.Touch;
using TouchPhase = UnityEngine.InputSystem.TouchPhase;
// 一根手指在本幀的狀態
public struct GridTouch
{
public int fingerId;
public Vector2 position;
public bool began; // 本幀新按下
public bool ended; // 本幀放開 / 取消
public int x, y; // 所在格子,不在格子上為 -1
public double pressAge; // 按下事件距今幾秒(用來回推精確的按下時間)
public bool OnCell => x >= 0;
}
// 格子的觸控輸入(EnhancedTouch:同一幀內按下又放開的快速點擊也不會漏掉)
// - IgnoreCurrentTouches 之前就按著的手指會被忽略(換畫面時)
// - 按下時若最上層是面板、按鈕等 UI,這根手指直到放開都不會送到格子(防穿透)
// - 編輯器裡用滑鼠模擬觸控
public class GridInput
{
private readonly Grid grid;
private readonly HashSet<int> ignored = new HashSet<int>();
private readonly List<GridTouch> touches = new List<GridTouch>();
// 按下事件最多回推的秒數(避免掉幀時判定被推太遠)
private const double MaxPressAge = 0.1;
public GridInput(Grid grid)
{
this.grid = grid;
EnhancedTouchSupport.Enable();
#if UNITY_EDITOR
TouchSimulation.Enable();
#endif
}
public void IgnoreCurrentTouches()
{
foreach (var t in Touch.activeTouches)
ignored.Add(t.touchId);
}
// blocked = true 時(例如開著對話框)所有新的觸控都不送到格子
public List<GridTouch> Poll(bool blocked = false)
{
touches.Clear();
double now = Time.realtimeSinceStartupAsDouble;
foreach (var t in Touch.activeTouches)
{
int id = t.touchId;
TouchPhase phase = t.phase;
bool ended = phase == TouchPhase.Ended || phase == TouchPhase.Canceled;
bool began = phase == TouchPhase.Began;
if (began && (blocked || UIHitTest.IsBlocked(t.screenPosition)))
ignored.Add(id);
if (ignored.Contains(id))
{
if (ended) ignored.Remove(id);
continue;
}
Vector2 pos = t.screenPosition;
if (ended)
{
touches.Add(new GridTouch { fingerId = id, ended = true, x = -1, y = -1, position = pos });
continue;
}
grid.CellAt(pos, out int x, out int y);
double age = began ? System.Math.Min(MaxPressAge, System.Math.Max(0, now - t.startTime)) : 0;
touches.Add(new GridTouch { fingerId = id, position = pos, began = began, x = x, y = y, pressAge = age });
}
return touches;
}
// 本幀是否有新的點擊(任意位置,結算畫面「點擊繼續」用)
public static bool AnyNewTap()
{
foreach (var t in Touch.activeTouches)
if (t.phase == TouchPhase.Began) return true;
return false;
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 58c9f43e3bbee1041b9972c39d2cf5cb
+79
View File
@@ -0,0 +1,79 @@
using UnityEngine;
// 以音訊 DSP 時鐘為準的歌曲時間(秒)
// AudioSettings.dspTime 在手機上是以音訊 buffer 為單位跳動,
// 這裡用 realtime 在兩次跳動之間補間,並保證時間單調遞增
public static class SongClock
{
public static bool Running { get; private set; }
public static bool Paused { get; private set; }
private static double dspStart;
private static double lastDsp;
private static double lastDspRealtime;
private static double lastReturned;
private static double offsetSec;
private static double pausedAt;
// 補間最多往前推 0.1 秒,避免音訊卡住時畫面跑太快
private const double MaxExtrapolation = 0.1;
// applyOffset = false:不套用延遲補償(校正量測時使用)
public static void Begin(double dspStartTime, bool applyOffset = true)
{
dspStart = dspStartTime;
lastDsp = AudioSettings.dspTime;
lastDspRealtime = Time.realtimeSinceStartupAsDouble;
lastReturned = double.MinValue;
offsetSec = applyOffset ? PlayerPrefs.GetInt(Prefs.AudioOffsetMs, 0) / 1000.0 : 0;
Running = true;
Paused = false;
}
// 暫停:時間停在目前的值(音符不會過期),以 Resume 接續
public static void Pause()
{
if (!Running || Paused) return;
pausedAt = Now;
Paused = true;
}
// 接續:音訊的 audioPos 秒在 DSP 時間 dspAt 播出(延遲補償沿用原本的值)
public static void Resume(double audioPos, double dspAt)
{
double offset = offsetSec;
Begin(dspAt - audioPos, false);
offsetSec = offset;
}
public static double PausedAt => pausedAt;
public static void Stop()
{
Running = false;
Paused = false;
}
// 目前歌曲時間;音樂開始前為負值
public static double Now
{
get
{
if (!Running) return 0;
if (Paused) return pausedAt;
double dsp = AudioSettings.dspTime;
double real = Time.realtimeSinceStartupAsDouble;
if (dsp != lastDsp)
{
lastDsp = dsp;
lastDspRealtime = real;
}
double t = lastDsp + System.Math.Min(real - lastDspRealtime, MaxExtrapolation) - dspStart - offsetSec;
if (t < lastReturned) t = lastReturned;
lastReturned = t;
return t;
}
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 352b164fefd8c6b45bb274076fffc604
+8
View File
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: ef31c3f58ae749c4a9eea18f56231884
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
+117
View File
@@ -0,0 +1,117 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
// 伺服器呼叫(回應一律用 MiniJson 解析)
public static class Api
{
public class Response
{
public Dictionary<string, object> data; // 解析失敗或連線失敗時為 null
public string error; // 給玩家看的錯誤;成功時為 null
public string Status => MiniJson.GetString(data, "status", "");
public string Reason => MiniJson.GetString(data, "reason", "");
public bool Ok => error == null && (Status == "success" || Status == "send" || Status == "found" || Status == "not_found");
public string Str(string key) => MiniJson.GetString(data, key, "");
public int Int(string key) => MiniJson.GetInt(data, key, 0);
}
public static IEnumerator Game(Dictionary<string, object> body, Action<Response> done)
=> Post(ServerConfig.GameServerUrl + "/", body, done);
public static IEnumerator Verify(Dictionary<string, object> body, Action<Response> done)
=> Post(ServerConfig.VerifyServerUrl + "/", body, done);
public static IEnumerator Post(string url, Dictionary<string, object> body, Action<Response> done)
{
using var www = new UnityWebRequest(url, "POST");
www.uploadHandler = new UploadHandlerRaw(System.Text.Encoding.UTF8.GetBytes(MiniJson.Serialize(body)));
www.downloadHandler = new DownloadHandlerBuffer();
www.SetRequestHeader("Content-Type", "application/json");
www.timeout = 10;
yield return www.SendWebRequest();
done(Parse(www));
}
public static IEnumerator Get(string url, Action<Response> done)
{
using var www = UnityWebRequest.Get(url);
www.timeout = 10;
yield return www.SendWebRequest();
done(Parse(www));
}
// 伺服器回 4xx/5xx 時 body 仍是 JSON,照樣解析
static Response Parse(UnityWebRequest www)
{
var r = new Response();
try { r.data = MiniJson.AsObject(MiniJson.Parse(www.downloadHandler.text)); }
catch { r.data = null; }
if (r.data == null)
r.error = www.result == UnityWebRequest.Result.ConnectionError ? "無法連線到伺服器" : "伺服器回傳異常";
else if (r.Status == "fail" || r.Status == "failed")
r.error = r.Reason;
if (r.error != null) Debug.LogWarning($"[Api] {www.url}: {r.error} ({www.error})");
return r;
}
// 以曲包代碼下載到 package 資料夾;progress 0~1;完成時 done(錯誤或 null, 曲名)
public static IEnumerator DownloadPack(string code, Action<float> progress, Action<string, string> done)
{
code = code.Trim().ToLowerInvariant();
Response info = null;
yield return Get($"{ServerConfig.GameServerUrl}/api/packs/{UnityWebRequest.EscapeURL(code)}", r => info = r);
if (info.error != null)
{
done(info.Reason == "not_found" ? "找不到這個代碼的曲包" : info.error, null);
yield break;
}
var pack = MiniJson.AsObject(MiniJson.Get(info.data, "pack"));
string title = MiniJson.GetString(pack, "title", code);
string url = ServerConfig.GameServerUrl + MiniJson.GetString(pack, "download", $"/p/{code}/download");
string dir = PackStorage.PackageDir;
Directory.CreateDirectory(dir);
string part = Path.Combine(dir, $".{code}.part");
using (var www = UnityWebRequest.Get(url))
{
www.downloadHandler = new DownloadHandlerFile(part) { removeFileOnAbort = true };
var op = www.SendWebRequest();
while (!op.isDone)
{
progress?.Invoke(www.downloadProgress);
yield return null;
}
if (www.result != UnityWebRequest.Result.Success)
{
try { File.Delete(part); } catch { }
done("下載失敗:" + www.error, title);
yield break;
}
}
// 同一個曲包的舊版本(代碼相同)換成新下載的
var old = Library.Find(code);
if (old != null) PackStorage.DeleteSource(old);
string target = PackStorage.UniquePath(dir, $"{SafeName(title)} [{code}]", ".zip");
File.Move(part, target);
// 讓掃描不必等「剛寫入」的緩衝時間
File.SetLastWriteTimeUtc(target, DateTime.UtcNow - PackLibrary.SettleTime - TimeSpan.FromSeconds(1));
Library.Rescan();
done(null, title);
}
static string SafeName(string s)
{
foreach (char c in Path.GetInvalidFileNameChars()) s = s.Replace(c, '_');
foreach (char c in "\\/:*?\"<>|") s = s.Replace(c, '_');
s = s.Trim();
return s.Length > 60 ? s.Substring(0, 60) : (s == "" ? "pack" : s);
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: ec2d9a420eee6e042b20268b397edc96
+151
View File
@@ -0,0 +1,151 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using UnityEngine;
// 曲包清單(遊戲其他地方都透過這裡取得曲目)
// 開啟遊戲、回到前景時立即掃描 package 資料夾,之後每秒一次;掃描在背景執行緒進行
public class Library : MonoBehaviour
{
public static IReadOnlyList<SongInfo> Songs { get; private set; } = new List<SongInfo>();
public static bool Loaded { get; private set; }
public static string PackageDir { get; private set; }
// 曲包清單有變(新增、刪除、更新)
public static event Action Changed;
// 有新的曲包出現(不含第一次掃描)
public static event Action<SongInfo> Added;
// 遊玩中暫停掃描,避免 IO 影響幀率
public static bool Paused;
private static Library instance;
private Task<PackLibrary.ScanResult> running;
private float nextScan;
private bool first = true;
public static void Create()
{
if (instance != null) return;
var go = new GameObject("Library");
DontDestroyOnLoad(go);
instance = go.AddComponent<Library>();
}
// 立即重新掃描(例如取得權限、下載完成後)
public static void Rescan()
{
if (instance != null) instance.nextScan = 0;
}
public static SongInfo Find(string id)
{
foreach (var s in Songs) if (s.id == id) return s;
return null;
}
public static SongInfo Current
{
get
{
var s = Find(PlayerPrefs.GetString(Prefs.Song, ""));
return s ?? (Songs.Count > 0 ? Songs[0] : null);
}
set
{
if (value == null) return;
PlayerPrefs.SetString(Prefs.Song, value.id);
}
}
void OnApplicationFocus(bool focus)
{
if (focus) nextScan = 0;
}
void Update()
{
if (running != null)
{
if (!running.IsCompleted) return;
Apply(running);
running = null;
}
if (Paused || Time.unscaledTime < nextScan) return;
nextScan = Time.unscaledTime + 1f;
string packageDir = PackStorage.PackageDir;
string cacheDir = PackStorage.CacheDir;
if (packageDir != PackageDir)
{
// 位置改變(取得權限):搬過去並重新開始
PackageDir = packageDir;
PackLibrary.ResetState();
first = true;
}
running = Task.Run(() =>
{
PackStorage.Migrate(packageDir);
return PackLibrary.Scan(packageDir, cacheDir);
});
}
void Apply(Task<PackLibrary.ScanResult> task)
{
if (task.IsFaulted)
{
Debug.LogWarning("[Library] 掃描失敗:" + task.Exception?.GetBaseException().Message);
return;
}
var r = task.Result;
foreach (var e in r.errors) Toast.Show("曲包有問題:" + e);
if (r.pending) nextScan = Time.unscaledTime + 0.5f;
if (r.changed || !Loaded)
{
Songs = r.songs;
Loaded = true;
Debug.Log($"[Library] {Songs.Count} 個曲包 @ {PackageDir}");
Changed?.Invoke();
}
if (!first)
foreach (var s in r.added)
{
Toast.Show($"已加入「{s.name}」");
Added?.Invoke(s);
}
first = false;
ReadImportError();
ReadPendingDownload();
}
// 曲包網站的「在遊戲中下載」連結(rhyculator://pack/<code>):Java 端把代碼寫在這個檔案
public static event Action<string> DownloadRequested;
static void ReadPendingDownload()
{
string path = Path.Combine(PackStorage.PrivateRoot, PackStorage.PendingDownloadFile);
if (!File.Exists(path)) return;
string code = "";
try { code = File.ReadAllText(path).Trim().ToLowerInvariant(); } catch { }
try { File.Delete(path); } catch { }
if (System.Text.RegularExpressions.Regex.IsMatch(code, "^[a-z0-9]{8}$")) DownloadRequested?.Invoke(code);
}
// Java 端讀取「開啟 / 分享」進來的檔案失敗時留下的訊息
static void ReadImportError()
{
string path = Path.Combine(PackStorage.PrivateRoot, PackStorage.ImportErrorFile);
if (!File.Exists(path)) return;
string detail = "";
try { detail = File.ReadAllText(path); } catch { }
try { File.Delete(path); } catch { }
Debug.LogWarning("[Library] " + detail);
Toast.Show(detail.Contains("Permission Denial") || detail.Contains("SecurityException")
? "沒有讀取這個檔案的權限,請從檔案管理員用「開啟」或「分享」送給 Rhyculator"
: "無法讀取檔案:" + detail);
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 6d3343d5a8659b64fabd125d9f91790a
+168
View File
@@ -0,0 +1,168 @@
using System;
using System.IO;
using UnityEngine;
// 曲包資料夾的位置
// - 有「所有檔案存取權」(Android 11+)或儲存權限(Android 10 以下):手機根目錄的 Rhyculator/package,
// 接上電腦(USB)或用任何檔案管理員都看得到,像插上一個隨身碟
// - 沒有權限:app 自己的資料夾 Android/data/<套件名>/files/package(USB 通常也看得到,但檔案管理員看不到)
// 位置的判斷與 RhyculatorActivity.packageDir() 一致,Java 收到的 zip 會直接放進同一個資料夾
public static class PackStorage
{
public const string FolderName = "Rhyculator";
public const string PackageFolder = "package";
// Java 端寫的訊息檔(在 app 自己的資料夾)
public const string ImportErrorFile = "import-error.txt";
public const string PendingDownloadFile = "pending-download.txt";
// 測試用:改放到別的資料夾
public static string rootOverride;
private static string privateRoot, cacheRoot, sharedRoot;
// 在主執行緒呼叫一次(Application.* 只能在主執行緒讀)
public static void Init()
{
privateRoot = Application.persistentDataPath;
cacheRoot = Path.Combine(Application.persistentDataPath, "cache", "packs");
#if UNITY_ANDROID && !UNITY_EDITOR
try
{
using var env = new AndroidJavaClass("android.os.Environment");
using var dir = env.CallStatic<AndroidJavaObject>("getExternalStorageDirectory");
sharedRoot = Path.Combine(dir.Call<string>("getAbsolutePath"), FolderName);
}
catch (Exception e) { Debug.LogWarning("[PackStorage] " + e.Message); }
#endif
}
public static string PrivateRoot => rootOverride ?? privateRoot;
public static string CacheDir => rootOverride != null ? Path.Combine(rootOverride, "cache") : cacheRoot;
public static bool SupportsShared => sharedRoot != null && rootOverride == null;
public static string Root => SupportsShared && HasSharedAccess() ? sharedRoot : PrivateRoot;
public static string PackageDir => Path.Combine(Root, PackageFolder);
public static bool HasSharedAccess()
{
#if UNITY_ANDROID && !UNITY_EDITOR
try { return Activity().CallStatic<bool>("hasStorageAccess", CurrentActivity()); }
catch (Exception e) { Debug.LogWarning("[PackStorage] " + e.Message); }
#endif
return false;
}
// 開啟系統的授權畫面;結果在回到遊戲時(OnApplicationFocus)重新檢查
public static void RequestSharedAccess()
{
#if UNITY_ANDROID && !UNITY_EDITOR
try { Activity().CallStatic("requestStorageAccess", CurrentActivity()); }
catch (Exception e) { Debug.LogWarning("[PackStorage] " + e.Message); }
#endif
}
#if UNITY_ANDROID && !UNITY_EDITOR
static AndroidJavaClass Activity() => new AndroidJavaClass("com.rhyculator.RhyculatorActivity");
static AndroidJavaObject CurrentActivity()
{
using var player = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
return player.GetStatic<AndroidJavaObject>("currentActivity");
}
#endif
// 把舊位置的曲包搬到目前的 package 資料夾(背景執行緒可呼叫):
// - 舊版匯入的 songs/<id>/ 資料夾
// - app 資料夾根目錄的 *.zip(舊版的收件匣、adb push)
// - 取得權限前放在 app 資料夾的 package/
public static void Migrate(string packageDir)
{
Directory.CreateDirectory(packageDir);
string root = PrivateRoot;
string privatePackage = Path.Combine(root, PackageFolder);
// 曲包裡的音樂不要出現在手機的音樂 app
try
{
string nomedia = Path.Combine(Path.GetDirectoryName(packageDir), ".nomedia");
if (!File.Exists(nomedia)) File.WriteAllBytes(nomedia, Array.Empty<byte>());
}
catch { }
string songs = Path.Combine(root, "songs");
if (Directory.Exists(songs))
{
foreach (var dir in Directory.GetDirectories(songs))
MoveInto(dir, packageDir);
TryDelete(songs);
}
foreach (var zip in Directory.GetFiles(root, "*.zip"))
MoveInto(zip, packageDir);
if (!SamePath(privatePackage, packageDir) && Directory.Exists(privatePackage))
{
foreach (var f in Directory.GetFiles(privatePackage)) MoveInto(f, packageDir);
foreach (var d in Directory.GetDirectories(privatePackage)) MoveInto(d, packageDir);
TryDelete(privatePackage);
}
}
static void MoveInto(string path, string dir)
{
try
{
string name = Path.GetFileName(path);
string dest = UniquePath(dir, Path.GetFileNameWithoutExtension(name), Path.GetExtension(name));
if (Directory.Exists(path)) MoveDirectory(path, dest);
else
{
File.Copy(path, dest); // 可能跨儲存區,用複製再刪除
File.Delete(path);
}
}
catch (Exception e) { Debug.LogWarning($"[PackStorage] 無法移動 {path}:{e.Message}"); }
}
static void MoveDirectory(string src, string dest)
{
try { Directory.Move(src, dest); return; }
catch (IOException) { }
Directory.CreateDirectory(dest);
foreach (var f in Directory.GetFiles(src)) File.Copy(f, Path.Combine(dest, Path.GetFileName(f)));
Directory.Delete(src, true);
}
// dir/name.ext,已存在時加上 (2)、(3)…
public static string UniquePath(string dir, string name, string ext)
{
string path = Path.Combine(dir, name + ext);
for (int i = 2; File.Exists(path) || Directory.Exists(path); i++)
path = Path.Combine(dir, $"{name} ({i}){ext}");
return path;
}
static bool SamePath(string a, string b)
=> string.Equals(Path.GetFullPath(a).TrimEnd('/', '\\'), Path.GetFullPath(b).TrimEnd('/', '\\'), StringComparison.OrdinalIgnoreCase);
static void TryDelete(string dir)
{
try { Directory.Delete(dir, true); } catch { }
}
// 刪除一個曲包的來源(zip 或資料夾)
public static bool DeleteSource(SongInfo song)
{
try
{
if (File.Exists(song.source)) File.Delete(song.source);
else if (Directory.Exists(song.source)) Directory.Delete(song.source, true);
return true;
}
catch (Exception e)
{
Debug.LogWarning("[PackStorage] " + e.Message);
return false;
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 650f3c7c23c45684c87f71208c439e2f
+12
View File
@@ -0,0 +1,12 @@
// 伺服器網址集中管理
// 本地測試:UseLocal = true,並對模擬器執行
// adb reverse tcp:2010 tcp:2010
// adb reverse tcp:2030 tcp:2030
public static class ServerConfig
{
public const bool UseLocal = true;
// 遊戲 API(POST /)與曲包網站(GET /、/api/packs)是同一個服務
public const string GameServerUrl = UseLocal ? "http://127.0.0.1:2010" : "https://lunchpad.sthkm3.org";
public const string VerifyServerUrl = UseLocal ? "http://127.0.0.1:2030" : "https://verify.sthkm3.org";
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 9d6e31a65e930824991bf2a768205f09
+17
View File
@@ -0,0 +1,17 @@
{
"name": "Rhyculator.Game",
"rootNamespace": "",
"references": [
"Unity.InputSystem",
"UnityEngine.UI"
],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
}
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: a1e14a99d24120545ac8d1ec87adf041
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
+8
View File
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: fd0071db2fe334348a171ad6820b873b
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
+226
View File
@@ -0,0 +1,226 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.UI;
using UnityEngine.UI;
// 一個畫面(主選單、選歌、遊玩…);同時只有一個,畫面內容放在 App.Top,格子是共用的
public abstract class Page
{
protected App App => App.Instance;
protected Grid Grid => App.Instance.Grid;
protected RectTransform Top => App.Instance.Top;
public virtual bool UsesGrid => true;
public virtual void Enter() { }
public virtual void Exit() { }
// 每幀:處理觸控與邏輯(在格子判定過期之前)
public virtual void Tick(List<GridTouch> touches) { }
// 每幀:格子更新後(生成新音符)
public virtual void LateTick() { }
// 返回鍵(對話框都關閉時)
public virtual void Back() => App.Go(new MainPage());
}
// 整個遊戲只有一個空場景:啟動時由這裡建立畫布、格子與第一個畫面
// 版面(畫布寬固定 1080):
// ┌ 安全區域 ┐
// │ Top │ 畫面內容(封面、標題、分數…),高度 = 剩下的空間
// │ Grid 5x6 │ 靠下;畫面太扁時縮小
// │ Footer │ UID / 版本
public class App : MonoBehaviour
{
public static App Instance { get; private set; }
public Grid Grid { get; private set; }
public RectTransform Top { get; private set; }
public RectTransform Overlay { get; private set; } // 對話框、結算
public RawImage Background { get; private set; } // 曲包影片
public AudioSource Music { get; private set; }
public GridInput Input { get; private set; }
public Page Current { get; private set; }
private const float FooterHeight = 90f;
private const float GridGap = 30f;
private const float MinTop = 460f;
private RectTransform safe;
private Text uidText;
private Rect lastSafe;
private Vector2Int lastSize;
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
static void Boot()
{
// 幀率上限 = 螢幕支援的最高更新率(Android 上 targetFrameRate = -1 代表 30fps)
QualitySettings.vSyncCount = 0;
double max = UnityEngine.Screen.currentResolution.refreshRateRatio.value;
foreach (var r in UnityEngine.Screen.resolutions)
if (r.refreshRateRatio.value > max) max = r.refreshRateRatio.value;
Application.targetFrameRate = Mathf.Max(60, Mathf.RoundToInt((float)max));
UnityEngine.Screen.sleepTimeout = SleepTimeout.NeverSleep;
PackStorage.Init();
var go = new GameObject("App");
DontDestroyOnLoad(go);
go.AddComponent<App>();
}
void Awake()
{
Instance = this;
Music = gameObject.AddComponent<AudioSource>();
Music.playOnAwake = false;
BuildEventSystem();
BuildCanvas();
Input = new GridInput(Grid);
Library.Create();
Library.Changed += () => (Current as ILibraryListener)?.LibraryChanged();
Library.DownloadRequested += code =>
{
if (!(Current is PlayPage) && !(Current is IntroPage)) Go(new ChoosePage(code));
else pendingDownload = code;
};
}
void Start()
{
Go(new IntroPage());
}
void BuildEventSystem()
{
var es = new GameObject("EventSystem", typeof(EventSystem), typeof(InputSystemUIInputModule));
DontDestroyOnLoad(es);
}
void BuildCanvas()
{
var root = new GameObject("Canvas", typeof(Canvas), typeof(CanvasScaler), typeof(GraphicRaycaster));
DontDestroyOnLoad(root);
var canvas = root.GetComponent<Canvas>();
canvas.renderMode = RenderMode.ScreenSpaceOverlay;
var scaler = root.GetComponent<CanvasScaler>();
scaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
scaler.referenceResolution = new Vector2(1080, 1920);
scaler.matchWidthOrHeight = 0f;
// 黑底 + 影片背景
var bg = Ui.Image(root.transform, null, Ui.Bg);
Ui.Stretch(bg.rectTransform);
Background = Ui.Rect(root.transform, "Video").gameObject.AddComponent<RawImage>();
Background.raycastTarget = false;
Background.enabled = false;
Ui.Stretch(Background.rectTransform);
safe = Ui.Rect(root.transform, "Safe");
Top = Ui.Rect(safe, "Top");
var gridHolder = Ui.Rect(safe, "GridHolder");
Ui.Stretch(gridHolder, 0, FooterHeight);
Grid = Grid.Create(gridHolder, Ui.Font);
var footer = Ui.Rect(safe, "Footer");
footer.anchorMin = Vector2.zero;
footer.anchorMax = new Vector2(1, 0);
footer.pivot = new Vector2(0.5f, 0);
footer.sizeDelta = new Vector2(0, FooterHeight);
uidText = Ui.Label(footer, "", 30, Ui.Muted, TextAnchor.MiddleLeft);
Ui.Stretch(uidText.rectTransform, 60, 0, 60, 0);
var ver = Ui.Label(footer, "version: Alpha " + Application.version, 30, Ui.Muted, TextAnchor.MiddleRight);
Ui.Stretch(ver.rectTransform, 60, 0, 60, 0);
Overlay = Ui.Stretch(Ui.Rect(root.transform, "Overlay"));
}
// 安全區域(瀏海、導覽列)與格子大小
void Layout()
{
var size = new Vector2Int(UnityEngine.Screen.width, UnityEngine.Screen.height);
Rect sa = UnityEngine.Screen.safeArea;
if (sa == lastSafe && size == lastSize) return;
lastSafe = sa;
lastSize = size;
safe.anchorMin = new Vector2(sa.xMin / size.x, sa.yMin / size.y);
safe.anchorMax = new Vector2(sa.xMax / size.x, sa.yMax / size.y);
safe.offsetMin = safe.offsetMax = Vector2.zero;
ApplyGridLayout();
}
void ApplyGridLayout()
{
float unitsPerPixel = 1080f / Mathf.Max(1, UnityEngine.Screen.width);
float safeH = lastSafe.height * unitsPerPixel;
bool grid = Current == null || Current.UsesGrid;
Grid.gameObject.SetActive(grid);
float gridScale = Mathf.Clamp((safeH - FooterHeight - GridGap - MinTop) / Grid.Height, 0.6f, 1f);
Grid.transform.localScale = Vector3.one * gridScale;
float bottom = grid ? FooterHeight + Grid.Height * gridScale + GridGap : FooterHeight;
Top.anchorMin = Vector2.zero;
Top.anchorMax = Vector2.one;
Top.offsetMin = new Vector2(0, bottom);
Top.offsetMax = Vector2.zero;
}
private string pendingDownload; // 開場、遊玩中收到的下載連結,離開後處理
public void Go(Page page)
{
if (pendingDownload != null && page is MainPage or ChoosePage)
{
page = new ChoosePage(pendingDownload);
pendingDownload = null;
}
Dialog.CloseAll();
Current?.Exit();
foreach (Transform child in Top) Destroy(child.gameObject);
Grid.ClearAll();
Background.enabled = false;
Input.IgnoreCurrentTouches();
Current = page;
lastSize = Vector2Int.zero; // 重新套用版面(畫面可能不用格子)
Layout();
RefreshFooter();
page.Enter();
}
public void RefreshFooter() => uidText.text = "UID: " + Prefs.UidText();
void Update()
{
Layout();
// Android 的返回鍵:舊版 Input 一定會對應到 Escape;新版 Input System 在部分裝置收不到
var kb = Keyboard.current;
bool back = UnityEngine.Input.GetKeyDown(KeyCode.Escape) || (kb != null && kb.escapeKey.wasPressedThisFrame);
if (back && !Dialog.HandleBack())
Current?.Back();
var touches = Input.Poll(Dialog.AnyOpen);
Current?.Tick(touches);
if (Grid.isActiveAndEnabled) Grid.Tick();
Current?.LateTick();
}
void OnApplicationPause(bool paused)
{
if (paused) (Current as IPausable)?.OnAppPause();
}
void OnApplicationQuit() => PlayerPrefs.Save();
}
// 曲包清單改變時要更新的畫面
public interface ILibraryListener
{
void LibraryChanged();
}
// 切到背景時要暫停的畫面(遊玩)
public interface IPausable
{
void OnAppPause();
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 7dababac1cb210545a1edfa37c46bed1
+8
View File
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 939b2bb37fbbddc4c94ddda61230a0ae
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
+277
View File
@@ -0,0 +1,277 @@
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using UnityEngine;
using UnityEngine.UI;
// 帳號:登入 / 註冊 / 信箱驗證 / 個人資訊
// 登入後手機上只存 token(不存密碼);舊版存的密碼會在進入個人資訊時換成 token 並刪除
public class AccountPage : Page
{
public override bool UsesGrid => false;
private RectTransform body;
private Text error;
private bool busy;
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));
if (Prefs.LoggedIn) ShowInfo();
else ShowLogin();
}
// 換一個面板:清掉內容,回傳新的 Column
RectTransform Panel(string title)
{
if (body != null) Object.Destroy(body.parent.parent.gameObject);
var holder = Ui.Stretch(Ui.Rect(Top, "Panel"), 60, 0, 60, 150);
body = Ui.Scroll(holder, 28, 10);
var t = Ui.Label(body, title, 64, Color.white);
t.fontStyle = FontStyle.Bold;
Ui.Height(t, 110);
error = Ui.Label(body, "", 36, Ui.Danger);
error.transform.SetAsLastSibling();
return body;
}
InputField Field(string label, string placeholder, InputField.ContentType type = InputField.ContentType.Standard)
{
Ui.Label(body, label, 36, Ui.Muted, TextAnchor.MiddleLeft);
return Ui.Height(Ui.Input(body, placeholder, type), 120);
}
Button Action(string label, System.Action onClick, bool primary = false)
=> Ui.Height(Ui.Button(body, label, () => { if (!busy) onClick(); }, 46, primary), 120);
void ShowError(string msg)
{
error.text = msg;
error.transform.SetAsLastSibling();
}
// ---------- 登入 ----------
void ShowLogin()
{
Panel("登入帳號");
var id = Field("ID", "輸入你的 ID");
var pw = Field("密碼", "輸入你的密碼", InputField.ContentType.Password);
Action("登入", () => App.StartCoroutine(Login(id.text.Trim(), pw.text)), primary: true);
Action("註冊帳號", ShowRegister);
Ui.Label(body, "曲包網站也使用同一組帳號登入", 32, Ui.Muted);
}
IEnumerator Login(string name, string password)
{
if (name == "" || password == "") { ShowError("請輸入 ID 與密碼"); yield break; }
busy = true;
Api.Response r = null;
yield return Api.Game(new Dictionary<string, object> { ["request"] = "login", ["name"] = name, ["password"] = password }, x => r = x);
busy = false;
if (r.error != null)
{
ShowError(r.error == "cant_find_name" || r.error == "password_wrong" ? "ID 或密碼錯誤" : "登入失敗:" + r.error);
yield break;
}
SaveLogin(r.Int("uid"), r.Str("token"), r.Str("email"));
ShowInfo();
}
static void SaveLogin(int uid, string token, string email)
{
PlayerPrefs.SetInt(Prefs.Uid, uid);
PlayerPrefs.SetString(Prefs.Token, token);
PlayerPrefs.SetString(Prefs.Email, email);
PlayerPrefs.DeleteKey(Prefs.LegacyPassword);
PlayerPrefs.Save();
}
// ---------- 註冊 ----------
void ShowRegister()
{
Panel("註冊帳號");
var email = Field("電子信箱", "輸入你的信箱", InputField.ContentType.EmailAddress);
var id = Field("ID", "自訂一個獨一無二 ID");
var pw = Field("密碼", "至少 6 位,包含英文與數字", InputField.ContentType.Password);
var pw2 = Field("確認密碼", "再輸入一次密碼", InputField.ContentType.Password);
Action("送出", () => App.StartCoroutine(Register(email.text.Trim(), id.text.Trim(), pw.text, pw2.text)), primary: true);
Action("已有帳號,登入", ShowLogin);
}
IEnumerator Register(string email, string id, string password, string password2)
{
string problem =
!Regex.IsMatch(email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$") ? "請輸入有效的電子郵件地址" :
id.Length < 4 ? "ID 長度不足 4 位" :
id.Length > 30 ? "ID 最多 30 字" :
password.Length < 6 ? "密碼長度不足 6 位" :
!Regex.IsMatch(password, @"^(?=.*[a-zA-Z])(?=.*\d).+$") ? "密碼需包含英文與數字" :
password != password2 ? "兩次輸入密碼不一致" : null;
if (problem != null) { ShowError(problem); yield break; }
busy = true;
Api.Response r = null;
yield return Api.Game(new Dictionary<string, object> { ["request"] = "create_user", ["email"] = email, ["name"] = id, ["password"] = password }, x => r = x);
busy = false;
if (r.error != null)
{
ShowError(r.error == "email_exists" ? "信箱已被註冊" : r.error == "name_exists" ? "ID 已被使用" : "建立帳號失敗:" + r.error);
yield break;
}
SaveLogin(r.Int("uid"), r.Str("token"), email);
App.RefreshFooter();
yield return SendCode(email);
}
// ---------- 信箱驗證 ----------
IEnumerator SendCode(string email)
{
busy = true;
Api.Response r = null;
yield return Api.Verify(new Dictionary<string, object> { ["game"] = "lunchpad", ["email"] = email, ["code"] = "", ["password"] = "" }, x => r = x);
busy = false;
if (r.error != null && r.error != "too_many_requests")
{
ShowError("驗證信寄送失敗:" + r.error);
yield break;
}
ShowVerify(email);
if (r.error == "too_many_requests") ShowError("驗證信已寄出,請稍候再重新發送");
}
void ShowVerify(string email)
{
Panel("驗證信箱");
Ui.Label(body, $"驗證信已寄到 {email}\n請檢查收件匣或垃圾郵件,驗證碼 5 分鐘內有效", 36, Ui.Muted);
var code = Field("驗證碼", "6 位數字", InputField.ContentType.IntegerNumber);
code.characterLimit = 6;
Action("驗證", () => App.StartCoroutine(Verify(email, code.text.Trim())), primary: true);
Action("重新發送", () => App.StartCoroutine(SendCode(email)));
Action("稍後再驗證", ShowInfo);
}
IEnumerator Verify(string email, string code)
{
busy = true;
Api.Response r = null;
yield return Api.Verify(new Dictionary<string, object>
{
["game"] = "lunchpad", ["email"] = email, ["code"] = code, ["password"] = Credential(),
}, x => r = x);
busy = false;
if (r.error != null)
{
ShowError(r.error switch
{
"wrong_code" => "驗證碼錯誤",
"expired" => "驗證碼已過期,請重新發送",
"not_requested" => "請先發送驗證碼",
_ => "驗證失敗:" + r.error,
});
yield break;
}
Toast.Show("信箱驗證完成");
ShowInfo();
}
// 驗證用憑證:Token 優先,舊版才用密碼
static string Credential()
{
string token = PlayerPrefs.GetString(Prefs.Token, "");
return token != "" ? token : PlayerPrefs.GetString(Prefs.LegacyPassword, "");
}
// ---------- 個人資訊 ----------
void ShowInfo()
{
App.RefreshFooter();
Panel("個人資訊");
var info = Ui.Label(body, "讀取中…", 40, Ui.TextColor, TextAnchor.UpperLeft);
info.lineSpacing = 1.3f;
var verifyButton = Action("驗證信箱", () => App.StartCoroutine(SendCode(PlayerPrefs.GetString(Prefs.Email, ""))));
verifyButton.gameObject.SetActive(false);
Action("重新整理", ShowInfo);
Action("登出", LogOut);
App.StartCoroutine(LoadInfo(info, verifyButton));
}
IEnumerator LoadInfo(Text info, Button verifyButton)
{
string token = PlayerPrefs.GetString(Prefs.Token, "");
string password = PlayerPrefs.GetString(Prefs.LegacyPassword, "");
Api.Response r = null;
yield return Api.Game(new Dictionary<string, object>
{
["request"] = "person_info", ["uid"] = Prefs.UserId, ["token"] = token,
["password"] = token == "" ? password : null,
}, x => r = x);
if (info == null) yield break; // 已經換面板
if (r.error != null)
{
info.text = r.error == "auth_failed" ? "登入已過期,請重新登入" : "載入失敗:" + r.error;
if (r.error == "auth_failed") ClearLogin();
yield break;
}
PlayerPrefs.SetString(Prefs.Name, r.Str("name"));
PlayerPrefs.SetString(Prefs.CreateTime, r.Str("create_time"));
PlayerPrefs.SetString(Prefs.AccountType, r.Str("account_type"));
PlayerPrefs.SetString(Prefs.Email, r.Str("email"));
PlayerPrefs.SetInt(Prefs.EmailVerified, r.Int("email_v"));
PlayerPrefs.Save();
App.RefreshFooter();
// 舊版只存了密碼:重新登入換取 Token,並刪除手機上的密碼
if (token == "" && password != "")
{
Api.Response login = null;
yield return Api.Game(new Dictionary<string, object> { ["request"] = "login", ["name"] = r.Str("name"), ["password"] = password }, x => login = x);
if (login.error == null && login.Str("token") != "")
SaveLogin(Prefs.UserId, login.Str("token"), r.Str("email"));
}
string type = r.Str("account_type") switch { "R" => "玩家", "A" => "Alpha 測試", "B" => "Beta 測試", "D" => "開發者", var t => t };
bool verified = r.Int("email_v") == 1;
info.text =
$"使用者號碼 {Prefs.UidText()}\n" +
$"顯示名稱  {r.Str("name")}\n" +
$"帳號類型  {type}\n" +
$"建立日期  {r.Str("create_time")}\n" +
$"電子信箱  {MaskEmail(r.Str("email"))} {(verified ? "<color=#7DD67D>已驗證</color>" : "<color=#FF6060>未驗證</color>")}";
verifyButton.gameObject.SetActive(!verified);
}
static string MaskEmail(string email)
{
int at = email.IndexOf('@');
return at < 0 ? email : email.Substring(0, Mathf.Min(2, at)) + "*****" + email.Substring(at);
}
void LogOut()
{
string token = PlayerPrefs.GetString(Prefs.Token, "");
if (token != "")
App.StartCoroutine(Api.Game(new Dictionary<string, object> { ["request"] = "logout", ["token"] = token }, _ => { }));
ClearLogin();
ShowLogin();
}
void ClearLogin()
{
foreach (var k in new[] { Prefs.Token, Prefs.Uid, Prefs.LegacyPassword, Prefs.Name, Prefs.AccountType, Prefs.CreateTime, Prefs.EmailVerified })
PlayerPrefs.DeleteKey(k);
PlayerPrefs.Save();
App.RefreshFooter();
}
public override void Back() => App.Go(new MainPage());
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 2095ee3cdc687d1469892a47e49f4777
+393
View File
@@ -0,0 +1,393 @@
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();
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 9ff06c2deef0cee4ca0c62902b0d3ced
+96
View File
@@ -0,0 +1,96 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
// 開場:STHKM3 → 戴上耳機 → 閃爍警告;點擊跳到下一張
// 第一次開啟且還沒有儲存權限時,結束後詢問是否使用手機根目錄的 Rhyculator/package
public class IntroPage : Page
{
private static readonly float[] Durations = { 1.885f, 1.846f, 1.846f };
public override bool UsesGrid => false;
private readonly List<GameObject> cards = new List<GameObject>();
private int index = -1;
private float nextAt;
public override void Enter()
{
cards.Add(ImageCard("Start_1", null));
cards.Add(ImageCard("Start_2", "戴上耳機以獲得最佳體驗"));
cards.Add(TextCard("本遊戲包含大量閃爍特效\n請斟酌遊玩"));
Next();
}
GameObject ImageCard(string sprite, string caption)
{
var card = Ui.Stretch(Ui.Rect(Top, sprite));
var img = Ui.Image(card, Sprites.Get(sprite), Color.white);
img.preserveAspect = true;
Ui.Place(img.rectTransform, new Vector2(0.5f, 0.5f), new Vector2(0, caption != null ? 120 : 0), new Vector2(1080, 720));
if (caption != null)
{
var t = Ui.Label(card, caption, 64, Color.white);
Ui.Place(t.rectTransform, new Vector2(0.5f, 0.5f), new Vector2(0, -220), new Vector2(1000, 120));
}
card.gameObject.SetActive(false);
return card.gameObject;
}
GameObject TextCard(string text)
{
var t = Ui.Label(Top, text, 64, Color.white);
t.lineSpacing = 1.3f;
Ui.Stretch(t.rectTransform, 40, 0, 40, 0);
t.gameObject.SetActive(false);
return t.gameObject;
}
void Next()
{
if (index >= 0) cards[index].SetActive(false);
index++;
if (index >= cards.Count)
{
Finish();
return;
}
cards[index].SetActive(true);
nextAt = -1; // 從第一個畫出來的幀開始計時(剛啟動的前幾幀很慢)
}
public override void Tick(List<GridTouch> touches)
{
if (index >= cards.Count) return;
if (nextAt < 0)
{
if (Time.unscaledDeltaTime < 0.1f) nextAt = Time.unscaledTime + Durations[index];
return;
}
if (Time.unscaledTime >= nextAt || GridInput.AnyNewTap()) Next();
}
public override void Back() => Next();
void Finish()
{
if (!PackStorage.SupportsShared || PackStorage.HasSharedAccess() || PlayerPrefs.GetInt(Prefs.StorageAsked, 0) == 1)
{
App.Go(new MainPage());
return;
}
PlayerPrefs.SetInt(Prefs.StorageAsked, 1);
var d = new Dialog(App.Overlay, "曲包資料夾",
"允許「所有檔案存取權」後,曲包會放在手機的\n<color=#FF66C4>Rhyculator/package</color>\n" +
"接上電腦或用檔案管理員就能直接放入 .zip 曲包,像插上隨身碟一樣。\n\n" +
"不允許也可以玩,曲包會放在 app 自己的資料夾。之後可在設定裡更改。");
d.cancellable = false;
d.AddClose("先不要", () => App.Go(new MainPage()));
d.AddClose("前往授權", () =>
{
PackStorage.RequestSharedAccess();
App.Go(new MainPage());
}, primary: true);
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 5a78ae78e1cfbcc4c9a4917bdf846ae2
+148
View File
@@ -0,0 +1,148 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
// 主選單:長按中間開始;上排帳號 / 設定 / 曲包網站;背景播放主題曲與它的譜面
// 點背景音符會顯示 Early / Late 毫秒數(可當延遲校正參考)
public class MainPage : Page, ILibraryListener
{
private const float HoldSeconds = 1f;
private const int HoldX = 2, HoldY = 2;
private ChartPlayer chart;
private Text info, offset;
private int holdFinger = -1;
private float holdStart;
public override void Enter()
{
var title = Ui.Label(Top, "Rhyculator", 140, Color.white);
title.fontStyle = FontStyle.Bold;
Ui.Place(title.rectTransform, new Vector2(0.5f, 0.5f), new Vector2(0, 60), new Vector2(1080, 200));
info = Ui.Label(Top, "", 40, Ui.Muted);
Ui.Place(info.rectTransform, new Vector2(0.5f, 0.5f), new Vector2(0, -70), new Vector2(1000, 60));
offset = Ui.Label(Top, "", 44, Ui.Accent);
Ui.Place(offset.rectTransform, new Vector2(0.5f, 0f), new Vector2(0, 10), new Vector2(1000, 70));
LibraryChanged();
Grid.SetIcon(1, 5, Sprites.Get("Display account"));
Grid.SetIcon(2, 5, Sprites.Get("Display setting"));
Grid.SetIcon(3, 5, Sprites.Get("Display global"));
Grid.SetIcon(HoldX, HoldY, Sprites.Get("HoldStart"));
Grid.SetIcon(1, 2, Sprites.Get("ArrowRight"));
Grid.SetIcon(3, 2, Sprites.Get("ArrowLeft"));
Grid.SetIcon(2, 1, Sprites.Get("ArrowUp"));
Grid.SetIcon(2, 3, Sprites.Get("ArrowDown"));
StartTheme();
}
public void LibraryChanged()
{
int n = Library.Songs.Count;
info.text = !Library.Loaded ? "讀取曲包中…" : n > 0 ? $"已載入 {n} 個曲包 長按中間開始" : "還沒有曲包:長按中間開始後可輸入代碼下載";
}
void StartTheme()
{
var music = App.Music;
var clip = Resources.Load<AudioClip>("MainTheme/music");
var sheet = Resources.Load<TextAsset>("MainTheme/sheet");
if (clip == null || sheet == null) return;
try { chart = new ChartPlayer(ChartLoader.Parse(sheet.text, 0, out _)); }
catch (System.Exception e) { Debug.LogWarning("[Main] 主題譜面讀取失敗:" + e.Message); }
// 從帳號 / 設定回來時主題曲還在播:接著播,時鐘對齊目前位置
if (music.clip == clip && music.isPlaying)
{
double start = AudioSettings.dspTime - music.time;
SongClock.Begin(start);
chart?.Seek(music.time);
return;
}
music.Stop();
music.clip = clip;
music.loop = false;
double dspStart = AudioSettings.dspTime + 0.5;
music.PlayScheduled(dspStart);
SongClock.Begin(dspStart);
chart?.Seek(0);
}
public override void Tick(List<GridTouch> touches)
{
// 主題曲播完:重新開始
if (App.Music.clip != null && !App.Music.isPlaying && SongClock.Running && SongClock.Now > App.Music.clip.length)
StartTheme();
foreach (var t in touches)
{
if (t.ended)
{
if (t.fingerId == holdFinger) StopHold();
continue;
}
if (!t.OnCell) continue;
if (!t.began)
{
Grid.Flash(t.x, t.y, CellFlash.White);
continue;
}
if (t.x == HoldX && t.y == HoldY && holdFinger < 0)
{
holdFinger = t.fingerId;
holdStart = Time.unscaledTime;
Grid.StartRing(t.x, t.y, HoldSeconds);
Grid.Flash(t.x, t.y, CellFlash.Blue);
}
else if (t.y == 5 && t.x == 1) App.Go(new AccountPage());
else if (t.y == 5 && t.x == 2) App.Go(new SettingsPage());
else if (t.y == 5 && t.x == 3) Application.OpenURL(ServerConfig.GameServerUrl + "/");
else JudgeBackground(t);
}
if (holdFinger >= 0 && Time.unscaledTime - holdStart >= HoldSeconds)
{
holdFinger = -1;
App.Go(new ChoosePage());
}
}
public override void LateTick()
{
if (chart != null && SongClock.Running) chart.Tick(Grid, SongClock.Now);
}
void StopHold()
{
holdFinger = -1;
Grid.StopRing(HoldX, HoldY);
}
void JudgeBackground(GridTouch t)
{
if (!Grid.HasNote(t.x, t.y)) return;
double delta = SongClock.Now - t.pressAge - Grid.HitTime(t.x, t.y);
Judgement j = NoteJudge.Evaluate(delta);
if (j == Judgement.None || j == Judgement.Miss) return;
Grid.Flash(t.x, t.y, PlayPage.FlashFor(j));
Grid.ClearNote(t.x, t.y);
int ms = (int)System.Math.Round(delta * 1000);
offset.text = (ms < 0 ? "Early " : "Late ") + System.Math.Abs(ms) + "ms";
}
public override void Back()
{
var d = new Dialog(App.Overlay, "離開遊戲?");
d.AddClose("取消");
d.AddClose("離開", Application.Quit, primary: true);
}
public override void Exit()
{
Grid.StopRing(HoldX, HoldY);
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 04825755a7bcb6243909e4a5e77d4a2f
+438
View File
@@ -0,0 +1,438 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
using UnityEngine.Video;
// 遊玩:載入曲包的音樂、譜面與影片,判定、計分,結束後上傳成績並顯示結算
// 音樂用 PlayScheduled 排在 DSP 時鐘上,音符時間與音訊同一個時間基準,不會累積誤差
public class PlayPage : Page, IPausable
{
private const double LeadIn = 1.0; // 音樂開始前的準備時間,讓開頭的音符也有完整的出現動畫
private const double ResumeRewind = 1.0; // 暫停後接續時倒回的秒數
private const int HoldFullScore = 212;
private const int SlideScore = 106;
private const float VideoAlpha = 0.4f;
private readonly SongInfo song;
private readonly int level;
private enum State { Loading, Playing, Paused, Finished }
private State state = State.Loading;
private ChartPlayer chart;
private AudioClip clip;
private VideoPlayer video;
private RenderTexture videoTexture;
private bool videoStarted;
private readonly PlayResult result = new PlayResult();
private Text scoreText, comboText;
private RectTransform progress;
private Button pauseButton;
private Dialog pauseDialog;
private GameObject overlay;
// 按住中的 Hold(可同時多個)
private class ActiveHold
{
public int x, y, fingerId;
public double hitTime, duration;
public Judgement head;
}
private readonly List<ActiveHold> holds = new List<ActiveHold>();
public PlayPage(SongInfo song, int level)
{
this.song = song;
this.level = level;
}
public override void Enter()
{
Library.Paused = true;
App.Music.Stop();
SongClock.Stop();
Grid.NoteExpired += OnExpired;
var title = Ui.Label(Top, $"{song.name} <color=#{ColorUtility.ToHtmlStringRGB(Ui.LevelColors[level])}>{SongInfo.LevelName(level).ToUpper()} {song.levelNum[level]}</color>", 34, Ui.Muted);
title.horizontalOverflow = HorizontalWrapMode.Overflow;
Ui.Place(title.rectTransform, new Vector2(0.5f, 1), new Vector2(0, -50), new Vector2(760, 60));
pauseButton = Ui.Button(Top, "II", Pause, 44);
Ui.Place((RectTransform)pauseButton.transform, new Vector2(1, 1), new Vector2(-40, -30), new Vector2(120, 100));
scoreText = Ui.Label(Top, "載入中…", 120, Color.white);
scoreText.fontStyle = FontStyle.Bold;
Ui.Place(scoreText.rectTransform, new Vector2(0.5f, 0.5f), new Vector2(0, 0), new Vector2(1000, 160));
comboText = Ui.Label(Top, "", 44, Ui.Accent);
Ui.Place(comboText.rectTransform, new Vector2(0.5f, 0.5f), new Vector2(0, -110), new Vector2(1000, 60));
var bar = Ui.Image(Top, null, new Color(1, 1, 1, 0.12f));
Ui.Place(bar.rectTransform, new Vector2(0.5f, 0), new Vector2(0, 0), new Vector2(980, 8));
progress = Ui.Image(bar.transform, null, Ui.Accent).rectTransform;
progress.anchorMin = Vector2.zero;
progress.anchorMax = new Vector2(0, 1);
progress.offsetMin = progress.offsetMax = Vector2.zero;
App.StartCoroutine(Load());
}
// ---------- 載入 ----------
IEnumerator Load()
{
try
{
chart = new ChartPlayer(ChartLoader.LoadFile(song.ChartPath(level), song.offsetMs, out int skipped));
if (skipped > 0) Debug.LogWarning($"[Play] {song.id} 略過 {skipped} 個無法使用的音符");
}
catch (Exception e)
{
Fail("譜面讀取失敗:" + e.Message);
yield break;
}
string musicPath = song.MusicPath;
if (musicPath == null) { Fail("曲包沒有音樂"); yield break; }
using (var www = LoadAudio(musicPath))
{
yield return www.SendWebRequest();
if (state != State.Loading) yield break; // 載入中就離開了
if (www.result != UnityWebRequest.Result.Success) { Fail("音樂載入失敗:" + www.error); yield break; }
clip = DownloadHandlerAudioClip.GetContent(www);
}
if (clip == null || clip.length <= 0f) { Fail("音樂無法解碼"); yield break; }
if (Prefs.GetBool(Prefs.VideoBackground, true) && song.VideoPath != null) SetupVideo(song.VideoPath);
var music = App.Music;
music.clip = clip;
music.loop = false;
music.time = 0;
double start = AudioSettings.dspTime + LeadIn;
music.PlayScheduled(start);
SongClock.Begin(start);
state = State.Playing;
scoreText.text = "0";
Debug.Log($"[Play] {song.id} {SongInfo.LevelName(level)}: {chart.Count} events, clip {clip.length:0.0}s");
}
void Fail(string message)
{
state = State.Finished;
Toast.Show(message);
App.Go(new ChoosePage());
}
// 本機檔案 → UnityWebRequest 用的 file:// 網址(處理空白與 Windows 路徑)
public static string FileUrl(string path) => new Uri(Path.GetFullPath(path)).AbsoluteUri;
// ogg / mp3 保持壓縮(整首不解壓,省記憶體);wav 開壓縮模式在 Android 上會讓主執行緒卡死,直接載入
public static UnityWebRequest LoadAudio(string path)
{
AudioType type = Path.GetExtension(path).ToLowerInvariant() switch
{
".ogg" => AudioType.OGGVORBIS,
".mp3" => AudioType.MPEG,
_ => AudioType.WAV,
};
var www = UnityWebRequestMultimedia.GetAudioClip(FileUrl(path), type);
((DownloadHandlerAudioClip)www.downloadHandler).compressed = type != AudioType.WAV;
return www;
}
// 曲包的 video.mp4:畫在格子後方當背景,聲音一律用 music 檔
void SetupVideo(string path)
{
var go = new GameObject("PackVideo");
go.transform.SetParent(App.transform, false);
video = go.AddComponent<VideoPlayer>();
video.playOnAwake = false;
video.source = VideoSource.Url;
video.url = FileUrl(path);
video.renderMode = VideoRenderMode.RenderTexture;
video.audioOutputMode = VideoAudioOutputMode.None;
video.isLooping = false;
video.skipOnDrop = true;
video.prepareCompleted += vp =>
{
videoTexture = new RenderTexture((int)vp.width, (int)vp.height, 0);
vp.targetTexture = videoTexture;
var bg = App.Background;
bg.texture = videoTexture;
bg.color = new Color(1, 1, 1, VideoAlpha);
var fit = bg.GetComponent<AspectRatioFitter>() ?? bg.gameObject.AddComponent<AspectRatioFitter>();
fit.aspectMode = AspectRatioFitter.AspectMode.EnvelopeParent;
fit.aspectRatio = (float)vp.width / Mathf.Max(1, vp.height);
};
video.Prepare();
}
// ---------- 遊玩 ----------
public override void Tick(List<GridTouch> touches)
{
if (state != State.Playing) return;
double now = SongClock.Now;
if (video != null && !videoStarted && now >= 0 && video.isPrepared)
{
if (now > 0.05) video.time = now; // 準備得比音樂慢:從目前位置接上
video.Play();
App.Background.enabled = true;
videoStarted = true;
}
// Hold 按滿時間 → 自動結算
for (int i = holds.Count - 1; i >= 0; i--)
if (now >= holds[i].hitTime + holds[i].duration)
FinishHold(holds[i], now);
foreach (var t in touches)
{
if (t.ended)
{
var h = holds.Find(a => a.fingerId == t.fingerId);
if (h != null) FinishHold(h, now);
continue;
}
if (!t.OnCell) continue;
if (!Grid.HasNote(t.x, t.y))
{
Grid.Flash(t.x, t.y, CellFlash.White); // 空按也亮白色(不覆蓋判定色)
continue;
}
// 按下的精確時間(觸控事件時間回推),不受幀率影響
double pressTime = now - t.pressAge;
switch (Grid.NoteTypeAt(t.x, t.y))
{
case NoteType.Tap:
if (t.began) ProcessTap(t.x, t.y, pressTime);
break;
case NoteType.Hold:
if (t.began) StartHold(t, pressTime, now);
break;
case NoteType.Slide:
// 不提早判定:到達判定點後手指在格子上即算接到(可延遲到判定窗結束)
if (now >= Grid.HitTime(t.x, t.y))
{
Grid.Flash(t.x, t.y, CellFlash.Blue);
Grid.ClearNote(t.x, t.y);
AddScore(Judgement.Perfect, SlideScore);
}
break;
}
}
if (clip != null)
{
progress.anchorMax = new Vector2(Mathf.Clamp01((float)(now / clip.length)), 1);
// 歌曲(含結尾緩衝)結束
if (now > clip.length + NoteJudge.BadWindow + 0.5) App.StartCoroutine(Finish());
}
}
public override void LateTick()
{
if (state == State.Playing) chart.Tick(Grid, SongClock.Now);
}
// 只做判定,不給分、不清除(None = 不在判定範圍)
Judgement JudgeHead(int x, int y, double pressTime)
{
Judgement j = NoteJudge.Evaluate(pressTime - Grid.HitTime(x, y));
return j == Judgement.Miss ? Judgement.None : j;
}
void ProcessTap(int x, int y, double pressTime)
{
Judgement j = JudgeHead(x, y, pressTime);
if (j == Judgement.None) return;
Grid.Flash(x, y, FlashFor(j));
AddScore(j, NoteJudge.Score(j));
Grid.ClearNote(x, y);
}
void StartHold(GridTouch t, double pressTime, double now)
{
int holdMs = Grid.HoldMs(t.x, t.y);
double hit = Grid.HitTime(t.x, t.y);
Judgement j = JudgeHead(t.x, t.y, pressTime);
if (j == Judgement.None || holdMs <= 0) return;
// Hold 頭判先記住,按滿才給分
Grid.Flash(t.x, t.y, FlashFor(j));
Grid.ClearNote(t.x, t.y);
var h = new ActiveHold { x = t.x, y = t.y, fingerId = t.fingerId, hitTime = hit, duration = holdMs / 1000.0, head = j };
holds.Add(h);
Grid.StartRing(t.x, t.y, (float)(hit + h.duration - now));
}
void FinishHold(ActiveHold h, double now)
{
if (now >= h.hitTime + h.duration - 0.02)
{
// 按滿:頭判分數 + 持續段分數
Grid.Flash(h.x, h.y, CellFlash.Blue);
AddScore(h.head, NoteJudge.Score(h.head) + HoldFullScore);
}
else
{
// 提早放開:亮紅色、不給分
Grid.Flash(h.x, h.y, CellFlash.Red);
AddScore(Judgement.Miss, 0);
}
Grid.StopRing(h.x, h.y);
holds.Remove(h);
}
void OnExpired(int x, int y, NoteType type)
{
if (state != State.Playing) return;
Grid.Flash(x, y, CellFlash.Red);
AddScore(Judgement.Miss, 0);
}
void AddScore(Judgement j, int amount)
{
result.Add(j, amount);
scoreText.text = result.score.ToString();
comboText.text = result.combo >= 5 ? $"{result.combo} COMBO" : "";
}
public static CellFlash FlashFor(Judgement j) => j switch
{
Judgement.Perfect => CellFlash.Blue,
Judgement.Fast => CellFlash.Green,
Judgement.Slow => CellFlash.Orange,
_ => CellFlash.Red,
};
// ---------- 暫停 ----------
public void OnAppPause()
{
if (state == State.Playing) Pause();
}
void Pause()
{
if (state != State.Playing) return;
state = State.Paused;
SongClock.Pause();
App.Music.Pause();
if (video != null && video.isPlaying) video.Pause();
// 按住中的 Hold 以目前進度結算(放開的手指在暫停期間收不到)
for (int i = holds.Count - 1; i >= 0; i--) FinishHold(holds[i], SongClock.Now);
pauseDialog = new Dialog(App.Overlay, "暫停");
pauseDialog.cancellable = false;
pauseDialog.AddClose("離開", () => Quit());
pauseDialog.AddClose("重來", () => App.Go(new PlayPage(song, level)));
pauseDialog.AddClose("繼續", Resume, primary: true);
}
void Resume()
{
// 倒回一點再接續,讓玩家有時間準備
double resumeAt = SongClock.PausedAt - ResumeRewind;
var music = App.Music;
double dsp = AudioSettings.dspTime + 0.1;
if (resumeAt >= 0)
{
music.time = (float)resumeAt;
music.PlayScheduled(dsp);
SongClock.Resume(resumeAt, dsp);
}
else
{
music.time = 0;
music.PlayScheduled(dsp - resumeAt);
SongClock.Resume(0, dsp - resumeAt);
}
// 影片在 Tick 裡對齊目前時間後重新播放
if (video != null && video.isPlaying) video.Pause();
videoStarted = false;
App.Input.IgnoreCurrentTouches();
state = State.Playing;
}
public override void Back()
{
if (state == State.Playing) Pause();
else if (state == State.Finished && overlay != null) Quit();
else if (state == State.Loading) Quit();
}
void Quit()
{
state = State.Finished;
App.Go(new ChoosePage());
}
// ---------- 結算 ----------
IEnumerator Finish()
{
state = State.Finished;
pauseButton.gameObject.SetActive(false);
PlayResult.Last = result;
Debug.Log($"[Play] song={song.id} level={level} notes={chart.Count} {result}");
string status;
if (!Prefs.LoggedIn) status = "未登入,成績不會上傳";
else
{
Api.Response r = null;
// 曲包不在伺服器上註冊過時,伺服器會用這些資訊建立歌曲資料
yield return Api.Game(new Dictionary<string, object>
{
["request"] = "user_play",
["uid"] = Prefs.UserId,
["token"] = PlayerPrefs.GetString(Prefs.Token, ""),
["song"] = song.id,
["title"] = song.name,
["artist"] = song.artist,
["bpm"] = song.bpm,
["duration_sec"] = Mathf.RoundToInt(clip.length),
["level"] = level,
["level_num"] = song.levelNum[level],
["score"] = result.score,
}, x => r = x);
status = r.error == null ? "成績已上傳" : "成績上傳失敗:" + r.error;
}
if (App.Current != this) yield break;
scoreText.gameObject.SetActive(false);
comboText.gameObject.SetActive(false);
overlay = ResultOverlay.Show(result, chart.Count, Ui.Font, status);
// 等待一次新的點擊(忽略結算出現前就按著的手指)
yield return new WaitForSecondsRealtime(0.6f);
while (App.Current == this && !GridInput.AnyNewTap()) yield return null;
if (App.Current == this) Quit();
}
public override void Exit()
{
state = State.Finished;
Grid.NoteExpired -= OnExpired;
Library.Paused = false;
SongClock.Stop();
App.Music.Stop();
if (App.Music.clip == clip) App.Music.clip = null;
if (clip != null) UnityEngine.Object.Destroy(clip);
if (video != null) UnityEngine.Object.Destroy(video.gameObject);
if (videoTexture != null)
{
App.Background.texture = null;
videoTexture.Release();
UnityEngine.Object.Destroy(videoTexture);
}
if (overlay != null) UnityEngine.Object.Destroy(overlay);
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 3e2f63f884d58af43bafffd2c824e590
+202
View File
@@ -0,0 +1,202 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem.EnhancedTouch;
using UnityEngine.UI;
using Touch = UnityEngine.InputSystem.EnhancedTouch.Touch;
// 設定:延遲校正、曲包資料夾位置、背景影片
// 延遲校正:播放節拍聲,玩家只聽聲音跟著點擊;取偏差中位數存成 AudioOffsetMs
public class SettingsPage : Page, ILibraryListener
{
private const double Bpm = 100;
private const int BeatCount = 16;
private const int WarmupBeats = 4;
private const double LeadIn = 1.0;
private double Interval => 60.0 / Bpm;
public override bool UsesGrid => false;
private Text offsetText, statusText, beatText, storageText;
private Button startButton, accessButton, videoButton;
private AudioClip clickTrack;
private bool running, hadAccess;
private readonly List<double> deltas = new List<double>();
private readonly HashSet<int> ignoredTouches = new HashSet<int>();
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 title = Ui.Label(Top, "設定", 64, Color.white);
Ui.Place(title.rectTransform, new Vector2(0.5f, 1), new Vector2(0, -30), new Vector2(600, 100));
var holder = Ui.Stretch(Ui.Rect(Top, "Body"), 40, 0, 40, 160);
var col = Ui.Scroll(holder, 26, 10);
Section(col, "延遲校正");
Ui.Label(col, "戴上平常玩的耳機,按「開始」後只聽聲音、跟著節拍點擊螢幕任意處\n前 4 拍為暖身不計分", 36, Ui.Muted);
offsetText = Ui.Label(col, "", 52, Ui.Accent);
beatText = Ui.Height(Ui.Label(col, "", 96, Color.white), 120);
statusText = Ui.Label(col, "", 36, Ui.Muted);
startButton = Ui.Height(Ui.Button(col, "開始", StartCalibration, 48, primary: true), 120);
var row = Ui.Height(Ui.Row(col), 110);
Ui.Button(row, "-5 ms", () => SetOffset(Offset - 5), 40);
Ui.Button(row, "重設", () => SetOffset(0), 40);
Ui.Button(row, "+5 ms", () => SetOffset(Offset + 5), 40);
Ui.Label(col, "正值 = 聲音比畫面晚(藍牙耳機通常為正)", 32, Ui.Muted);
Section(col, "曲包資料夾");
storageText = Ui.Label(col, "", 36, Ui.Muted);
accessButton = Ui.Height(Ui.Button(col, "允許「所有檔案存取權」", PackStorage.RequestSharedAccess, 42), 110);
Ui.Height(Ui.Button(col, "重新掃描", Library.Rescan, 42), 110);
Section(col, "畫面");
videoButton = Ui.Height(Ui.Button(col, "", ToggleVideo, 42), 110);
Ui.Label(col, $"\nRhyculator Alpha {Application.version}", 30, Ui.Muted);
EnhancedTouchSupport.Enable();
clickTrack = BuildClickTrack();
hadAccess = PackStorage.HasSharedAccess();
RefreshOffset();
LibraryChanged();
RefreshVideo();
}
static void Section(Transform parent, string name)
{
var t = Ui.Label(parent, name, 48, Color.white, TextAnchor.MiddleLeft);
t.fontStyle = FontStyle.Bold;
Ui.Height(t, 90);
}
public void LibraryChanged()
{
bool shared = PackStorage.HasSharedAccess();
string where = ChoosePage.DisplayPath(PackStorage.PackageDir);
storageText.text = $"<color=#FF66C4>{where}</color>\n目前 {Library.Songs.Count} 個曲包 · " +
(shared ? "已允許所有檔案存取權" : PackStorage.SupportsShared ? "未授權:曲包放在 app 自己的資料夾" : "");
accessButton.gameObject.SetActive(PackStorage.SupportsShared && !shared);
}
// ---------- 背景影片 ----------
void ToggleVideo()
{
Prefs.SetBool(Prefs.VideoBackground, !Prefs.GetBool(Prefs.VideoBackground, true));
RefreshVideo();
}
void RefreshVideo() => Ui.SetButtonText(videoButton, "曲包背景影片:" + (Prefs.GetBool(Prefs.VideoBackground, true) ? "開" : "關"));
// ---------- 延遲校正 ----------
static int Offset => PlayerPrefs.GetInt(Prefs.AudioOffsetMs, 0);
public override void Tick(List<GridTouch> touches)
{
// 從系統授權畫面回來:位置改變
bool access = PackStorage.HasSharedAccess();
if (access != hadAccess)
{
hadAccess = access;
Library.Rescan();
LibraryChanged();
}
if (!running) return;
double now = SongClock.Now;
int beat = (int)System.Math.Floor((now - LeadIn) / Interval) + 1;
beatText.text = beat <= 0 ? "準備…" : $"{Mathf.Min(beat, BeatCount)} / {BeatCount}";
double real = Time.realtimeSinceStartupAsDouble;
foreach (var t in Touch.activeTouches)
{
if (t.phase != UnityEngine.InputSystem.TouchPhase.Began || ignoredTouches.Contains(t.touchId)) continue;
double age = System.Math.Min(0.1, System.Math.Max(0, real - t.startTime));
if (CalibrationMath.TryBeatDelta(now - age, LeadIn, Interval, BeatCount, WarmupBeats, out double d))
deltas.Add(d);
}
if (now > LeadIn + (BeatCount - 0.5) * Interval + 0.3) Finish();
}
void StartCalibration()
{
deltas.Clear();
ignoredTouches.Clear();
// 開始前已按著的手指(按下「開始」的那一下)不計入
foreach (var t in Touch.activeTouches) ignoredTouches.Add(t.touchId);
double dspStart = AudioSettings.dspTime + 0.2;
App.Music.clip = clickTrack;
App.Music.loop = false;
App.Music.PlayScheduled(dspStart);
SongClock.Begin(dspStart, applyOffset: false);
running = true;
startButton.interactable = false;
statusText.text = "閉上眼睛,跟著聲音點擊螢幕任意處";
}
void Finish()
{
running = false;
SongClock.Stop();
App.Music.Stop();
startButton.interactable = true;
beatText.text = "";
int needed = (BeatCount - WarmupBeats) / 2;
if (deltas.Count < needed)
{
statusText.text = $"有效點擊太少({deltas.Count} 次),請再試一次";
return;
}
int ms = (int)System.Math.Round(CalibrationMath.Median(deltas) * 1000);
SetOffset(ms);
statusText.text = $"已套用:{deltas.Count} 次有效點擊,中位數 {ms:+0;-0;0} ms";
}
void SetOffset(int ms)
{
PlayerPrefs.SetInt(Prefs.AudioOffsetMs, Mathf.Clamp(ms, -500, 500));
PlayerPrefs.Save();
RefreshOffset();
}
void RefreshOffset() => offsetText.text = $"目前延遲補償:{Offset:+0;-0;0} ms";
// 整段節拍聲(每四拍第一拍較高音)
AudioClip BuildClickTrack()
{
int rate = AudioSettings.outputSampleRate;
double length = LeadIn + BeatCount * Interval + 0.5;
var data = new float[(int)(rate * length)];
int clickLen = (int)(rate * 0.04);
for (int b = 0; b < BeatCount; b++)
{
int start = (int)((LeadIn + b * Interval) * rate);
double freq = b % 4 == 0 ? 1760 : 1320;
for (int i = 0; i < clickLen && start + i < data.Length; i++)
{
double env = System.Math.Exp(-i / (rate * 0.008));
data[start + i] = (float)(System.Math.Sin(2 * System.Math.PI * freq * i / rate) * env * 0.8);
}
}
var clip = AudioClip.Create("CalibrationClicks", data.Length, 1, rate, false);
clip.SetData(data, 0);
return clip;
}
public override void Exit()
{
if (running) SongClock.Stop();
App.Music.Stop();
if (App.Music.clip == clickTrack) App.Music.clip = null;
if (clickTrack != null) Object.Destroy(clickTrack);
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 5f3c820e04a29bb48b04cf0685fdf378
+87
View File
@@ -0,0 +1,87 @@
using UnityEngine;
using UnityEngine.UI;
// 結算畫面(以程式建立,不需改動場景)
public static class ResultOverlay
{
public static GameObject Show(PlayResult r, int totalNotes, Font font, string uploadStatus)
{
var root = new GameObject("ResultOverlay", typeof(Canvas), typeof(CanvasScaler));
var canvas = root.GetComponent<Canvas>();
canvas.renderMode = RenderMode.ScreenSpaceOverlay;
canvas.sortingOrder = 100;
var scaler = root.GetComponent<CanvasScaler>();
scaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
scaler.referenceResolution = new Vector2(1080, 2400);
scaler.matchWidthOrHeight = 0f;
var bg = NewChild(root.transform, "Background").AddComponent<Image>();
bg.color = new Color(0f, 0f, 0f, 0.88f);
Stretch(bg.rectTransform);
int hit = r.perfect + r.fast + r.slow + r.bad;
float acc = totalNotes > 0
? (r.perfect + 0.75f * (r.fast + r.slow) + 0.25f * r.bad) / totalNotes * 100f
: 0f;
AddText(root.transform, font, "RESULT", 72, new Color(1f, 0.42f, 0.8f), 600);
AddText(root.transform, font, r.score.ToString(), 140, Color.white, 420);
AddText(root.transform, font, $"準確率 {acc:0.00}% 最大連擊 {r.maxCombo}", 44, new Color(0.85f, 0.85f, 0.85f), 280);
// 兩欄:判定名稱靠右、次數靠左(比例字型無法用空白對齊)
string names =
"<color=#6EB4FF>Perfect</color>\n<color=#7CD67C>Fast</color>\n<color=#FFA64D>Slow</color>\n" +
"<color=#FF5050>Bad</color>\n<color=#888888>Miss</color>";
string counts = $"{r.perfect}\n{r.fast}\n{r.slow}\n{r.bad}\n{r.miss}";
AddColumn(root.transform, font, names, TextAnchor.MiddleRight, -40);
AddColumn(root.transform, font, counts, TextAnchor.MiddleLeft, 40);
AddText(root.transform, font, uploadStatus, 36, new Color(0.6f, 0.6f, 0.6f), -330);
AddText(root.transform, font, "點擊任意處繼續", 44, new Color(0.85f, 0.85f, 0.85f), -520);
return root;
}
private static void AddColumn(Transform parent, Font font, string content, TextAnchor align, float x)
{
var text = AddText(parent, font, content, 56, Color.white, 0);
text.supportRichText = true;
text.alignment = align;
text.lineSpacing = 1.1f;
var rt = text.rectTransform;
rt.pivot = new Vector2(align == TextAnchor.MiddleRight ? 1f : 0f, 0.5f);
rt.sizeDelta = new Vector2(400, 440);
rt.anchoredPosition = new Vector2(x, 0);
}
private static GameObject NewChild(Transform parent, string name)
{
var go = new GameObject(name, typeof(RectTransform));
go.transform.SetParent(parent, false);
return go;
}
private static void Stretch(RectTransform rt)
{
rt.anchorMin = Vector2.zero;
rt.anchorMax = Vector2.one;
rt.offsetMin = rt.offsetMax = Vector2.zero;
}
private static Text AddText(Transform parent, Font font, string content, int size, Color color, float y)
{
var text = NewChild(parent, "Text").AddComponent<Text>();
text.font = font;
text.text = content;
text.fontSize = size;
text.color = color;
text.alignment = TextAnchor.MiddleCenter;
text.horizontalOverflow = HorizontalWrapMode.Overflow;
text.verticalOverflow = VerticalWrapMode.Overflow;
text.raycastTarget = false;
var rt = text.rectTransform;
rt.anchorMin = rt.anchorMax = new Vector2(0.5f, 0.5f);
rt.sizeDelta = new Vector2(1000, size * 1.5f);
rt.anchoredPosition = new Vector2(0, y);
return text;
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 31af18566e9d68a4cbebbad7400e4329
+84
View File
@@ -0,0 +1,84 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
// 畫面下方的短訊息(跨場景保留),例如「已匯入曲包」
public class Toast : MonoBehaviour
{
private static Toast instance;
private readonly Queue<string> queue = new Queue<string>();
private Text text;
private CanvasGroup group;
private Coroutine running;
public static void Show(string message)
{
Debug.Log("[Toast] " + message);
if (instance == null) instance = Create();
instance.queue.Enqueue(message);
if (instance.running == null) instance.running = instance.StartCoroutine(instance.Run());
}
private static Toast Create()
{
var root = new GameObject("Toast", typeof(Canvas), typeof(CanvasScaler), typeof(CanvasGroup));
DontDestroyOnLoad(root);
var canvas = root.GetComponent<Canvas>();
canvas.renderMode = RenderMode.ScreenSpaceOverlay;
canvas.sortingOrder = 500;
var scaler = root.GetComponent<CanvasScaler>();
scaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
scaler.referenceResolution = new Vector2(1080, 2400);
scaler.matchWidthOrHeight = 0f;
var bg = new GameObject("Background", typeof(RectTransform)).AddComponent<Image>();
bg.transform.SetParent(root.transform, false);
bg.color = new Color(0f, 0f, 0f, 0.82f);
bg.raycastTarget = false;
var rt = bg.rectTransform;
rt.anchorMin = rt.anchorMax = new Vector2(0.5f, 0f);
rt.pivot = new Vector2(0.5f, 0f);
rt.anchoredPosition = new Vector2(0, 260);
rt.sizeDelta = new Vector2(960, 150);
var t = new GameObject("Text", typeof(RectTransform)).AddComponent<Text>();
t.transform.SetParent(bg.transform, false);
t.font = Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf");
t.fontSize = 38;
t.color = Color.white;
t.alignment = TextAnchor.MiddleCenter;
t.horizontalOverflow = HorizontalWrapMode.Wrap;
t.verticalOverflow = VerticalWrapMode.Overflow;
t.raycastTarget = false;
var trt = t.rectTransform;
trt.anchorMin = Vector2.zero;
trt.anchorMax = Vector2.one;
trt.offsetMin = new Vector2(24, 8);
trt.offsetMax = new Vector2(-24, -8);
var toast = root.AddComponent<Toast>();
toast.text = t;
toast.group = root.GetComponent<CanvasGroup>();
toast.group.alpha = 0f;
return toast;
}
private IEnumerator Run()
{
while (queue.Count > 0)
{
text.text = queue.Dequeue();
group.alpha = 1f;
yield return new WaitForSecondsRealtime(3f);
for (float a = 1f; a > 0f; a -= Time.unscaledDeltaTime * 2f)
{
group.alpha = a;
yield return null;
}
group.alpha = 0f;
}
running = null;
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 0426c50443e552e4fba1e79de13e96ea
+24
View File
@@ -0,0 +1,24 @@
using UnityEngine;
using UnityEngine.UI;
// 螢幕某點是否被 UI(按鈕、輸入框、對話框)擋住
// 格子與一般圖片、文字都不是 raycastTarget,所以只要有 raycastTarget 的圖形就算擋住
public static class UIHitTest
{
public static bool IsBlocked(Vector2 screenPos)
{
foreach (var canvas in Object.FindObjectsByType<Canvas>(FindObjectsSortMode.None))
{
if (!canvas.isActiveAndEnabled) continue;
Camera cam = canvas.rootCanvas.renderMode == RenderMode.ScreenSpaceOverlay ? null : canvas.rootCanvas.worldCamera;
var graphics = GraphicRegistry.GetRaycastableGraphicsForCanvas(canvas);
for (int i = 0; i < graphics.Count; i++)
{
Graphic g = graphics[i];
if (!g.isActiveAndEnabled || g.depth < 0 || g.canvasRenderer.cull) continue;
if (RectTransformUtility.RectangleContainsScreenPoint(g.rectTransform, screenPos, cam)) return true;
}
}
return false;
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 3b514edd2240c764db075f214a207d42
+299
View File
@@ -0,0 +1,299 @@
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
// 以程式建立 UI 的小工具(遊戲沒有預先擺好的場景與 prefab)
// 單位:畫布寬固定 1080
public static class Ui
{
public static readonly Color Bg = Color.black;
public static readonly Color Panel = new Color(0.09f, 0.09f, 0.11f);
public static readonly Color ButtonFill = new Color(0.16f, 0.16f, 0.19f);
public static readonly Color Line = new Color(0.33f, 0.33f, 0.36f);
public static readonly Color TextColor = new Color(0.93f, 0.93f, 0.95f);
public static readonly Color Muted = new Color(0.6f, 0.6f, 0.64f);
public static readonly Color Accent = new Color(1f, 0.4f, 0.77f);
public static readonly Color Blue = new Color(0.25f, 0.64f, 1f);
public static readonly Color Danger = new Color(1f, 0.38f, 0.38f);
// 難度顏色:[0] 未用、easy、normal、hard
public static readonly Color[] LevelColors =
{
Color.white, new Color(0.49f, 0.84f, 0.49f), new Color(1f, 0.31f, 0.31f), new Color(0.71f, 0.39f, 1f),
};
private static Font font;
public static Font Font => font != null ? font : (font = Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf"));
private static Sprite rounded;
// 圓角矩形(9-slice),按鈕、輸入框、對話框共用
public static Sprite Rounded
{
get
{
if (rounded != null) return rounded;
const int size = 64, r = 20;
var tex = new Texture2D(size, size, TextureFormat.RGBA32, false) { wrapMode = TextureWrapMode.Clamp };
var px = new Color32[size * size];
for (int y = 0; y < size; y++)
for (int x = 0; x < size; x++)
{
float dx = Mathf.Max(0, Mathf.Max(r - x - 0.5f, x + 0.5f - (size - r)));
float dy = Mathf.Max(0, Mathf.Max(r - y - 0.5f, y + 0.5f - (size - r)));
float a = Mathf.Clamp01(r - Mathf.Sqrt(dx * dx + dy * dy) + 0.5f);
px[y * size + x] = new Color32(255, 255, 255, (byte)(a * 255));
}
tex.SetPixels32(px);
tex.Apply(false, true);
rounded = Sprite.Create(tex, new Rect(0, 0, size, size), new Vector2(0.5f, 0.5f), 100, 0,
SpriteMeshType.FullRect, new Vector4(r, r, r, r));
return rounded;
}
}
// ---------- 基本元件 ----------
public static RectTransform Rect(Transform parent, string name = "Rect")
{
var go = new GameObject(name, typeof(RectTransform));
go.transform.SetParent(parent, false);
return (RectTransform)go.transform;
}
public static RectTransform Stretch(RectTransform rt, float left = 0, float bottom = 0, float right = 0, float top = 0)
{
rt.anchorMin = Vector2.zero;
rt.anchorMax = Vector2.one;
rt.offsetMin = new Vector2(left, bottom);
rt.offsetMax = new Vector2(-right, -top);
return rt;
}
// 以錨點(0~1)放置:pivot 與錨點相同,pos 為偏移
public static RectTransform Place(RectTransform rt, Vector2 anchor, Vector2 pos, Vector2 size)
{
rt.anchorMin = rt.anchorMax = rt.pivot = anchor;
rt.anchoredPosition = pos;
rt.sizeDelta = size;
return rt;
}
public static Text Label(Transform parent, string text, int size, Color color, TextAnchor align = TextAnchor.MiddleCenter)
{
var t = Rect(parent, "Text").gameObject.AddComponent<Text>();
t.font = Font;
t.text = text;
t.fontSize = size;
t.color = color;
t.alignment = align;
t.horizontalOverflow = HorizontalWrapMode.Wrap;
t.verticalOverflow = VerticalWrapMode.Overflow;
t.raycastTarget = false;
t.supportRichText = true;
return t;
}
public static Image Image(Transform parent, Sprite sprite, Color color)
{
var img = Rect(parent, "Image").gameObject.AddComponent<Image>();
img.sprite = sprite;
img.color = color;
img.raycastTarget = false;
if (sprite == Rounded) img.type = UnityEngine.UI.Image.Type.Sliced;
return img;
}
public static Button Button(Transform parent, string label, UnityAction onClick, int fontSize = 44, bool primary = false)
{
var img = Image(parent, Rounded, primary ? new Color(0.45f, 0.17f, 0.34f) : ButtonFill);
img.raycastTarget = true;
img.name = "Button";
var btn = img.gameObject.AddComponent<Button>();
var colors = btn.colors;
colors.highlightedColor = Color.white;
colors.pressedColor = new Color(0.7f, 0.7f, 0.7f);
colors.disabledColor = new Color(0.5f, 0.5f, 0.5f, 0.6f);
btn.colors = colors;
if (onClick != null) btn.onClick.AddListener(onClick);
var outline = Image(img.transform, Rounded, primary ? Accent : Line);
outline.fillCenter = false;
Stretch(outline.rectTransform);
var t = Label(img.transform, label, fontSize, TextColor);
Stretch(t.rectTransform, 16, 4, 16, 4);
return btn;
}
public static void SetButtonText(Button b, string text) => b.GetComponentInChildren<Text>().text = text;
public static InputField Input(Transform parent, string placeholder, InputField.ContentType type = InputField.ContentType.Standard, int fontSize = 42)
{
var bg = Image(parent, Rounded, new Color(0.05f, 0.05f, 0.06f));
bg.raycastTarget = true;
bg.name = "Input";
var outline = Image(bg.transform, Rounded, Line);
outline.fillCenter = false;
Stretch(outline.rectTransform);
var text = Label(bg.transform, "", fontSize, TextColor, TextAnchor.MiddleLeft);
text.supportRichText = false;
text.horizontalOverflow = HorizontalWrapMode.Overflow;
Stretch(text.rectTransform, 28, 4, 28, 4);
var ph = Label(bg.transform, placeholder, fontSize, new Color(0.45f, 0.45f, 0.5f), TextAnchor.MiddleLeft);
Stretch(ph.rectTransform, 28, 4, 28, 4);
var field = bg.gameObject.AddComponent<InputField>();
field.textComponent = text;
field.placeholder = ph;
field.contentType = type;
field.lineType = InputField.LineType.SingleLine;
field.caretColor = Accent;
field.selectionColor = new Color(1f, 0.4f, 0.77f, 0.35f);
field.caretWidth = 3;
return field;
}
// 垂直排列容器(表單、清單用):子物件以 LayoutElement 指定高度
public static RectTransform Column(Transform parent, float spacing = 24, int padding = 0, TextAnchor align = TextAnchor.UpperCenter)
{
var rt = Rect(parent, "Column");
var v = rt.gameObject.AddComponent<VerticalLayoutGroup>();
v.spacing = spacing;
v.padding = new RectOffset(padding, padding, padding, padding);
v.childAlignment = align;
v.childControlWidth = v.childControlHeight = true;
v.childForceExpandWidth = true;
v.childForceExpandHeight = false;
return rt;
}
public static RectTransform Row(Transform parent, float spacing = 24)
{
var rt = Rect(parent, "Row");
var h = rt.gameObject.AddComponent<HorizontalLayoutGroup>();
h.spacing = spacing;
h.childAlignment = TextAnchor.MiddleCenter;
h.childControlWidth = h.childControlHeight = true;
h.childForceExpandWidth = true;
h.childForceExpandHeight = true;
return rt;
}
public static T Height<T>(T c, float height) where T : Component
{
var le = c.GetComponent<LayoutElement>() ?? c.gameObject.AddComponent<LayoutElement>();
le.minHeight = le.preferredHeight = height;
return c;
}
// 可捲動的內容區(放在 parent 內填滿);回傳要放內容的 Column
public static RectTransform Scroll(Transform parent, float spacing = 24, int padding = 24)
{
var view = Image(parent, null, new Color(0, 0, 0, 0));
view.raycastTarget = true; // 讓拖曳可以捲動
view.name = "Scroll";
Stretch(view.rectTransform);
view.gameObject.AddComponent<RectMask2D>();
var scroll = view.gameObject.AddComponent<ScrollRect>();
scroll.horizontal = false;
scroll.movementType = ScrollRect.MovementType.Clamped;
scroll.scrollSensitivity = 40;
var content = Column(view.transform, spacing, padding);
content.anchorMin = new Vector2(0, 1);
content.anchorMax = new Vector2(1, 1);
content.pivot = new Vector2(0.5f, 1);
content.offsetMin = content.offsetMax = Vector2.zero;
content.gameObject.AddComponent<ContentSizeFitter>().verticalFit = ContentSizeFitter.FitMode.PreferredSize;
scroll.viewport = view.rectTransform;
scroll.content = content;
return content;
}
}
// 對話框:半透明遮罩 + 置中面板(標題、內文、自訂內容、按鈕列)
// 開著時格子不接受觸控;返回鍵關閉最上層(cancellable 時)
public class Dialog
{
private static readonly List<Dialog> open = new List<Dialog>();
public static bool AnyOpen => open.Count > 0;
public readonly RectTransform root;
public readonly RectTransform body; // 面板內的 Column,可加入自訂內容
public readonly Text message;
public bool cancellable = true;
public event Action Closed;
private RectTransform buttons;
public Dialog(Transform layer, string title, string text = null)
{
var dim = Ui.Image(layer, null, new Color(0, 0, 0, 0.75f));
dim.raycastTarget = true;
dim.name = "Dialog";
root = Ui.Stretch(dim.rectTransform);
var panel = Ui.Image(root, Ui.Rounded, Ui.Panel);
panel.raycastTarget = true;
var prt = panel.rectTransform;
prt.anchorMin = prt.anchorMax = prt.pivot = new Vector2(0.5f, 0.5f);
prt.sizeDelta = new Vector2(940, 0);
var outline = Ui.Image(prt, Ui.Rounded, Ui.Line);
outline.fillCenter = false;
Ui.Stretch(outline.rectTransform);
outline.gameObject.AddComponent<LayoutElement>().ignoreLayout = true;
body = Ui.Column(prt, 28, 48);
var fitter = panel.gameObject.AddComponent<ContentSizeFitter>();
fitter.verticalFit = ContentSizeFitter.FitMode.PreferredSize;
// 面板高度跟著內容:讓 Column 的偏好高度傳到面板
var v = panel.gameObject.AddComponent<VerticalLayoutGroup>();
v.childControlHeight = v.childControlWidth = true;
v.childForceExpandHeight = false;
if (!string.IsNullOrEmpty(title))
Ui.Label(body, title, 56, Ui.TextColor).fontStyle = FontStyle.Bold;
message = Ui.Label(body, text ?? "", 40, Ui.Muted);
message.gameObject.SetActive(!string.IsNullOrEmpty(text));
open.Add(this);
}
public Button AddButton(string label, Action onClick, bool primary = false)
{
if (buttons == null)
{
buttons = Ui.Row(body, 24);
Ui.Height(buttons, 120);
}
var b = Ui.Button(buttons, label, () => onClick?.Invoke(), 44, primary);
return b;
}
// 按鈕:關閉對話框後執行
public Button AddClose(string label, Action then = null, bool primary = false)
=> AddButton(label, () => { Close(); then?.Invoke(); }, primary);
public bool IsOpen => root != null;
public void Close()
{
if (root == null) return;
open.Remove(this);
UnityEngine.Object.Destroy(root.gameObject);
Closed?.Invoke();
}
// 返回鍵:關閉最上層可取消的對話框;有關閉任何對話框時回傳 true
public static bool HandleBack()
{
if (open.Count == 0) return false;
var top = open[open.Count - 1];
if (top.cancellable) top.Close();
return true;
}
public static void CloseAll()
{
for (int i = open.Count - 1; i >= 0; i--) open[i].Close();
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 47e9856f5baa7894fa4a8a1039940881