This commit is contained in:
Sahik committed 2026-10-22 21:07:47 +08:00
commit 62e284866b
22 files changed
+3080

No files matched your search

+6
View File
@@ -0,0 +1,6 @@
.venv/
__pycache__/
.pytest_cache/
*.pyc
*.zip
!examples/*.zip
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 sthkm3
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+208
View File
@@ -0,0 +1,208 @@
# Rhyculator Maker
小遊戲 [Rhyculator](https://github.com/Sthkm3/Rhyculator) 的簡易譜面製作器。 | A simple chart editor for game [Rhyculator](https://github.com/Sthkm3/Rhyculator).
## 製譜流程
該遊戲非傳統下落式音遊,直接使用遊玩的顯示方式製譜不夠直覺,且該遊戲預設為兩指遊玩設計,本製作器會採用兩階段製譜。
- **第一階段**:將遊戲的 5x6 格子拆分成左手專用的 2x6、左右手皆可使用的 1x6 以及右手專用的 2x6,渲染成三條下落式軌道,用來設計敲擊手感。
![譜面第一階段](docs/chart.png)
- **第二階段**:把三條軌道上的音符個別配置到 5x6 格子上,最後輸出成曲包(`.zip`)。
![譜面第二階段](docs/position.png)
## 額外功能
- **手動微調**:點音符、點格子即可改位置,改過的音符會鎖定,重新自動配置時保留
- **與遊戲一致的預覽**:5x6 預覽的出現時間、縮放動畫與遊戲相同
- **精確播放**:以音訊取樣計算播放位置並扣除輸出延遲;可 0.5x/0.75x 慢速播放、開關打擊音效
- **錄製模式**:邊聽邊按 F/空白/J 打點,停止時自動吸附到格線
- **檢查**:未配置、區域違規、同格重疊、同一隻手同時要按兩個,都會即時標紅
- **匯入 osu! 當參考**:taiko 與 mania 4K 譜面可匯入當作參考
## 安裝
需要 Python 3.10 以上。
```
git clone https://github.com/sthkm3/RhyculatorMaker.git
cd RhyculatorMaker
python -m venv .venv
.venv\Scripts\pip install -r requirements.txt
```
macOS/Linux 把 `.venv\Scripts\` 換成 `.venv/bin/`。
## 快速開始
開啟示範曲包 FREEDOM DiVE (tpz Overcute Remix)(也可以把 `examples/FREEDOM DiVE (tpz Overcute Remix).zip` 拖進啟動視窗):
```
.venv\Scripts\python maker.py "examples\FREEDOM DiVE (tpz Overcute Remix).zip"
```
> 示範曲包內的音樂〈FREEDOM DiVE (tpz Overcute Remix)〉原曲為 xi 的〈FREEDOM DiVE↓〉,Remix 為 tpz,版權屬於原作者,僅供示範用途,不在本專案的 MIT 授權範圍內。
不帶參數啟動時會先出現啟動視窗(Windows 也可以直接執行 `run.bat`):
```
.venv\Scripts\python maker.py
```
- **開啟曲包**:把 `.zip` 拖進視窗(或按「選擇檔案…」),按「確定」。曲包會解壓到暫存區編輯,
每次 `Ctrl+S` 都直接重新打包並覆蓋原本的 zip
- **建立新曲包**:路徑留空按「確定」,填好存放位置、ID、曲名、曲師、BPM、音訊或影片、封面,
並勾選要有的難度與難度數字,按「建立」後會立刻存出一個空曲包並進入編輯器
## 操作說明
### 1. 譜面分頁:決定節奏與分手
| 操作 | 說明 |
|---|---|
| 左鍵點軌道 | 放 tap |
| 拖曳 | 放 hold |
| `Shift` + 拖曳 | 放 slide |
| 右鍵 | 刪除 |
| `↑` `↓` | 選取的音符移動一格線 |
| `1` `2` `3` | 選取的音符改到 L/M/R 軌 |
| `R` | 錄製模式:播放中按 `F`(左)`空白`(中)`J`(右) |
| `[` `]` | 格線細分(1/1 ~ 1/16 拍) |
| `B`/`O` | 設定 BPM/第一拍時間 |
### 2. 座標分頁:配置到 5x6
| 操作 | 說明 |
|---|---|
| `A` | 自動配置所有未鎖定的音符 |
| `Shift` + `A` | 只配置還沒有座標的音符 |
| 點音符 → 點格子 | 指定座標並鎖定(只能點該手可用的區域) |
| slide:點格子/`Shift` + 點格子 | 重畫路徑/延伸路徑 |
| `U` | 解除鎖定 |
各軌可用的欄位(x = 0 在最左,y = 0 在最下):
| 軌 | tap/hold | slide 路徑 |
|---|---|---|
| L(左手) | x = 0, 1 | x = 0, 1, 2 |
| R(右手) | x = 3, 4 | x = 2, 3, 4 |
| M(中間,任一隻手) | x = 2 | x = 2 |
### 共用操作
| 操作 | 說明 |
|---|---|
| `空白` | 播放/暫停(錄製模式時改用 `Enter`) |
| 滾輪/`Ctrl` + 滾輪 | 捲動/縮放時間軸 |
| `F1` `F2` `F3` | 播放速度 0.5x/0.75x/1x |
| `K` | 打擊音效開關 |
| 左上下拉選單 | 切換難度 |
| 右上「難度」勾選 | 決定曲包有哪些難度(例如只要 normal、hard);點 `Lv` 修改難度數字 |
| `I` | 編輯曲包資訊 |
| `Tab` | 切換分頁 |
| `Ctrl+O` | 回到啟動視窗(開啟其他曲包/建立新曲包) |
| `Ctrl+S`/`Ctrl+Shift+S` | 存檔/另存 |
| `Ctrl+I` | 匯入 osu! 譜面到目前難度 |
| `Ctrl+Z` | 復原 |
| `H` | 顯示/隱藏說明 |
## 曲包格式
```
<id>.zip
├─ config.json 必要
├─ easy.json / normal.json / hard.json 至少一個(檔案存在 = 有這個難度,可以是空譜面)
├─ music.wav | .ogg | .mp3 / video.mp4 音訊與影片至少一個(只有影片時,Maker 會自動抽出 music.wav)
└─ image.png 必要,正方形(匯入時自動置中裁切為 512x512)
```
### config.json
```json
{
"format": 1,
"id": "my-song",
"name": "曲名",
"artist": "曲師",
"charter": "譜師",
"bpm": 174.0,
"beat_offset": 1216,
"offset": 0,
"preview_start": 60000,
"preview_length": 15000,
"easy_num": 4,
"normal_num": 9,
"hard_num": 15
}
```
| 欄位 | 說明 |
|---|---|
| `id` | 曲包唯一 ID,小寫英數字與 `-` |
| `name`/`artist`/`charter` | 曲名/曲師/譜師 |
| `bpm`/`beat_offset` | Maker 格線用:BPM 與第一拍時間(ms) |
| `offset` | 遊戲判定時間微調(ms) |
| `preview_start`/`preview_length` | 選歌試聽片段(ms) |
| `easy_num`/`normal_num`/`hard_num` | 難度數字;有該難度譜面時必填 |
### 譜面(easy.json 等)
```json
{
"format": 1,
"divisor": 4,
"notes": [
{"t": 1216, "lane": "L", "type": "tap", "pos": {"x": 0, "y": 3}},
{"t": 2000, "lane": "R", "type": "hold", "end": 2500, "pos": {"x": 3, "y": 1}, "locked": true},
{"t": 3000, "lane": "L", "type": "slide", "end": 3500,
"path": [{"x": 0, "y": 0}, {"x": 1, "y": 1}, {"x": 2, "y": 2}]}
]
}
```
- `t`/`end`:判定時間與結束時間(ms)
- `lane`:L/M/R,`locked`:手動指定過座標
- slide 的路徑格子平均分布在 `t` ~ `end`,第一格在 `t`、最後一格在 `end`
遊戲讀取時忽略 `lane` 與 `locked`。
## 檢查譜面
```
.venv\Scripts\python validate.py my-song.zip
```
會檢查曲包本身與每個難度的譜面;有問題時列出並以非 0 結束碼結束(可用在 CI)。
Maker 存檔前也會檢查曲包:必要檔案、config 欄位、`id` 格式、封面是否為正方形;有問題時不會存檔,並在狀態列列出原因。
## 開發
```
.venv\Scripts\python -m pytest tests
```
| 檔案 | 內容 |
|---|---|
| `maker.py` | 主程式(pygame) |
| `chart.py` | 譜面資料模型、格線吸附、匯出 |
| `pack.py` | 曲包讀寫與驗證、封面裁切、影片抽音軌 |
| `placer.py` | 依手分區的自動配置 |
| `validate.py` | 譜面檢查 |
| `zones.py` | 手的區域規則與遊戲共用常數 |
| `audio.py` | 播放、變速、打擊音效、波形 |
| `importers.py`/`osu_parse.py` | osu! 匯入 |
| `examples/make_demo_pack.py` | 產生示範曲包 |
`maker.py --screenshot out.png` 可在不開視窗的情況下輸出畫面(測試用)。
## 關於 Rhyculator
Rhyculator 是一款以雙指為主的 Android 節奏遊戲,在 5x6 的格子上按下出現的音符,有 tap、hold、slide 三種音符。
## 授權
[MIT](LICENSE)
+123
View File
@@ -0,0 +1,123 @@
"""音訊播放:以送出的取樣數計算播放位置(比 pygame.mixer 準),支援變速與打擊音效"""
import threading
import numpy as np
try:
import sounddevice as sd
except Exception: # 沒有音訊裝置(例如 CI)時仍可載入、計算波形
sd = None
SAMPLE_RATE = 44100
def load_audio(path):
"""讀 wav/mp3/flac/ogg → float32 stereo ndarray (n, 2)"""
import miniaudio
dec = miniaudio.decode_file(path, output_format=miniaudio.SampleFormat.FLOAT32,
nchannels=2, sample_rate=SAMPLE_RATE)
return np.frombuffer(dec.samples, dtype=np.float32).reshape(-1, 2).copy()
def make_click(freq=1800.0, ms=30):
n = int(SAMPLE_RATE * ms / 1000)
t = np.arange(n) / SAMPLE_RATE
return (np.sin(2 * np.pi * freq * t) * np.exp(-t * 180) * 0.6).astype(np.float32)
class Player:
def __init__(self, samples):
self.samples = samples
self.pos = 0.0 # 播放位置(取樣,可為小數:變速時)
self.speed = 1.0
self.playing = False
self.hit_times = [] # 打擊音效時間點(ms,已排序)
self.hitsound = True
self._click = make_click()
self._clicks = [] # 進行中的打擊音效 [(offset_in_click)]
self._lock = threading.Lock()
self._stream = None
self.latency = 0.0
if sd is not None:
try:
self._stream = sd.OutputStream(samplerate=SAMPLE_RATE, channels=2, dtype="float32",
callback=self._callback, latency="low")
self._stream.start()
self.latency = self._stream.latency
except Exception:
self._stream = None
@property
def length_ms(self):
return len(self.samples) / SAMPLE_RATE * 1000
def position_ms(self):
"""目前「聽到」的位置:扣掉輸出延遲"""
with self._lock:
p = self.pos
heard = p / SAMPLE_RATE * 1000 - (self.latency * 1000 * self.speed if self.playing else 0)
return max(0.0, heard)
def seek(self, ms):
with self._lock:
self.pos = max(0.0, min(len(self.samples) - 1, ms / 1000 * SAMPLE_RATE))
self._clicks.clear()
def toggle(self):
self.playing = not self.playing
def set_hit_times(self, times):
with self._lock:
self.hit_times = sorted(times)
def close(self):
if self._stream is not None:
self._stream.stop()
self._stream.close()
def _callback(self, out, frames, time_info, status):
out.fill(0)
if not self.playing:
return
with self._lock:
start = self.pos
idx = start + np.arange(frames) * self.speed
i0 = idx.astype(np.int64)
valid = i0 < len(self.samples) - 1
if valid.any():
i0v = i0[valid]
frac = (idx[valid] - i0v)[:, None]
out[valid] = self.samples[i0v] * (1 - frac) + self.samples[i0v + 1] * frac
self.pos = start + frames * self.speed
if self.pos >= len(self.samples) - 1:
self.pos = len(self.samples) - 1
self.playing = False
if self.hitsound and self.hit_times:
t0 = start / SAMPLE_RATE * 1000
t1 = self.pos / SAMPLE_RATE * 1000
lo = np.searchsorted(self.hit_times, t0)
hi = np.searchsorted(self.hit_times, t1)
for ht in self.hit_times[lo:hi]:
at = int((ht - t0) / 1000 * SAMPLE_RATE / self.speed)
self._clicks.append(-at)
alive = []
for off in self._clicks:
a = max(0, -off)
c0 = max(0, off)
n = min(frames - a, len(self._click) - c0)
if n > 0:
out[a:a + n] += self._click[c0:c0 + n, None]
if off + frames < len(self._click):
alive.append(off + frames)
self._clicks = alive
def waveform(samples, bin_ms=10):
"""每 bin_ms 一個峰值(0~1),用於畫波形"""
mono = np.abs(samples).max(axis=1)
step = int(SAMPLE_RATE * bin_ms / 1000)
n = len(mono) // step
peaks = mono[: n * step].reshape(n, step).max(axis=1)
m = peaks.max() or 1.0
return peaks / m
+162
View File
@@ -0,0 +1,162 @@
"""譜面資料模型:三軌(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)
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 104 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.
+87
View File
@@ -0,0 +1,87 @@
"""產生示範曲包 demo.zip(節拍音軌 + 漸層封面 + 三種音符的範例譜面),全部由程式產生、無版權疑慮
用法:python examples/make_demo_pack.py [輸出路徑]
"""
import os
import sys
import tempfile
import wave
import numpy as np
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, ".."))
from chart import Note # noqa: E402
from pack import SongPack, default_config, save_pack # noqa: E402
from placer import auto_place # noqa: E402
BPM = 120
FIRST_BEAT = 1000
BEATS = 64
SR = 44100
def click_track(path):
beat = 60.0 / BPM
length = FIRST_BEAT / 1000 + BEATS * beat + 1.0
data = np.zeros(int(SR * length), dtype=np.float32)
n = int(SR * 0.05)
t = np.arange(n) / SR
for b in range(BEATS):
freq = 1760 if b % 4 == 0 else 1320
start = int((FIRST_BEAT / 1000 + b * beat) * SR)
data[start:start + n] += np.sin(2 * np.pi * freq * t) * np.exp(-t * 60) * 0.6
pcm = (np.clip(data, -1, 1) * 32767).astype(np.int16)
with wave.open(path, "wb") as w:
w.setnchannels(1)
w.setsampwidth(2)
w.setframerate(SR)
w.writeframes(pcm.tobytes())
def cover(path):
from PIL import Image
x = np.linspace(0, 1, 512)
r = (40 + 180 * x)[None, :].repeat(512, 0)
g = np.full((512, 512), 60.0)
b = (200 - 120 * x)[:, None].repeat(512, 1)
Image.fromarray(np.stack([r, g, b], -1).astype(np.uint8)).save(path)
def demo_notes():
beat = 60000 / BPM
notes = []
for i in range(48): # 前 48 拍:左右交替,每 4 拍一顆中間
t = int(FIRST_BEAT + i * beat)
notes.append(Note(t, "M" if i % 4 == 3 else ("L" if i % 2 == 0 else "R"), "tap"))
t = int(FIRST_BEAT + 48 * beat)
notes.append(Note(t, "L", "hold", int(t + 2 * beat)))
notes.append(Note(int(t + 2 * beat), "R", "hold", int(t + 4 * beat)))
notes.append(Note(int(t + 6 * beat), "L", "slide", int(t + 8 * beat)))
notes.append(Note(int(t + 10 * beat), "R", "slide", int(t + 12 * beat)))
return notes
def main():
out = sys.argv[1] if len(sys.argv) > 1 else os.path.join(HERE, "demo.zip")
tmp = tempfile.mkdtemp()
music, image = os.path.join(tmp, "music.wav"), os.path.join(tmp, "cover.png")
click_track(music)
cover(image)
pack = SongPack(default_config(id="demo", name="Maker Demo", artist="Rhyculator Maker",
charter="Rhyculator Maker", bpm=BPM, beat_offset=FIRST_BEAT,
normal_num=1))
pack.set_music(music)
pack.set_image(image)
chart = pack.chart("normal", create=True)
chart.notes = demo_notes()
auto_place(chart)
save_pack(pack, out)
pack.close()
print(f"已產生 {out}(normal {len(chart.notes)} 顆)")
if __name__ == "__main__":
main()
+113
View File
@@ -0,0 +1,113 @@
"""從 osu 譜面匯入成三軌(L/M/R)譜面,作為製譜起點
- taiko:don → L、ka → R、大音符 → M;同色快速連打改為左右交替,避免單手連打;
轉盤 → M 的 hold、連打條 → slide
- mania 4K:1-2 軌 → L、3-4 軌 → R、長條 → hold;同手和弦時其中一顆移到 M
"""
from chart import Chart, Note
from osu_parse import parse_osu
# 同一隻手連續兩下的最短間隔,比這更快就換手(ms)
ALTERNATE_BELOW = 150
def read_sections(path):
sections, cur = {}, None
for raw in open(path, encoding="utf-8"):
line = raw.strip()
if not line or line.startswith("//"):
continue
if line.startswith("[") and line.endswith("]"):
cur = line[1:-1]
sections[cur] = []
elif cur:
sections[cur].append(line)
return sections
def timing_info(sections):
"""第一個非繼承 timing point 的 BPM 與時間"""
for l in sections.get("TimingPoints", []):
p = l.split(",")
uninherited = p[6] == "1" if len(p) > 6 else True
if uninherited and float(p[1]) > 0:
return 60000.0 / float(p[1]), int(float(p[0]))
return 120.0, 0
def general(sections, key, default=""):
for l in sections.get("General", []):
if l.startswith(key + ":"):
return l.split(":", 1)[1].strip()
return default
def import_taiko(path):
sec = read_sections(path)
bpm, offset = timing_info(sec)
chart = Chart(general(sec, "AudioFilename"), round(bpm, 3), offset, 4)
last = {"L": -10**9, "R": -10**9}
prev_lane = None
for o in parse_osu(path):
t = o["time"]
if o["kind"] == "spinner":
chart.notes.append(Note(t, "M", "hold", o["end"]))
continue
if o["kind"] == "drumroll":
lane = "R" if prev_lane == "L" else "L"
chart.notes.append(Note(t, lane, "slide", o["end"]))
last[lane] = o["end"]
prev_lane = lane
continue
if o["big"]:
chart.notes.append(Note(t, "M", "tap"))
last["L"] = last["R"] = t
prev_lane = None
continue
lane = "R" if o["kat"] else "L"
other = "L" if lane == "R" else "R"
# 同一隻手太快 → 換另一隻手
if t - last[lane] < ALTERNATE_BELOW and t - last[other] >= ALTERNATE_BELOW:
lane = other
chart.notes.append(Note(t, lane, "tap"))
last[lane] = t
prev_lane = lane
chart.sort()
return chart
def import_mania4k(path):
sec = read_sections(path)
bpm, offset = timing_info(sec)
chart = Chart(general(sec, "AudioFilename"), round(bpm, 3), offset, 4)
busy_until = {"L": -10**9, "R": -10**9, "M": -10**9}
for l in sec["HitObjects"]:
p = l.split(",")
col = min(3, int(int(p[0]) * 4 / 512))
t, typ = int(p[2]), int(p[3])
end = int(p[5].split(":")[0]) if typ & 128 else None
lane = "L" if col <= 1 else "R"
# 同手已被佔用(和弦或長條中)→ 移到中間欄,再不行就略過
if busy_until[lane] >= t:
lane = "M" if busy_until["M"] < t else None
if lane is None:
continue
chart.notes.append(Note(t, lane, "hold" if end else "tap", end))
busy_until[lane] = end if end else t
chart.sort()
return chart
def import_osu(path):
sec = read_sections(path)
mode = general(sec, "Mode", "0")
if mode == "1":
return import_taiko(path)
if mode == "3":
return import_mania4k(path)
raise ValueError("目前只支援 osu!taiko 與 osu!mania 4K 譜面")
+2
View File
@@ -0,0 +1,2 @@
python -m venv .venv
.venv\Scripts\pip install -r requirements.txt
+241
View File
@@ -0,0 +1,241 @@
"""啟動視窗:選擇(或拖入)曲包 zip 開啟;留空按確定則建立新曲包
run_launcher() 回傳:
("open", zip 路徑)
("new", SongPack) 已建立並存檔的新曲包
None 取消
"""
import os
import zipfile
from pack import DIFFS, ID_RE, create_pack
AUDIO_TYPES = [("音訊或影片", "*.wav *.ogg *.mp3 *.mp4")]
IMAGE_TYPES = [("圖片", "*.png *.jpg *.jpeg *.webp")]
def check_open_path(path):
"""回傳錯誤訊息,沒問題回傳 None"""
if not path.lower().endswith(".zip"):
return "請選擇 .zip 曲包"
if not os.path.isfile(path):
return "找不到這個檔案"
if not zipfile.is_zipfile(path):
return "這不是有效的 zip 檔"
return None
def new_pack_errors(v):
"""新曲包表單的檢查(v 為各欄位字串與勾選狀態),回傳錯誤清單"""
errors = []
if not v.get("save_path", "").strip():
errors.append("請選擇曲包存放位置")
elif not v["save_path"].lower().endswith(".zip"):
errors.append("存放位置需為 .zip")
if not ID_RE.match(v.get("id", "").strip()):
errors.append("ID 只能用小寫英數字與 -(2~64 字)")
for k, label in (("name", "曲名"), ("artist", "曲師")):
if not v.get(k, "").strip():
errors.append(f"請填{label}")
try:
if float(v.get("bpm", "")) <= 0:
errors.append("BPM 必須大於 0")
except ValueError:
errors.append("BPM 必須是數字")
try:
int(v.get("beat_offset", "") or 0)
except ValueError:
errors.append("第一拍時間必須是整數(ms)")
media = v.get("media", "").strip()
if not media:
errors.append("請選擇音訊或影片")
elif not os.path.isfile(media):
errors.append("找不到音訊/影片檔")
image = v.get("image", "").strip()
if not image:
errors.append("請選擇封面圖片")
elif not os.path.isfile(image):
errors.append("找不到封面圖片")
chosen = [d for d in DIFFS if v.get(f"use_{d}")]
if not chosen:
errors.append("至少勾選一個難度")
for d in chosen:
try:
n = int(v.get(f"{d}_num", ""))
if not 1 <= n <= 99:
raise ValueError
except ValueError:
errors.append(f"{d} 的難度數字需為 1~99")
return errors
def _tk_root():
try:
from tkinterdnd2 import TkinterDnD
return TkinterDnD.Tk(), True
except Exception:
import tkinter as tk
return tk.Tk(), False
def run_launcher():
import tkinter as tk
from tkinter import filedialog, messagebox
root, dnd = _tk_root()
root.title("Rhyculator Maker")
root.resizable(False, False)
result = {"value": None}
# ---------- 開啟畫面 ----------
open_frame = tk.Frame(root, padx=16, pady=14)
path_var = tk.StringVar()
tk.Label(open_frame, text="開啟曲包", font=("Microsoft JhengHei", 14, "bold")).grid(row=0, column=0, columnspan=2, sticky="w")
drop = tk.Label(open_frame, text=("把曲包 .zip 拖到這裡" if dnd else "按「選擇檔案…」選擇曲包 .zip") +
"\n留空按「確定」可建立新曲包",
width=48, height=4, relief="groove", fg="#666")
drop.grid(row=1, column=0, columnspan=2, pady=(8, 8), sticky="we")
entry = tk.Entry(open_frame, textvariable=path_var, width=46)
entry.grid(row=2, column=0, sticky="we")
def browse_open():
p = filedialog.askopenfilename(parent=root, filetypes=[("Rhyculator 曲包", "*.zip")])
if p:
path_var.set(p)
tk.Button(open_frame, text="選擇檔案…", command=browse_open).grid(row=2, column=1, padx=(6, 0))
open_err = tk.Label(open_frame, text="", fg="#c33")
open_err.grid(row=3, column=0, columnspan=2, sticky="w")
if dnd:
from tkinterdnd2 import DND_FILES
def on_drop(e):
files = root.tk.splitlist(e.data)
if files:
path_var.set(files[0])
for w in (drop, entry):
w.drop_target_register(DND_FILES)
w.dnd_bind("<<Drop>>", on_drop)
def confirm_open():
p = path_var.get().strip().strip('"')
if not p:
open_frame.pack_forget()
new_frame.pack()
refresh_new()
return
err = check_open_path(p)
if err:
open_err.config(text=err)
return
result["value"] = ("open", os.path.abspath(p))
root.quit()
btns = tk.Frame(open_frame)
btns.grid(row=4, column=0, columnspan=2, sticky="e", pady=(8, 0))
tk.Button(btns, text="取消", width=10, command=root.quit).pack(side="right", padx=(6, 0))
tk.Button(btns, text="確定", width=10, command=confirm_open).pack(side="right")
open_frame.pack()
# ---------- 新曲包畫面 ----------
new_frame = tk.Frame(root, padx=16, pady=14)
tk.Label(new_frame, text="建立新曲包", font=("Microsoft JhengHei", 14, "bold")).grid(row=0, column=0, columnspan=3, sticky="w")
vars_ = {}
def add_row(r, key, label, default="", browse=None):
tk.Label(new_frame, text=label).grid(row=r, column=0, sticky="e", padx=(0, 6), pady=2)
var = tk.StringVar(value=default)
tk.Entry(new_frame, textvariable=var, width=40).grid(row=r, column=1, sticky="we", pady=2)
if browse:
tk.Button(new_frame, text="…", width=3, command=lambda: browse(var)).grid(row=r, column=2, padx=(4, 0))
vars_[key] = var
def browse_save(var):
p = filedialog.asksaveasfilename(parent=root, defaultextension=".zip", filetypes=[("Rhyculator 曲包", "*.zip")],
initialfile=(vars_["id"].get().strip() or "song") + ".zip")
if p:
var.set(p)
def browse_file(types):
def f(var):
p = filedialog.askopenfilename(parent=root, filetypes=types)
if p:
var.set(p)
return f
add_row(1, "save_path", "存放位置", browse=browse_save)
add_row(2, "id", "曲包 ID")
add_row(3, "name", "曲名")
add_row(4, "artist", "曲師")
add_row(5, "charter", "譜師")
add_row(6, "bpm", "BPM", "120")
add_row(7, "beat_offset", "第一拍 (ms)", "0")
add_row(8, "media", "音訊或影片", browse=browse_file(AUDIO_TYPES))
add_row(9, "image", "封面圖片", browse=browse_file(IMAGE_TYPES))
tk.Label(new_frame, text="難度").grid(row=10, column=0, sticky="ne", padx=(0, 6), pady=(6, 0))
diff_box = tk.Frame(new_frame)
diff_box.grid(row=10, column=1, columnspan=2, sticky="w", pady=(6, 0))
for i, d in enumerate(DIFFS):
use = tk.BooleanVar(value=(d == "normal"))
num = tk.StringVar()
tk.Checkbutton(diff_box, text=d, variable=use, width=7, anchor="w").grid(row=0, column=i * 2)
tk.Entry(diff_box, textvariable=num, width=4).grid(row=0, column=i * 2 + 1, padx=(0, 12))
vars_[f"use_{d}"] = use
vars_[f"{d}_num"] = num
tk.Label(diff_box, text="(勾選要有的難度並填難度數字)", fg="#666").grid(row=1, column=0, columnspan=6, sticky="w")
new_err = tk.Label(new_frame, text="", fg="#c33", justify="left", wraplength=380)
new_err.grid(row=11, column=0, columnspan=3, sticky="w", pady=(6, 0))
def values():
return {k: v.get() for k, v in vars_.items()}
def refresh_new(*_):
errs = new_pack_errors(values())
new_err.config(text="\n".join("・" + e for e in errs[:4]))
create_btn.config(state="disabled" if errs else "normal")
def back():
new_frame.pack_forget()
open_frame.pack()
def create():
v = values()
if new_pack_errors(v):
return
config = {"id": v["id"].strip(), "name": v["name"].strip(), "artist": v["artist"].strip(),
"charter": v["charter"].strip(), "bpm": float(v["bpm"]), "beat_offset": int(v["beat_offset"] or 0)}
diffs = {d: int(v[f"{d}_num"]) for d in DIFFS if v[f"use_{d}"]}
try:
root.config(cursor="watch")
root.update()
pack = create_pack(os.path.abspath(v["save_path"].strip()), config, v["media"].strip(),
v["image"].strip(), diffs)
except Exception as e:
root.config(cursor="")
messagebox.showerror("建立失敗", str(e), parent=root)
return
result["value"] = ("new", pack)
root.quit()
nb = tk.Frame(new_frame)
nb.grid(row=12, column=0, columnspan=3, sticky="e", pady=(8, 0))
create_btn = tk.Button(nb, text="建立", width=10, command=create)
create_btn.pack(side="right", padx=(6, 0))
tk.Button(nb, text="返回", width=10, command=back).pack(side="right")
for var in vars_.values():
var.trace_add("write", refresh_new)
root.protocol("WM_DELETE_WINDOW", root.quit)
root.bind("<Return>", lambda e: confirm_open() if open_frame.winfo_ismapped() else create())
entry.focus_set()
root.mainloop()
root.destroy()
return result["value"]
if __name__ == "__main__":
print(run_launcher())
+1023
View File
File diff suppressed because it is too large. Load diff
+52
View File
@@ -0,0 +1,52 @@
"""osu! 譜面(.osu)解析:回傳打擊物件清單,供 importers 使用"""
def parse_osu(path):
sections, cur = {}, None
for raw in open(path, encoding="utf-8"):
line = raw.strip()
if not line or line.startswith("//"):
continue
if line.startswith("[") and line.endswith("]"):
cur = line[1:-1]
sections[cur] = []
elif cur:
sections[cur].append(line)
diff = dict(l.split(":", 1) for l in sections["Difficulty"])
slider_mult = float(diff["SliderMultiplier"])
timing = []
for l in sections["TimingPoints"]:
p = l.split(",")
timing.append((float(p[0]), float(p[1]), p[6] == "1" if len(p) > 6 else True))
objs = []
for l in sections["HitObjects"]:
p = l.split(",")
t, typ, sound = int(p[2]), int(p[3]), int(p[4])
o = {"time": t, "kat": bool(sound & (2 | 8)), "big": bool(sound & 4)}
if typ & 8: # spinner / denden
o["kind"] = "spinner"
o["end"] = int(p[5])
elif typ & 2: # slider / drumroll
beat, sv = beat_at(timing, t)
length, slides = float(p[7]), int(p[6])
o["kind"] = "drumroll"
o["end"] = int(t + length / (slider_mult * 100 * sv) * beat * slides)
else:
o["kind"] = "hit"
objs.append(o)
return objs
def beat_at(timing, t):
beat, sv = 500.0, 1.0
for time, val, uninherited in timing:
if time > t:
break
if uninherited:
beat, sv = val, 1.0
else:
sv = -100.0 / val
return beat, sv
+269
View File
@@ -0,0 +1,269 @@
"""曲包(.zip)讀寫與驗證
<id>.zip
├─ config.json 必要
├─ easy.json / normal.json / hard.json 至少一個(統一格式:Chart.chart_json)
├─ music.wav|.ogg|.mp3 / video.mp4 至少一個;只有影片時會從影片抽出 music.wav
└─ image.png 必要,正方形
"""
import json
import os
import re
import shutil
import subprocess
import tempfile
import zipfile
from chart import Chart
PACK_FORMAT = 1
DIFFS = ("easy", "normal", "hard")
MUSIC_NAMES = ("music.wav", "music.ogg", "music.mp3")
VIDEO_NAME = "video.mp4"
IMAGE_NAME = "image.png"
CONFIG_NAME = "config.json"
IMAGE_SIZE = 512
ALLOWED = {CONFIG_NAME, IMAGE_NAME, VIDEO_NAME, *MUSIC_NAMES, *(f"{d}.json" for d in DIFFS)}
ID_RE = re.compile(r"^[a-z0-9][a-z0-9-]{1,63}$")
REQUIRED_TEXT = ("id", "name", "artist")
REQUIRED_NUM = ("bpm", "beat_offset", "offset")
def default_config(**over):
c = {"format": PACK_FORMAT, "id": "", "name": "", "artist": "", "charter": "",
"bpm": 120.0, "beat_offset": 0, "offset": 0, "preview_start": 0, "preview_length": 15000}
c.update(over)
return c
class SongPack:
def __init__(self, config=None):
self.workdir = tempfile.mkdtemp(prefix="rhypack_")
self.config = config or default_config()
self.charts = {} # 難度 → Chart
self.path = None # 對應的 .zip
# ---------- 檔案位置 ----------
def file(self, name):
return os.path.join(self.workdir, name)
@property
def music(self):
for n in MUSIC_NAMES:
if os.path.exists(self.file(n)):
return self.file(n)
return None
@property
def video(self):
return self.file(VIDEO_NAME) if os.path.exists(self.file(VIDEO_NAME)) else None
@property
def image(self):
return self.file(IMAGE_NAME) if os.path.exists(self.file(IMAGE_NAME)) else None
def close(self):
shutil.rmtree(self.workdir, ignore_errors=True)
# ---------- 難度 ----------
# 「難度存在」= charts 裡有這個 key(曲包內有該檔案,可以是空譜面)
def enabled(self):
return [d for d in DIFFS if d in self.charts]
def enable(self, diff, num=None):
self.chart(diff, create=True)
if num is not None:
self.config[f"{diff}_num"] = int(num)
def disable(self, diff):
self.charts.pop(diff, None)
self.config.pop(f"{diff}_num", None)
# ---------- 內容 ----------
def chart(self, diff, create=False):
if diff not in self.charts and create:
self.charts[diff] = Chart(self.music or "", float(self.config["bpm"]),
int(self.config["beat_offset"]), 4, [])
return self.charts.get(diff)
def sync_timing(self):
"""config 的 bpm / beat_offset 套用到各難度(Maker 格線用)"""
for c in self.charts.values():
c.bpm = float(self.config["bpm"])
c.offset = int(self.config["beat_offset"])
c.audio = self.music or ""
def set_music(self, src):
ext = os.path.splitext(src)[1].lower()
name = f"music{ext}"
if name not in MUSIC_NAMES:
raise ValueError("音訊只支援 wav / ogg / mp3")
for n in MUSIC_NAMES:
if os.path.exists(self.file(n)):
os.remove(self.file(n))
shutil.copyfile(src, self.file(name))
self.sync_timing()
def set_video(self, src):
shutil.copyfile(src, self.file(VIDEO_NAME))
# 時間以音訊為準:沒有音訊時從影片抽出
if self.music is None:
extract_audio(self.file(VIDEO_NAME), self.file("music.wav"))
self.sync_timing()
def set_image(self, src):
import_image(src, self.file(IMAGE_NAME))
# ---------- 讀寫 ----------
def open_pack(zip_path):
pack = SongPack()
with zipfile.ZipFile(zip_path) as z:
for info in z.infolist():
name = info.filename
# 只接受白名單檔名(防止 zip 內的路徑寫到別處)
if name not in ALLOWED:
continue
with z.open(info) as src, open(pack.file(name), "wb") as dst:
shutil.copyfileobj(src, dst)
if os.path.exists(pack.file(CONFIG_NAME)):
pack.config = default_config(**json.load(open(pack.file(CONFIG_NAME), encoding="utf-8")))
for d in DIFFS:
p = pack.file(f"{d}.json")
if os.path.exists(p):
pack.charts[d] = Chart.from_chart_json(json.load(open(p, encoding="utf-8")),
pack.config["bpm"], pack.config["beat_offset"],
pack.music or "")
pack.path = zip_path
return pack
def save_pack(pack, zip_path):
"""驗證通過才寫入;先寫暫存檔再取代,失敗不會弄壞原本的曲包"""
errors = validate_pack(pack)
if errors:
raise ValueError(";".join(errors))
pack.config["format"] = PACK_FORMAT
tmp = zip_path + ".tmp"
with zipfile.ZipFile(tmp, "w", zipfile.ZIP_DEFLATED) as z:
z.writestr(CONFIG_NAME, json.dumps(pack.config, ensure_ascii=False, indent=2))
# 啟用的難度全部寫入(空譜面也寫,代表這個難度存在)
for d in pack.enabled():
z.writestr(f"{d}.json", json.dumps(pack.charts[d].chart_json(), ensure_ascii=False, indent=1))
# 音訊 / 影片本身已壓縮或很大,不再壓縮
for path in (pack.music, pack.video):
if path:
z.write(path, os.path.basename(path), compress_type=zipfile.ZIP_STORED)
z.write(pack.image, IMAGE_NAME, compress_type=zipfile.ZIP_STORED)
os.replace(tmp, zip_path)
pack.path = zip_path
def validate_pack(pack):
errors = []
cfg = pack.config
for k in REQUIRED_TEXT:
if not str(cfg.get(k, "")).strip():
errors.append(f"config 缺少 {k}")
if cfg.get("id") and not ID_RE.match(cfg["id"]):
errors.append("id 只能用小寫英數字與 -(2~64 字)")
for k in REQUIRED_NUM:
try:
float(cfg.get(k))
except (TypeError, ValueError):
errors.append(f"config 的 {k} 必須是數字")
try:
if float(cfg.get("bpm", 0)) <= 0:
errors.append("bpm 必須大於 0")
except (TypeError, ValueError):
pass
present = pack.enabled()
if not present:
errors.append("至少需要啟用一個難度")
for d in present:
v = cfg.get(f"{d}_num")
if not isinstance(v, int) or not (1 <= v <= 99):
errors.append(f"{d} 有譜面,config 需要 {d}_num(1~99 的整數)")
if pack.music is None and pack.video is None:
errors.append("至少需要 music 或 video")
if pack.image is None:
errors.append("缺少 image.png")
else:
from PIL import Image
with Image.open(pack.image) as im:
if im.width != im.height:
errors.append(f"image.png 必須是正方形(目前 {im.width}x{im.height})")
return errors
# ---------- 媒體 ----------
def import_image(src, dst, size=IMAGE_SIZE):
"""置中裁成正方形並縮放"""
from PIL import Image
with Image.open(src) as im:
im = im.convert("RGBA")
side = min(im.size)
left, top = (im.width - side) // 2, (im.height - side) // 2
im = im.crop((left, top, left + side, top + side)).resize((size, size), Image.LANCZOS)
im.save(dst, "PNG")
def convert_audio(src, dst, quality=6):
"""轉成 Ogg Vorbis(quality 0~10,6 約 192kbps),44.1kHz 雙聲道"""
import imageio_ffmpeg
ffmpeg = imageio_ffmpeg.get_ffmpeg_exe()
subprocess.run([ffmpeg, "-y", "-loglevel", "error", "-i", src, "-vn", "-ac", "2", "-ar", "44100",
"-c:a", "libvorbis", "-q:a", str(quality), dst], check=True)
def extract_audio(video, dst):
"""用 imageio-ffmpeg 內附的 ffmpeg 抽出 44.1kHz 雙聲道 wav"""
import imageio_ffmpeg
ffmpeg = imageio_ffmpeg.get_ffmpeg_exe()
subprocess.run([ffmpeg, "-y", "-loglevel", "error", "-i", video, "-vn", "-ac", "2", "-ar", "44100",
"-f", "wav", dst], check=True)
def create_pack(zip_path, config, media, image, diffs):
"""建立新曲包並立即存檔(譜面可為空);diffs = {難度: 難度數字}。回傳已開啟的 SongPack"""
pack = SongPack(default_config(**config))
try:
if media.lower().endswith(".mp4"):
pack.set_video(media)
else:
pack.set_music(media)
pack.set_image(image)
for d, num in diffs.items():
pack.enable(d, num)
save_pack(pack, zip_path)
except Exception:
pack.close()
raise
return pack
# ---------- 遷移 ----------
def pack_from_lanes(lanes_by_diff, image_src, **config):
"""把舊的 *.lanes.json(每難度一份)轉成曲包;音訊取第一份的 audio"""
pack = SongPack()
first = None
for d, path in lanes_by_diff.items():
c = Chart.load(path)
if first is None:
first = (c, path)
pack.charts[d] = c
c0, p0 = first
audio = c0.audio if os.path.isabs(c0.audio) else os.path.join(os.path.dirname(p0), c0.audio)
pack.config = default_config(bpm=c0.bpm, beat_offset=c0.offset, **config)
pack.set_music(audio)
pack.set_image(image_src)
return pack
+123
View File
@@ -0,0 +1,123 @@
"""第二階段:依手的區域把音符自動配置到 5x6 格子
規則
- L 軌只用左手區、R 軌只用右手區、M 軌只用中間欄;slide 可進中間欄但不跨到另一手
- 每隻手記住自己上一格;間隔越短,下一格只能離上一格越近(同一隻手連打不用大跳)
- 同一格在音符顯示期間(判定前 APPEAR_MS ~ 判定後 EXPIRE_MS)不重複使用
- M 軌交給「目前空著、且最久沒按」的那隻手
- locked 的音符保留座標,但仍計入格子與手的佔用
- 固定亂數種子,結果可重現
"""
import random
from zones import COLS, ROWS, APPEAR_MS, EXPIRE_MS, TAP_COLS, SLIDE_COLS
from chart import slide_steps
CELL_MARGIN = 50 # 格子釋放後再多留一點緩衝(ms),避免掉幀時同格重疊
class HandState:
def __init__(self, start):
self.cell = start
self.last_time = -10**9 # 上一次按下的時間
self.busy_until = -10**9 # hold / slide 進行中
def assign_hand(note, hands):
"""回傳負責這顆音符的手('L' / 'R'),M 軌選空著且最久沒按的手"""
if note.lane in ("L", "R"):
return note.lane
free = [h for h in ("L", "R") if hands[h].busy_until < note.t]
pool = free or ["L", "R"]
return min(pool, key=lambda h: hands[h].last_time)
def reach_for(gap):
return 1 if gap < 140 else 2 if gap < 300 else max(COLS, ROWS)
class ZonePlacer:
def __init__(self, seed=1):
self.rng = random.Random(seed)
self.cell_free_at = {(x, y): -10**9 for x in range(COLS) for y in range(ROWS)}
self.hands = {"L": HandState((1, 2)), "R": HandState((3, 2))}
def _free(self, cell, t):
return self.cell_free_at[cell] <= t - APPEAR_MS
def _occupy(self, cell, t_end):
self.cell_free_at[cell] = t_end + EXPIRE_MS + CELL_MARGIN
def _pick(self, t, cols, hand):
h = self.hands[hand]
reach = reach_for(t - h.last_time)
lx, ly = h.cell
cells = [(x, y) for x in cols for y in range(ROWS)]
cands = [c for c in cells if c != h.cell and self._free(c, t)
and max(abs(c[0] - lx), abs(c[1] - ly)) <= reach]
if not cands:
cands = [c for c in cells if self._free(c, t)]
if not cands:
cands = [min(cells, key=lambda c: self.cell_free_at[c])]
return self.rng.choice(cands)
def _path(self, t0, t1, steps, cols, hand):
h = self.hands[hand]
interval = (t1 - t0) / max(1, steps - 1)
start = self._pick(t0, cols, hand)
path = [start]
cur = start
for i in range(1, steps):
t = t0 + interval * i
x, y = cur
nbrs = [(x + dx, y + dy) for dx in (-1, 0, 1) for dy in (-1, 0, 1)
if (dx or dy) and (x + dx) in cols and 0 <= y + dy < ROWS
and (x + dx, y + dy) not in path and self._free((x + dx, y + dy), t)]
# 傾向直線前進,看起來像一筆畫
if len(path) >= 2:
d = (path[-1][0] - path[-2][0], path[-1][1] - path[-2][1])
straight = (x + d[0], y + d[1])
if straight in nbrs and self.rng.random() < 0.6:
nbrs = [straight]
if not nbrs:
break
cur = self.rng.choice(nbrs)
path.append(cur)
return path
def _commit(self, note, hand):
h = self.hands[hand]
if note.type == "slide":
k = len(note.path)
interval = (note.end_time - note.t) / max(1, k - 1)
for i, c in enumerate(note.path):
self._occupy(c, note.t + interval * i)
h.cell = note.path[-1]
else:
self._occupy(note.pos, note.end_time)
h.cell = note.pos
h.last_time = note.end_time if note.type != "tap" else note.t
if note.type != "tap":
h.busy_until = note.end_time
def place(self, chart, only_unplaced=False):
"""配置 chart 內所有未鎖定的音符(only_unplaced=True 時只配置還沒有座標的)"""
chart.sort()
for note in chart.notes:
hand = assign_hand(note, self.hands)
keep = note.locked or (only_unplaced and note.placed())
if not keep:
if note.type == "slide":
steps = slide_steps(chart, note)
note.path = self._path(note.t, note.end_time, steps, SLIDE_COLS[note.lane], hand)
note.pos = None
else:
note.pos = self._pick(note.t, TAP_COLS[note.lane], hand)
note.path = None
if note.placed():
self._commit(note, hand)
return chart
def auto_place(chart, seed=1, only_unplaced=False):
return ZonePlacer(seed).place(chart, only_unplaced)
+8
View File
@@ -0,0 +1,8 @@
pygame-ce>=2.4
numpy
miniaudio
sounddevice
Pillow
imageio-ffmpeg
tkinterdnd2
pytest
+1
View File
@@ -0,0 +1 @@
.venv\Scripts\python maker.py %*
+224
View File
@@ -0,0 +1,224 @@
import os
import sys
import pytest
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, ".."))
from chart import Chart, Note, slide_steps # noqa: E402
from placer import auto_place # noqa: E402
from validate import validate # noqa: E402
from zones import TAP_COLS, SLIDE_COLS # noqa: E402
BPM = 120.0 # 1 拍 = 500 ms
def make(notes, divisor=4):
c = Chart("", BPM, 1000, divisor, notes)
c.sort()
return c
# ---------- 格線 ----------
def test_snap_to_grid():
c = make([])
assert c.snap(1000) == 1000
assert c.snap(1120) == 1125 # 1/4 拍 = 125 ms
assert c.snap(1060) == 1000
assert c.snap(1063, divisor=8) == 1062 or c.snap(1063, divisor=8) == 1063
def test_grid_lines_mark_beats_and_bars():
c = make([])
lines = c.grid_lines(1000, 3000)
assert lines[0] == (1000, True, True)
assert sum(1 for _, beat, _ in lines if beat) == 5 # 1000..3000 每 500ms
assert sum(1 for _, _, bar in lines if bar) == 2 # 1000、3000
# ---------- 自動配置的區域限制 ----------
def dense_chart():
notes = []
t = 1000
for i in range(200):
notes.append(Note(t, "LRM"[i % 3], "tap"))
t += 125
notes.append(Note(t + 500, "L", "hold", t + 1500))
notes.append(Note(t + 2000, "R", "slide", t + 3000))
notes.append(Note(t + 4000, "L", "slide", t + 5000))
return make(notes)
def test_auto_place_respects_zones():
c = auto_place(dense_chart())
for n in c.notes:
if n.type == "slide":
assert all(x in SLIDE_COLS[n.lane] for x, _ in n.path)
assert len(n.path) >= 2
else:
assert n.pos[0] in TAP_COLS[n.lane]
assert validate(c) == []
def test_slide_never_crosses_to_other_hand():
c = auto_place(dense_chart())
for n in c.notes:
if n.type == "slide" and n.lane == "L":
assert max(x for x, _ in n.path) <= 2
if n.type == "slide" and n.lane == "R":
assert min(x for x, _ in n.path) >= 2
def test_auto_place_is_deterministic_and_keeps_locked():
a = auto_place(dense_chart(), seed=7)
b = dense_chart()
b.notes[10].pos, b.notes[10].locked = (0, 5) if b.notes[10].lane == "L" else (2, 5) if b.notes[10].lane == "M" else (4, 5), True
locked = b.notes[10].pos
auto_place(b, seed=7)
assert b.notes[10].pos == locked
assert [n.pos for n in auto_place(dense_chart(), seed=7).notes] == [n.pos for n in a.notes]
# ---------- 檢查 ----------
def test_validate_zone_violation_and_overlap():
c = make([Note(1000, "L", "tap", pos=(4, 0)), # 左手放到右手區
Note(2000, "R", "tap", pos=(3, 0)),
Note(2300, "R", "tap", pos=(3, 0))]) # 同格 300ms 內重複
msgs = [m for _, m in validate(c)]
assert any("不在 L 軌" in m for m in msgs)
assert any("重疊" in m for m in msgs)
def test_validate_same_hand_simultaneous():
c = make([Note(1000, "L", "hold", 2000, pos=(0, 0)),
Note(1500, "L", "tap", pos=(1, 5))]) # 左手 hold 中又按
assert any("左手同時" in m for _, m in validate(c))
c2 = make([Note(1000, "L", "hold", 2000, pos=(0, 0)),
Note(1000, "R", "hold", 2000, pos=(4, 0)),
Note(1500, "M", "tap", pos=(2, 3))]) # 兩手都忙
assert any("沒有空著的手" in m for _, m in validate(c2))
c3 = make([Note(1000, "L", "hold", 2000, pos=(0, 0)),
Note(1500, "M", "tap", pos=(2, 3))]) # 右手空著 → 合法
assert validate(c3) == []
# ---------- 匯出 ----------
def test_export_sheet_matches_game_format():
c = make([Note(1000, "L", "tap", pos=(1, 2)),
Note(2000, "R", "hold", 2500, pos=(3, 1)),
Note(3000, "L", "slide", 3500, path=[(0, 0), (1, 1), (2, 2)])])
sheet = c.export_sheet()
assert sheet[0] == {"type": "tap", "startTime": 1000, "pos": {"x": 1, "y": 2}}
assert sheet[1] == {"type": "hold", "startTime": 2000, "endTime": 2500, "pos": {"x": 3, "y": 1}}
s = sheet[2]
# 遊戲把第 i 格放在 start + i*(end-start)/len:最後一格應落在 3500
last_hit = s["startTime"] + (s["endTime"] - s["startTime"]) / len(s["path"]) * (len(s["path"]) - 1)
assert last_hit == pytest.approx(3500)
def test_save_load_roundtrip(tmp_path):
c = auto_place(dense_chart())
c.notes[0].locked = True
p = tmp_path / "x.lanes.json"
c.save(p)
d = Chart.load(p)
assert d.bpm == c.bpm and d.offset == c.offset and len(d.notes) == len(c.notes)
assert [(n.t, n.lane, n.type, n.pos, n.path, n.locked) for n in d.notes] == \
[(n.t, n.lane, n.type, n.pos, n.path, n.locked) for n in c.notes]
def test_slide_steps_follow_divisor():
c = make([])
assert slide_steps(c, Note(1000, "L", "slide", 1500)) == 5 # 500ms / 125ms + 1
# ---------- osu 匯入(有 osu 檔時才跑)----------
OSU_DIR = os.environ.get("RHY_OSU_DIR")
@pytest.mark.skipif(not OSU_DIR, reason="設定 RHY_OSU_DIR 指向解壓的 osu 譜面資料夾")
def test_import_taiko_keeps_all_objects():
import glob
from importers import import_osu
from osu_parse import parse_osu
for f in glob.glob(os.path.join(OSU_DIR, "*.osu")):
c = import_osu(f)
assert len(c.notes) == len(parse_osu(f))
auto_place(c)
assert validate(c) == [], f
# ---------- 編輯器操作(無視窗)----------
@pytest.fixture
def editor():
os.environ["SDL_VIDEODRIVER"] = "dummy"
import pygame
from maker import Editor
ed = Editor(audio_enabled=False)
ed.chart = Chart("", BPM, 0, 4, [])
yield ed
pygame.quit()
def _click(ed, x, y, button=1, up_y=None, shift=False):
import pygame
pygame.key.set_mods(pygame.KMOD_SHIFT if shift else 0)
ed.handle(pygame.event.Event(pygame.MOUSEBUTTONDOWN, pos=(x, y), button=button))
if button == 1:
ed.handle(pygame.event.Event(pygame.MOUSEBUTTONUP, pos=(x, up_y if up_y is not None else y), button=1))
pygame.key.set_mods(0)
def test_editor_place_tap_hold_slide_and_undo(editor):
from maker import lane_x, JUDGE_Y, LANE_W
ed = editor
ed.time_ms = 0
# 判定線上方 125ms 處點一下 → L 軌 tap
y = JUDGE_Y - 125 * ed.zoom
_click(ed, lane_x("L") + LANE_W // 2, y)
assert [(n.lane, n.type, n.t) for n in ed.chart.notes] == [("L", "tap", 125)]
# R 軌往上拖 500ms → hold
_click(ed, lane_x("R") + LANE_W // 2, JUDGE_Y - 500 * ed.zoom, up_y=JUDGE_Y - 1000 * ed.zoom)
hold = [n for n in ed.chart.notes if n.lane == "R"][0]
assert (hold.type, hold.t, hold.end) == ("hold", 500, 1000)
# Shift + 拖曳 → slide
_click(ed, lane_x("M") + LANE_W // 2, JUDGE_Y - 1500 * ed.zoom, up_y=JUDGE_Y - 2000 * ed.zoom, shift=True)
assert any(n.type == "slide" and n.lane == "M" for n in ed.chart.notes)
# 右鍵刪除 tap,再復原
_click(ed, lane_x("L") + LANE_W // 2, y, button=3)
assert not any(n.lane == "L" for n in ed.chart.notes)
ed.undo()
assert any(n.lane == "L" for n in ed.chart.notes)
def test_editor_assign_cell_respects_zone(editor):
from maker import cell_rect
ed = editor
note = ed.chart.add(Note(1000, "L", "tap"))
ed.tab = "pos"
ed.selected = note
r = cell_rect(4, 0) # 右手區 → 拒絕
_click(ed, r.centerx, r.centery)
assert note.pos is None
r = cell_rect(1, 3)
_click(ed, r.centerx, r.centery)
assert note.pos == (1, 3) and note.locked
def test_editor_recording_snaps(editor):
ed = editor
ed.recorded = [("L", 1010), ("R", 1490), ("M", 2130)]
ed.finish_recording()
assert [(n.lane, n.t) for n in ed.chart.notes] == [("L", 1000), ("R", 1500), ("M", 2125)]
+289
View File
@@ -0,0 +1,289 @@
import json
import os
import subprocess
import sys
import wave
import zipfile
import numpy as np
import pytest
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, ".."))
from chart import Note # noqa: E402
from pack import (SongPack, default_config, open_pack, save_pack, # noqa: E402
validate_pack, import_image, extract_audio)
# ---------- 測試素材 ----------
def write_wav(path, seconds=1.0):
sr = 44100
t = np.arange(int(sr * seconds)) / sr
data = (np.sin(2 * np.pi * 440 * t) * 8000).astype(np.int16)
with wave.open(str(path), "wb") as w:
w.setnchannels(1)
w.setsampwidth(2)
w.setframerate(sr)
w.writeframes(data.tobytes())
return str(path)
def write_image(path, size=(800, 600)):
from PIL import Image
Image.new("RGB", size, (200, 80, 120)).save(path)
return str(path)
def make_pack(tmp_path):
p = SongPack(default_config(id="test-song", name="Test", artist="Someone", charter="Me",
bpm=120.0, beat_offset=100, easy_num=3, hard_num=12))
p.set_music(write_wav(tmp_path / "a.wav"))
p.set_image(write_image(tmp_path / "cover.jpg"))
e = p.chart("easy", create=True)
e.notes = [Note(100, "L", "tap", pos=(0, 1)), Note(600, "R", "hold", 900, pos=(4, 2), locked=True)]
h = p.chart("hard", create=True)
h.notes = [Note(100, "M", "tap", pos=(2, 0)),
Note(400, "L", "slide", 800, path=[(0, 0), (1, 1), (2, 2)])]
return p
# ---------- 往返 ----------
def test_save_open_roundtrip(tmp_path):
p = make_pack(tmp_path)
z = str(tmp_path / "test-song.zip")
save_pack(p, z)
names = set(zipfile.ZipFile(z).namelist())
assert names == {"config.json", "easy.json", "hard.json", "music.wav", "image.png"} # 沒有 normal
q = open_pack(z)
assert q.config["id"] == "test-song" and q.config["easy_num"] == 3
assert set(q.charts) == {"easy", "hard"}
def dump(pack, d):
return [(n.t, n.lane, n.type, n.end, n.pos, n.path, n.locked) for n in pack.charts[d].notes]
for d in ("easy", "hard"):
assert dump(q, d) == dump(p, d)
# 曲目層級的 BPM / 第一拍來自 config
assert q.charts["easy"].bpm == 120.0 and q.charts["easy"].offset == 100
def test_chart_file_is_unified_format(tmp_path):
p = make_pack(tmp_path)
z = str(tmp_path / "x.zip")
save_pack(p, z)
d = json.loads(zipfile.ZipFile(z).read("easy.json"))
assert d["format"] == 1 and d["divisor"] == 4
assert d["notes"][1] == {"t": 600, "lane": "R", "type": "hold", "end": 900,
"pos": {"x": 4, "y": 2}, "locked": True}
assert "bpm" not in d
def test_save_failure_keeps_old_zip(tmp_path):
p = make_pack(tmp_path)
z = str(tmp_path / "x.zip")
save_pack(p, z)
before = open(z, "rb").read()
p.config["name"] = ""
with pytest.raises(ValueError):
save_pack(p, z)
assert open(z, "rb").read() == before
def test_open_ignores_unexpected_paths(tmp_path):
z = tmp_path / "evil.zip"
with zipfile.ZipFile(z, "w") as f:
f.writestr("config.json", json.dumps(default_config(id="x1", name="n", artist="a")))
f.writestr("../escape.txt", "nope")
f.writestr("sub/easy.json", "{}")
q = open_pack(str(z))
assert not os.path.exists(os.path.join(os.path.dirname(q.workdir), "escape.txt"))
assert q.charts == {}
# ---------- 驗證 ----------
def test_validate_reports_each_problem(tmp_path):
p = make_pack(tmp_path)
assert validate_pack(p) == []
p.config["id"] = "Bad ID"
p.config.pop("hard_num")
p.config["bpm"] = "fast"
errs = " ".join(validate_pack(p))
assert "id 只能用" in errs and "hard_num" in errs and "bpm" in errs
q = SongPack(default_config(id="empty", name="n", artist="a"))
errs = " ".join(validate_pack(q))
assert "至少需要啟用一個難度" in errs and "music 或 video" in errs and "image.png" in errs
def test_validate_rejects_non_square_image(tmp_path):
p = make_pack(tmp_path)
from PIL import Image
Image.new("RGB", (300, 200)).save(p.file("image.png"))
assert any("正方形" in e for e in validate_pack(p))
def test_import_image_center_crop(tmp_path):
from PIL import Image
src = tmp_path / "wide.png"
im = Image.new("RGB", (900, 300), (0, 0, 255))
for x in range(300, 600): # 中間 300x300 為紅色
for y in range(300):
im.putpixel((x, y), (255, 0, 0))
im.save(src)
dst = tmp_path / "out.png"
import_image(str(src), str(dst))
out = Image.open(dst).convert("RGB")
assert out.size == (512, 512)
assert out.getpixel((10, 256)) == (255, 0, 0) and out.getpixel((500, 256)) == (255, 0, 0)
# ---------- 只有影片 ----------
def test_video_only_extracts_audio(tmp_path):
import imageio_ffmpeg
ff = imageio_ffmpeg.get_ffmpeg_exe()
video = str(tmp_path / "clip.mp4")
subprocess.run([ff, "-y", "-loglevel", "error", "-f", "lavfi", "-i", "color=c=black:s=64x64:d=2",
"-f", "lavfi", "-i", "sine=frequency=440:duration=2", "-shortest",
"-c:v", "libx264", "-c:a", "aac", video], check=True)
p = SongPack(default_config(id="video-song", name="v", artist="a", normal_num=5))
p.set_video(video)
assert p.video and p.music and p.music.endswith("music.wav")
with wave.open(p.music) as w:
assert w.getframerate() == 44100 and w.getnchannels() == 2
assert abs(w.getnframes() / 44100 - 2.0) < 0.1
p.set_image(write_image(tmp_path / "c.png", (256, 256)))
p.chart("normal", create=True).notes = [Note(500, "M", "tap", pos=(2, 2))]
z = str(tmp_path / "v.zip")
save_pack(p, z)
assert {"video.mp4", "music.wav"} <= set(zipfile.ZipFile(z).namelist())
# ---------- Maker:難度切換 ----------
def test_maker_switch_difficulty_keeps_edits_and_undo(tmp_path):
os.environ["SDL_VIDEODRIVER"] = "dummy"
import pygame
from maker import Editor
p = make_pack(tmp_path)
ed = Editor(audio_enabled=False)
try:
ed.set_pack(p, "easy")
ed.push_undo()
ed.chart.add(Note(1500, "L", "tap"))
ed.switch_diff("normal") # 不存在 → 建立空譜面
assert ed.chart.notes == [] and "normal" in p.charts
assert ed.undo_stack == [] # undo 各難度獨立
ed.switch_diff("easy")
assert len(ed.chart.notes) == 3 # 剛剛的編輯還在
ed.undo()
assert len(ed.chart.notes) == 2
finally:
pygame.quit()
# ---------- 啟用 / 停用難度、空曲包 ----------
def test_empty_pack_can_be_saved_and_opened(tmp_path):
from pack import create_pack
z = str(tmp_path / "new.zip")
p = create_pack(z, {"id": "new-song", "name": "N", "artist": "A", "bpm": 150.0, "beat_offset": 0},
write_wav(tmp_path / "m.wav"), write_image(tmp_path / "c.png"), {"normal": 5, "hard": 11})
assert p.path == z
names = set(zipfile.ZipFile(z).namelist())
assert {"normal.json", "hard.json"} <= names and "easy.json" not in names
q = open_pack(z)
assert q.enabled() == ["normal", "hard"]
assert q.charts["normal"].notes == [] and q.config["hard_num"] == 11
def test_disable_removes_difficulty_on_save(tmp_path):
p = make_pack(tmp_path)
z = str(tmp_path / "x.zip")
save_pack(p, z)
p.disable("easy")
save_pack(p, z) # 同一路徑直接覆蓋
q = open_pack(z)
assert q.enabled() == ["hard"]
assert "easy.json" not in zipfile.ZipFile(z).namelist() and "easy_num" not in q.config
def test_at_least_one_difficulty_required(tmp_path):
p = make_pack(tmp_path)
p.disable("easy")
p.disable("hard")
assert any("至少需要啟用一個難度" in e for e in validate_pack(p))
def test_enabled_difficulty_needs_number(tmp_path):
p = make_pack(tmp_path)
p.enable("normal") # 沒給難度數字
assert any("normal_num" in e for e in validate_pack(p))
p.enable("normal", 7)
assert validate_pack(p) == []
def test_convert_audio_to_ogg_keeps_length(tmp_path):
from pack import convert_audio
from audio import load_audio
src = write_wav(tmp_path / "a.wav", seconds=3.0)
dst = str(tmp_path / "a.ogg")
convert_audio(src, dst)
assert os.path.getsize(dst) < os.path.getsize(src)
assert abs(len(load_audio(dst)) / 44100 - 3.0) < 0.05
# ---------- 啟動視窗的檢查 ----------
def test_launcher_checks(tmp_path):
from launcher import check_open_path, new_pack_errors
assert check_open_path(str(tmp_path / "nope.zip")) == "找不到這個檔案"
assert check_open_path("song.txt") == "請選擇 .zip 曲包"
bad = tmp_path / "bad.zip"
bad.write_text("not a zip")
assert check_open_path(str(bad)) == "這不是有效的 zip 檔"
ok = {"save_path": str(tmp_path / "s.zip"), "id": "my-song", "name": "N", "artist": "A", "charter": "",
"bpm": "120", "beat_offset": "0", "media": write_wav(tmp_path / "m.wav"),
"image": write_image(tmp_path / "c.png"), "use_easy": False, "use_normal": True, "use_hard": False,
"easy_num": "", "normal_num": "6", "hard_num": ""}
assert new_pack_errors(ok) == []
errs = new_pack_errors(dict(ok, id="My Song", bpm="x", use_normal=False))
assert any("ID" in e for e in errs) and any("BPM" in e for e in errs) and any("至少勾選" in e for e in errs)
assert any("normal 的難度數字" in e for e in new_pack_errors(dict(ok, normal_num="0")))
# ---------- Maker:難度勾選列 ----------
def test_maker_diff_toggle(tmp_path, monkeypatch):
os.environ["SDL_VIDEODRIVER"] = "dummy"
import pygame
from maker import Editor
p = make_pack(tmp_path)
ed = Editor(audio_enabled=False)
try:
ed.set_pack(p, "hard")
monkeypatch.setattr(ed, "dialog_number", lambda *a: 8)
monkeypatch.setattr(ed, "confirm", lambda *a: True)
ed.toggle_diff("normal") # 啟用 normal → 切過去
assert ed.diff == "normal" and p.config["normal_num"] == 8
ed.toggle_diff("hard") # 停用目前以外的難度
assert "hard" not in p.charts
ed.toggle_diff("normal") # 停用目前難度 → 自動切到 easy
assert ed.diff == "easy" and p.enabled() == ["easy"]
ed.toggle_diff("easy") # 最後一個不能停用
assert p.enabled() == ["easy"]
# 點擊勾選列也能操作
d, box, lv = ed.diff_bar_rects()[2]
ed.handle(pygame.event.Event(pygame.MOUSEBUTTONDOWN, pos=box.center, button=1))
assert "hard" in p.charts
finally:
pygame.quit()
+101
View File
@@ -0,0 +1,101 @@
"""譜面檢查:未配置、區域違規、越界、同格顯示重疊、同一隻手同時按壓
用法(CLI):python validate.py chart.lanes.json
"""
import sys
from zones import COLS, ROWS, APPEAR_MS, EXPIRE_MS, cell_allowed
def _events(chart):
"""與遊戲 MusicPlayer 相同的展開方式:(hit_time, x, y, 結束時間, 音符 index)"""
ev = []
for i, n in enumerate(chart.notes):
if n.type == "slide" and n.path:
k = len(n.path)
iv = (n.end_time - n.t) / max(1, k - 1)
ev += [(n.t + iv * j, x, y, n.t + iv * j, i) for j, (x, y) in enumerate(n.path)]
elif n.pos is not None:
ev.append((n.t, n.pos[0], n.pos[1], n.end_time, i))
ev.sort()
return ev
def validate(chart):
"""回傳 [(音符 index, 訊息)],空串列表示沒有問題"""
issues = []
chart.sort()
for i, n in enumerate(chart.notes):
if not n.placed():
issues.append((i, "尚未配置座標"))
continue
cells = n.path if n.type == "slide" else [n.pos]
for x, y in cells:
if not (0 <= x < COLS and 0 <= y < ROWS):
issues.append((i, f"座標超出範圍 ({x},{y})"))
elif not cell_allowed(n.lane, n.type, x, y):
issues.append((i, f"({x},{y}) 不在 {n.lane} 軌可用的區域"))
if n.type in ("hold", "slide") and (n.end is None or n.end <= n.t):
issues.append((i, "結束時間必須晚於開始時間"))
if n.type == "slide" and n.path:
for (ax, ay), (bx, by) in zip(n.path, n.path[1:]):
if max(abs(ax - bx), abs(ay - by)) != 1:
issues.append((i, "slide 路徑必須走相鄰格"))
break
# 同格在顯示期間重疊
free_at = {}
for t, x, y, end, i in _events(chart):
if (x, y) in free_at and t - APPEAR_MS < free_at[(x, y)]:
issues.append((i, f"({x},{y}) 與前一顆音符顯示重疊"))
free_at[(x, y)] = end + EXPIRE_MS
# 同一隻手同時按壓(M 交給空著的手)
busy = {"L": [], "R": []} # 每隻手的 (start, end)
def overlaps(hand, s, e):
return any(not (e < bs or s > be) for bs, be in busy[hand])
for i, n in enumerate(chart.notes):
s, e = n.t, n.end_time
if n.lane in ("L", "R"):
if overlaps(n.lane, s, e):
issues.append((i, f"{'左' if n.lane == 'L' else '右'}手同時有兩個按壓"))
busy[n.lane].append((s, e))
else:
free = [h for h in ("L", "R") if not overlaps(h, s, e)]
if not free:
issues.append((i, "中間欄的音符沒有空著的手"))
else:
busy[free[0]].append((s, e))
issues.sort()
return issues
def _report(label, c):
found = validate(c)
print(f"{label}: {len(c.notes)} notes, {len(found)} issues")
for i, msg in found[:50]:
print(f" #{i} t={c.notes[i].t} {c.notes[i].lane} {c.notes[i].type}: {msg}")
return len(found)
if __name__ == "__main__":
# 用法:python validate.py 曲包.zip | 舊版.lanes.json ...
from chart import Chart
total = 0
for p in sys.argv[1:]:
if p.lower().endswith(".zip"):
from pack import open_pack, validate_pack
pack = open_pack(p)
for msg in validate_pack(pack):
print(f"{p}: {msg}")
total += 1
for d, c in pack.charts.items():
total += _report(f"{p} [{d}]", c)
pack.close()
else:
total += _report(p, Chart.load(p))
sys.exit(1 if total else 0)
+27
View File
@@ -0,0 +1,27 @@
"""手的區域規則與遊戲共用常數"""
COLS, ROWS = 5, 6
# 與遊戲一致:GridDisplay.AppearLead / NoteJudge.BadWindow
APPEAR_MS = 500
EXPIRE_MS = 200
LANES = ("L", "M", "R")
# tap / hold 可用欄
TAP_COLS = {"L": (0, 1), "M": (2,), "R": (3, 4)}
# slide 路徑可用欄:可進中間欄,但不跨到另一隻手的區域
SLIDE_COLS = {"L": (0, 1, 2), "M": (2,), "R": (2, 3, 4)}
def allowed_cols(lane, note_type):
return SLIDE_COLS[lane] if note_type == "slide" else TAP_COLS[lane]
def cell_allowed(lane, note_type, x, y):
return 0 <= y < ROWS and x in allowed_cols(lane, note_type)
def lane_of_column(x):
"""格子屬於哪一軌(用於預覽上色)"""
return "L" if x <= 1 else "R" if x >= 3 else "M"