Initial import of Rhyculator

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
SahikandClaude Opus 5.5 committed 2026-10-24 11:55:22 +08:00
commit 728bb0c657
315 files changed
+96030

No files matched your search

+388
View File
@@ -0,0 +1,388 @@
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
// 選歌:左右切換已匯入的曲包、選難度、看個人最高分 / 排行榜、開始
// 格子配置:(0,5) 分數 (1..3,5) 難度 (4,5) 排行 | (2,3) 目前難度 | (1,2) 上一首 (2,2) 開始 (3,2) 下一首
public class UIManager_Choose : MonoBehaviour
{
public GameObject ScorePanel;
public GameObject RankPanel;
public Text ScoreText;
public Text RankText;
public GridSpawner gridSpawner;
public GridDisplaySpawner gridDisplaySpawner;
public string PlayingSceneName = "PlayingScene";
public TouchManager_Choose touchManager;
public Sprite imgStart;
public Sprite imgArrowRight;
public Sprite imgArrrowLeft;
public Sprite imgScore;
public Sprite imgRank;
[Header("曲目顯示")]
public Image coverImage;
public Text nameLabel;
public AudioSource previewSource;
private static readonly Color[] LevelColors =
{
Color.white,
new Color(0.49f, 0.84f, 0.49f), // easy
new Color(1f, 0.31f, 0.31f), // normal
new Color(0.71f, 0.39f, 1f), // hard
};
private IReadOnlyList<SongInfo> songs;
private int index;
private int level;
private readonly Dictionary<string, Sprite> covers = new Dictionary<string, Sprite>();
private int previewGeneration;
private AudioClip previewClip;
private float previewStart, previewEnd;
private Text emptyHint;
private SongInfo Song => songs.Count > 0 ? songs[index] : null;
void Start()
{
touchManager.OnTap += HandleTap;
songs = SongLibrary.Songs;
var current = SongLibrary.Current;
index = 0;
for (int i = 0; i < songs.Count; i++)
if (songs[i] == current) index = i;
level = PlayerPrefs.GetInt("NowPlayingLevel", 1);
ShowSong();
}
void OnDestroy()
{
previewGeneration++;
if (previewSource != null) previewSource.Stop();
if (previewClip != null) Destroy(previewClip);
foreach (var s in covers.Values)
{
if (s == null) continue;
Destroy(s.texture);
Destroy(s);
}
}
void Update()
{
// 試聽片段循環
if (previewSource != null && previewSource.isPlaying && previewEnd > previewStart && previewSource.time >= previewEnd)
previewSource.time = previewStart;
}
// 面板開著時,格子不接受操作(避免穿透誤觸)
bool IsPanelOpen => ScorePanel.activeSelf || RankPanel.activeSelf;
void ShowSong()
{
var song = Song;
bool many = songs.Count > 1;
gridDisplaySpawner.SetImage(1, 2, many ? imgArrrowLeft : null);
gridDisplaySpawner.SetImage(3, 2, many ? imgArrowRight : null);
if (song == null)
{
ShowEmpty();
return;
}
SongLibrary.Current = song;
if (!song.HasLevel(level)) level = song.FirstLevel();
PlayerPrefs.SetInt("NowPlayingLevel", level);
if (emptyHint != null) emptyHint.gameObject.SetActive(false);
nameLabel.text = string.IsNullOrEmpty(song.artist) ? song.name : $"{song.name} / {song.artist}";
coverImage.sprite = LoadCover(song);
coverImage.preserveAspect = true;
coverImage.enabled = coverImage.sprite != null;
gridDisplaySpawner.SetImage(0, 5, imgScore);
gridDisplaySpawner.SetImage(4, 5, imgRank);
gridDisplaySpawner.SetImage(2, 2, imgStart);
for (int l = 1; l <= SongInfo.LevelCount; l++)
gridDisplaySpawner.SetLabel(l, 5, song.HasLevel(l) ? LevelText(song, l) : null, LevelColors[l]);
gridDisplaySpawner.SetLabel(2, 3, LevelText(song, level), LevelColors[level]);
StartCoroutine(PlayPreview(song));
}
static string LevelText(SongInfo song, int l) => song.levelNum[l] > 0 ? song.levelNum[l].ToString() : "?";
// 沒有任何曲包:顯示匯入方式
void ShowEmpty()
{
nameLabel.text = "";
coverImage.enabled = false;
for (int x = 0; x < 5; x++)
for (int y = 0; y < 6; y++)
gridDisplaySpawner.Clear(x, y);
if (emptyHint == null) emptyHint = CreateHint();
emptyHint.gameObject.SetActive(true);
emptyHint.text = "尚未匯入任何曲包\n\n用檔案管理員或瀏覽器開啟曲包 .zip,\n選擇以「Rhyculator」開啟即可匯入\n\n或把 .zip 放到:\n" + Application.persistentDataPath;
}
Text CreateHint()
{
var go = new GameObject("EmptyHint", typeof(RectTransform));
go.transform.SetParent(coverImage.transform.parent, false);
var t = go.AddComponent<Text>();
t.font = nameLabel.font;
t.fontSize = 40;
t.color = new Color(0.8f, 0.8f, 0.8f);
t.alignment = TextAnchor.MiddleCenter;
t.horizontalOverflow = HorizontalWrapMode.Wrap;
t.verticalOverflow = VerticalWrapMode.Overflow;
t.raycastTarget = false;
var rt = t.rectTransform;
var cover = coverImage.rectTransform;
rt.anchorMin = cover.anchorMin;
rt.anchorMax = cover.anchorMax;
rt.pivot = cover.pivot;
rt.anchoredPosition = cover.anchoredPosition;
rt.sizeDelta = new Vector2(960, cover.sizeDelta.y);
return t;
}
Sprite LoadCover(SongInfo song)
{
if (covers.TryGetValue(song.id, out var cached)) return cached;
Sprite sprite = null;
try
{
if (File.Exists(song.ImagePath))
{
var tex = new Texture2D(2, 2, TextureFormat.RGBA32, false);
if (tex.LoadImage(File.ReadAllBytes(song.ImagePath)))
sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f), 100f);
else
Destroy(tex);
}
}
catch (System.Exception e)
{
Debug.LogWarning($"[Choose] 封面讀取失敗 {song.id}:{e.Message}");
}
covers[song.id] = sprite;
return sprite;
}
IEnumerator PlayPreview(SongInfo song)
{
int generation = ++previewGeneration;
if (previewSource == null) yield break;
previewSource.Stop();
string path = song.MusicPath;
if (path == null) yield break;
AudioClip clip;
using (var www = MusicPlayer.LoadAudio(path))
{
yield return www.SendWebRequest();
if (generation != previewGeneration) yield break; // 已經切到別首
if (www.result != UnityWebRequest.Result.Success)
{
Debug.LogWarning("[Choose] 試聽載入失敗:" + www.error);
yield break;
}
clip = DownloadHandlerAudioClip.GetContent(www);
}
if (clip == null) yield break;
if (previewClip != null) Destroy(previewClip);
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;
previewSource.clip = clip;
previewSource.loop = true;
previewSource.time = previewStart;
previewSource.Play();
}
void HandleTap(int x, int y)
{
if (IsPanelOpen) return;
var song = Song;
if (song == null) return;
if (y == 2 && x == 1 && songs.Count > 1)
{
index = (index + songs.Count - 1) % songs.Count;
ShowSong();
}
else if (y == 2 && x == 3 && songs.Count > 1)
{
index = (index + 1) % songs.Count;
ShowSong();
}
else if (y == 5 && x >= 1 && x <= SongInfo.LevelCount)
{
if (!song.HasLevel(x)) return;
level = x;
PlayerPrefs.SetInt("NowPlayingLevel", level);
gridDisplaySpawner.SetLabel(2, 3, LevelText(song, level), LevelColors[level]);
}
else if (y == 5 && x == 0)
{
StartCoroutine(RequestScoreAndShowPanel(song));
}
else if (y == 5 && x == 4)
{
StartCoroutine(RequestRankAndShowPanel(song));
}
else if (y == 2 && x == 2)
{
if (previewSource != null) previewSource.Stop();
SceneManager.LoadScene(PlayingSceneName);
}
}
IEnumerator RequestScoreAndShowPanel(SongInfo song)
{
string jsonData = JsonUtility.ToJson(new ScoreRequest
{
request = "score",
uid = PlayerPrefs.GetInt("UID", 0),
song = song.id,
level = level
});
using (UnityWebRequest www = new UnityWebRequest(ServerConfig.GameServerUrl, "POST"))
{
byte[] bodyRaw = System.Text.Encoding.UTF8.GetBytes(jsonData);
www.uploadHandler = new UploadHandlerRaw(bodyRaw);
www.downloadHandler = new DownloadHandlerBuffer();
www.SetRequestHeader("Content-Type", "application/json");
yield return www.SendWebRequest();
if (www.result != UnityWebRequest.Result.Success)
{
Debug.LogError("Error requesting score: " + www.error);
ScoreText.text = "Error";
}
else
{
ScoreResponse response = JsonUtility.FromJson<ScoreResponse>(www.downloadHandler.text);
ScoreText.text = response.status == "success" ? response.score.ToString() : "0";
}
}
ScorePanel.SetActive(true);
}
IEnumerator RequestRankAndShowPanel(SongInfo song)
{
string jsonData = JsonUtility.ToJson(new RankRequest
{
request = "rank",
song = song.id,
level = level
});
using (UnityWebRequest www = new UnityWebRequest(ServerConfig.GameServerUrl, "POST"))
{
byte[] bodyRaw = System.Text.Encoding.UTF8.GetBytes(jsonData);
www.uploadHandler = new UploadHandlerRaw(bodyRaw);
www.downloadHandler = new DownloadHandlerBuffer();
www.SetRequestHeader("Content-Type", "application/json");
yield return www.SendWebRequest();
if (www.result != UnityWebRequest.Result.Success)
{
Debug.LogError("Error requesting rank: " + www.error);
RankText.text = "Error";
}
else
{
RankResponse response = JsonUtility.FromJson<RankResponse>(www.downloadHandler.text);
if (response.status == "success")
{
string[] names = { response.name_1, response.name_2, response.name_3, response.name_4, response.name_5 };
int[] scores = { response.score_1, response.score_2, response.score_3, response.score_4, response.score_5 };
// 伺服器以 null 表示該名次無人,只顯示有名字的名次
string rankStr = "";
for (int i = 0; i < 5; i++)
{
if (string.IsNullOrEmpty(names[i])) break;
rankStr += $"{i + 1}. {names[i]} - {scores[i]}\n";
}
if (rankStr == "") rankStr = "尚無紀錄";
RankText.text = rankStr;
}
else
{
RankText.text = "No data";
}
}
}
RankPanel.SetActive(true);
}
[System.Serializable]
public class ScoreRequest
{
public string request;
public int uid;
public string song;
public int level;
}
[System.Serializable]
public class ScoreResponse
{
public int score;
public string status;
}
[System.Serializable]
public class RankRequest
{
public string request;
public string song;
public int level;
}
[System.Serializable]
public class RankResponse
{
public string name_1;
public string name_2;
public string name_3;
public string name_4;
public string name_5;
public int score_1;
public int score_2;
public int score_3;
public int score_4;
public int score_5;
public string status;
}
public void QuitScorePanel()
{
ScorePanel.SetActive(false);
}
public void QuitRankPanel()
{
RankPanel.SetActive(false);
}
}