Files
2026-10-22 21:07:47 +08:00

163 lines
5.9 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""譜面資料模型:三軌(L/M/R)中間檔 *.lanes.json 與遊戲譜面匯出"""
from __future__ import annotations
import copy
import json
from dataclasses import dataclass, field, asdict
from typing import Optional
NOTE_TYPES = ("tap", "hold", "slide")
@dataclass(eq=False) # 以物件身分比較:選取、刪除都針對「這一顆」
class Note:
t: int # 判定時間(ms)
lane: str # "L" / "M" / "R"
type: str = "tap" # tap / hold / slide
end: Optional[int] = None # hold / slide 結束時間(ms)
pos: Optional[tuple] = None # tap / hold 的格子 (x, y)
path: Optional[list] = None # slide 路徑 [(x, y), ...]
locked: bool = False # 手動指定過座標,自動配置時保留
@property
def end_time(self):
return self.end if self.end is not None else self.t
def placed(self):
return bool(self.path) if self.type == "slide" else self.pos is not None
def to_json(self):
d = {"t": self.t, "lane": self.lane, "type": self.type}
if self.end is not None:
d["end"] = self.end
if self.pos is not None:
d["pos"] = {"x": self.pos[0], "y": self.pos[1]}
if self.path:
d["path"] = [{"x": x, "y": y} for x, y in self.path]
if self.locked:
d["locked"] = True
return d
@staticmethod
def from_json(d):
pos = (d["pos"]["x"], d["pos"]["y"]) if "pos" in d else None
path = [(p["x"], p["y"]) for p in d["path"]] if "path" in d else None
return Note(int(d["t"]), d["lane"], d.get("type", "tap"), d.get("end"), pos, path, d.get("locked", False))
@dataclass
class Chart:
audio: str = ""
bpm: float = 120.0
offset: int = 0 # 第一拍的時間(ms)
divisor: int = 4 # 吸附細分:1/divisor 拍
notes: list = field(default_factory=list)
# ---------- 節拍格線 ----------
@property
def beat_ms(self):
return 60000.0 / self.bpm
def snap(self, t, divisor=None):
step = self.beat_ms / (divisor or self.divisor)
return int(round(self.offset + round((t - self.offset) / step) * step))
def grid_lines(self, t0, t1, divisor=None):
"""回傳 [(time, is_beat, is_bar)]"""
div = divisor or self.divisor
step = self.beat_ms / div
k = int((t0 - self.offset) // step)
out = []
while True:
t = self.offset + k * step
if t > t1:
break
if t >= t0:
out.append((t, k % div == 0, k % (div * 4) == 0))
k += 1
return out
# ---------- 音符 ----------
def sort(self):
self.notes.sort(key=lambda n: (n.t, "LMR".index(n.lane)))
def add(self, note):
self.notes.append(note)
self.sort()
return note
def note_at(self, lane, t, tolerance):
best = None
for n in self.notes:
if n.lane != lane:
continue
if n.t - tolerance <= t <= n.end_time + tolerance:
if best is None or abs(n.t - t) < abs(best.t - t):
best = n
return best
def snapshot(self):
return copy.deepcopy(self.notes)
# ---------- 曲包內的譜面(統一格式;bpm 等曲目資訊在 config.json)----------
CHART_FORMAT = 1
def chart_json(self):
return {"format": self.CHART_FORMAT, "divisor": self.divisor,
"notes": [n.to_json() for n in self.notes]}
@staticmethod
def from_chart_json(d, bpm, beat_offset, audio=""):
c = Chart(audio, float(bpm), int(beat_offset), int(d.get("divisor", 4)),
[Note.from_json(n) for n in d.get("notes", [])])
c.sort()
return c
# ---------- 舊版 *.lanes.json ----------
def to_json(self):
return {"audio": self.audio, "bpm": self.bpm, "offset": self.offset, "divisor": self.divisor,
"notes": [n.to_json() for n in self.notes]}
def save(self, path):
with open(path, "w", encoding="utf-8", newline="\n") as f:
json.dump(self.to_json(), f, ensure_ascii=False, indent=1)
@staticmethod
def load(path):
d = json.load(open(path, encoding="utf-8"))
c = Chart(d.get("audio", ""), float(d.get("bpm", 120)), int(d.get("offset", 0)), int(d.get("divisor", 4)),
[Note.from_json(n) for n in d.get("notes", [])])
c.sort()
return c
# ---------- 匯出遊戲譜面 ----------
def export_sheet(self):
"""轉成遊戲 MusicPlayer 讀取的格式;未配置座標的音符會被略過"""
out = []
for n in self.notes:
if not n.placed():
continue
if n.type == "slide":
# 遊戲把路徑格子平均分配在 [startTime, endTime):第 i 格在 start + i * (end-start)/len
# 這裡讓最後一格剛好落在 n.end
k = len(n.path)
end = n.end if k == 1 else int(round(n.t + (n.end - n.t) * k / (k - 1)))
out.append({"type": "slide", "startTime": n.t, "endTime": end,
"path": [{"x": x, "y": y} for x, y in n.path]})
elif n.type == "hold":
out.append({"type": "hold", "startTime": n.t, "endTime": n.end,
"pos": {"x": n.pos[0], "y": n.pos[1]}})
else:
out.append({"type": "tap", "startTime": n.t, "pos": {"x": n.pos[0], "y": n.pos[1]}})
return out
def export_sheet_file(self, path):
with open(path, "w", encoding="utf-8", newline="\n") as f:
json.dump(self.export_sheet(), f, ensure_ascii=False, indent=2)
def slide_steps(chart, note):
"""slide 路徑的格子數:每 1/divisor 拍一格,至少 2 格"""
step = chart.beat_ms / chart.divisor
return max(2, int(round((note.end_time - note.t) / step)) + 1)