1024 lines
40 KiB
Python
1024 lines
40 KiB
Python
"""Rhyculator Maker(譜面製作器)
|
||
|
||
第一階段(譜面分頁):L / M / R 三軌下落式時間軸做譜
|
||
第二階段(座標分頁):依手的區域把音符配置到 5x6 格子(自動 + 手動)
|
||
|
||
執行:python maker.py [chart.lanes.json]
|
||
按 H 顯示所有快捷鍵。
|
||
"""
|
||
import argparse
|
||
import os
|
||
import sys
|
||
|
||
import pygame
|
||
|
||
from chart import Chart, Note, slide_steps
|
||
from pack import DIFFS, SongPack, default_config, open_pack, save_pack, validate_pack
|
||
from placer import auto_place
|
||
from validate import validate
|
||
from zones import COLS, ROWS, APPEAR_MS, EXPIRE_MS, allowed_cols, cell_allowed, lane_of_column
|
||
|
||
W, H = 1280, 820
|
||
TOP = 44
|
||
JUDGE_Y = 720
|
||
WAVE_X, WAVE_W = 16, 60
|
||
LANE_X0, LANE_W = 90, 120
|
||
LANE_ORDER = ("L", "M", "R")
|
||
PANEL_X = 480
|
||
TAB_X = 420 # 分頁按鈕起點
|
||
DD_RECT = (8, 6, 132, 32) # 難度下拉按鈕
|
||
|
||
GRID_CELL, GRID_GAP = 86, 10
|
||
GRID_X = PANEL_X + 120
|
||
GRID_Y = TOP + 110
|
||
DIFF_BAR_Y = TOP + 14 # 右側「難度」勾選列
|
||
|
||
C_BG = (18, 18, 22)
|
||
C_PANEL = (28, 28, 34)
|
||
C_TEXT = (225, 225, 230)
|
||
C_DIM = (130, 130, 140)
|
||
C_LINE_BAR = (120, 120, 130)
|
||
C_LINE_BEAT = (70, 70, 80)
|
||
C_LINE_SUB = (40, 40, 48)
|
||
C_JUDGE = (255, 107, 204)
|
||
C_NOTE = {"tap": (110, 180, 255), "hold": (255, 107, 204), "slide": (255, 220, 90)}
|
||
C_ZONE = {"L": (34, 46, 70), "M": (52, 40, 62), "R": (70, 44, 40)}
|
||
C_ERR = (255, 70, 70)
|
||
C_SEL = (255, 255, 255)
|
||
|
||
HELP = [
|
||
"空白 播放/暫停(錄製時:Enter) 滾輪 捲動 Ctrl+滾輪 縮放",
|
||
"[ ] 格線細分 F1/F2/F3 速度 0.5/0.75/1x K 打擊音效開關",
|
||
"譜面分頁:左鍵點軌道=tap 拖曳=hold Shift+拖曳=slide 右鍵=刪除",
|
||
" 選取後:↑↓ 移動一格線 1/2/3 改到 L/M/R 軌 Delete 刪除",
|
||
" R 錄製模式:播放中按 F=L 空白=M J=R,停止時自動吸附格線",
|
||
"座標分頁:點音符選取 → 點格子指定座標(自動鎖定)",
|
||
" slide:點格子重畫路徑,Shift+點格子延伸路徑 U 解除鎖定",
|
||
" A 自動配置全部未鎖定 Shift+A 只配置未配置的",
|
||
"左上下拉選單切換難度 I 編輯曲包資訊(config)",
|
||
"B 設定 BPM O 設定第一拍時間 Tab 切換分頁",
|
||
"右上「難度」勾選要有哪些難度,點 Lv 修改難度數字",
|
||
"Ctrl+O 回到啟動視窗(開啟其他曲包 / 建立新曲包) Ctrl+I 匯入 osu 到目前難度",
|
||
"Ctrl+S 存檔(直接覆蓋原 zip) Ctrl+Shift+S 另存 Ctrl+E 匯出現行遊戲格式 sheet_N.json",
|
||
"Ctrl+Z 復原 H 顯示/隱藏說明",
|
||
]
|
||
|
||
|
||
def lane_x(lane):
|
||
return LANE_X0 + LANE_ORDER.index(lane) * LANE_W
|
||
|
||
|
||
def cell_rect(x, y):
|
||
# y=0 在最下面(與遊戲一致)
|
||
px = GRID_X + x * (GRID_CELL + GRID_GAP)
|
||
py = GRID_Y + (ROWS - 1 - y) * (GRID_CELL + GRID_GAP)
|
||
return pygame.Rect(px, py, GRID_CELL, GRID_CELL)
|
||
|
||
|
||
class Editor:
|
||
def __init__(self, chart_path=None, audio_enabled=True):
|
||
pygame.init()
|
||
self.screen = pygame.display.set_mode((W, H))
|
||
pygame.display.set_caption("Rhyculator Maker")
|
||
self.font = self._font(18)
|
||
self.font_small = self._font(14)
|
||
self.font_big = self._font(24)
|
||
self.clock = pygame.time.Clock()
|
||
|
||
self.audio_enabled = audio_enabled
|
||
self.pack = None # SongPack;None = 舊版 *.lanes.json 模式
|
||
self.diff = "normal" # 目前編輯的難度
|
||
self.chart = Chart()
|
||
self.chart_path = None # 舊版 lanes 檔路徑
|
||
self.player = None
|
||
self.wave = None
|
||
self.audio_loaded = None
|
||
self.time_ms = 0.0
|
||
self.zoom = 0.25 # px / ms
|
||
self.tab = "chart"
|
||
self.selected = None
|
||
self.undo_stacks = {} # 難度 → undo 堆疊(切換難度不會混在一起)
|
||
self.drag = None # (lane, start_t, shift)
|
||
self.recording = False
|
||
self.recorded = []
|
||
self.show_help = True
|
||
self.issues = []
|
||
self.message = ""
|
||
self.dirty = False
|
||
self.dropdown_open = False
|
||
|
||
if chart_path:
|
||
self.open_path(chart_path)
|
||
|
||
@property
|
||
def undo_stack(self):
|
||
return self.undo_stacks.setdefault(self.diff if self.pack else "_lanes", [])
|
||
|
||
# ---------- 基本 ----------
|
||
@staticmethod
|
||
def _font(size):
|
||
for name in ("microsoftjhenghei", "microsoftyahei", "notosanscjktc", "simhei", "pingfangtc"):
|
||
path = pygame.font.match_font(name)
|
||
if path:
|
||
return pygame.font.Font(path, size)
|
||
return pygame.font.Font(None, size + 6)
|
||
|
||
def say(self, msg):
|
||
self.message = msg
|
||
|
||
def push_undo(self):
|
||
self.undo_stack.append(self.chart.snapshot())
|
||
if len(self.undo_stack) > 200:
|
||
self.undo_stack.pop(0)
|
||
self.dirty = True
|
||
|
||
def undo(self):
|
||
if self.undo_stack:
|
||
self.chart.notes = self.undo_stack.pop()
|
||
self.selected = None
|
||
self.changed()
|
||
self.say("已復原")
|
||
|
||
def changed(self):
|
||
self.chart.sort()
|
||
self.issues = validate(self.chart)
|
||
if self.player:
|
||
self.player.set_hit_times([n.t for n in self.chart.notes])
|
||
|
||
def now(self):
|
||
if self.player and self.player.playing:
|
||
self.time_ms = self.player.position_ms()
|
||
return self.time_ms
|
||
|
||
def seek(self, ms):
|
||
length = self.player.length_ms if self.player else 10**7
|
||
self.time_ms = max(0.0, min(length, ms))
|
||
if self.player:
|
||
self.player.seek(self.time_ms)
|
||
|
||
# ---------- 對話框 ----------
|
||
def _dialog(self):
|
||
import tkinter
|
||
from tkinter import filedialog, simpledialog
|
||
root = tkinter.Tk()
|
||
root.withdraw()
|
||
root.attributes("-topmost", True)
|
||
return root, filedialog, simpledialog
|
||
|
||
def ask_file(self, title, types, save=False, initial=""):
|
||
root, fd, _ = self._dialog()
|
||
if save:
|
||
path = fd.asksaveasfilename(title=title, filetypes=types, initialfile=initial,
|
||
defaultextension=types[0][1].split()[0][1:])
|
||
else:
|
||
path = fd.askopenfilename(title=title, filetypes=types)
|
||
root.destroy()
|
||
return path or None
|
||
|
||
def dialog_number(self, title, prompt, initial, is_float):
|
||
root, _, sd = self._dialog()
|
||
v = (sd.askfloat if is_float else sd.askinteger)(title, prompt, initialvalue=initial, parent=root)
|
||
root.destroy()
|
||
return v
|
||
|
||
def form(self, title, fields, values):
|
||
"""簡易表單:fields = [(key, 標籤, 型別)];回傳 dict 或 None(取消)。空白的數字欄位回傳 None"""
|
||
import tkinter as tk
|
||
from tkinter import messagebox
|
||
root = tk.Tk()
|
||
root.title(title)
|
||
root.attributes("-topmost", True)
|
||
entries = {}
|
||
for i, (k, label, _) in enumerate(fields):
|
||
tk.Label(root, text=label).grid(row=i, column=0, sticky="e", padx=8, pady=3)
|
||
e = tk.Entry(root, width=44)
|
||
v = values.get(k)
|
||
e.insert(0, "" if v is None else str(v))
|
||
e.grid(row=i, column=1, padx=8, pady=3)
|
||
entries[k] = e
|
||
result = {}
|
||
done = {"ok": False}
|
||
|
||
def ok():
|
||
out = {}
|
||
for k, label, typ in fields:
|
||
s = entries[k].get().strip()
|
||
if s == "":
|
||
out[k] = "" if typ is str else None
|
||
continue
|
||
try:
|
||
out[k] = typ(s)
|
||
except ValueError:
|
||
messagebox.showerror(title, f"「{label}」格式不正確", parent=root)
|
||
return
|
||
result.update(out)
|
||
done["ok"] = True
|
||
root.quit()
|
||
|
||
row = len(fields)
|
||
tk.Button(root, text="確定", width=10, command=ok).grid(row=row, column=1, sticky="e", padx=8, pady=8)
|
||
tk.Button(root, text="取消", width=10, command=root.quit).grid(row=row, column=0, padx=8, pady=8)
|
||
root.protocol("WM_DELETE_WINDOW", root.quit)
|
||
root.mainloop()
|
||
root.destroy()
|
||
return result if done["ok"] else None
|
||
|
||
CONFIG_FIELDS = [
|
||
("id", "曲包 ID(小寫英數與 -)", str),
|
||
("name", "曲名", str),
|
||
("artist", "曲師", str),
|
||
("charter", "譜師", str),
|
||
("bpm", "BPM", float),
|
||
("beat_offset", "第一拍時間 (ms)", int),
|
||
("offset", "判定時間微調 (ms)", int),
|
||
("preview_start", "試聽開始 (ms)", int),
|
||
("preview_length", "試聽長度 (ms)", int),
|
||
("easy_num", "Easy 難度數字", int),
|
||
("normal_num", "Normal 難度數字", int),
|
||
("hard_num", "Hard 難度數字", int),
|
||
]
|
||
|
||
def edit_config(self, title="曲包資訊"):
|
||
if not self.pack:
|
||
self.say("目前不是曲包(Ctrl+S 可轉成曲包)")
|
||
return False
|
||
v = self.form(title, self.CONFIG_FIELDS, self.pack.config)
|
||
if v is None:
|
||
return False
|
||
for k, val in v.items():
|
||
if val is None:
|
||
self.pack.config.pop(k, None)
|
||
else:
|
||
self.pack.config[k] = val
|
||
self.pack.sync_timing()
|
||
self.dirty = True
|
||
self.say("已更新曲包資訊")
|
||
return True
|
||
|
||
# ---------- 音訊 ----------
|
||
def load_audio(self, path):
|
||
if not path or not os.path.exists(path):
|
||
self.say(f"找不到音檔:{path}")
|
||
return
|
||
if path == self.audio_loaded and self.player:
|
||
return
|
||
from audio import load_audio, waveform, Player
|
||
samples = load_audio(path)
|
||
self.wave = waveform(samples)
|
||
if self.player:
|
||
self.player.close()
|
||
self.player = Player(samples) if self.audio_enabled else None
|
||
if self.player is None:
|
||
# 無音訊模式仍需要長度
|
||
class _Len:
|
||
length_ms = len(samples) / 44.1
|
||
playing = False
|
||
def seek(self, ms): pass
|
||
def position_ms(self): return 0
|
||
def set_hit_times(self, t): pass
|
||
def close(self): pass
|
||
self.player = _Len()
|
||
self.audio_loaded = path
|
||
|
||
# ---------- 曲包 / 難度 ----------
|
||
def set_pack(self, pack, diff=None):
|
||
if self.pack and self.pack is not pack:
|
||
self.pack.close()
|
||
self.pack = pack
|
||
self.chart_path = None
|
||
self.undo_stacks.clear()
|
||
existing = [d for d in DIFFS if d in pack.charts]
|
||
self.switch_diff(diff or (existing[0] if existing else "normal"))
|
||
self.load_audio(pack.music)
|
||
self.dirty = False
|
||
|
||
def switch_diff(self, diff):
|
||
if not self.pack:
|
||
return
|
||
self.diff = diff
|
||
self.chart = self.pack.chart(diff, create=True)
|
||
self.selected = None
|
||
self.changed()
|
||
self.say(f"編輯 {diff}({len(self.chart.notes)} 顆)")
|
||
|
||
def title(self):
|
||
if self.pack:
|
||
return self.pack.config.get("name") or self.pack.config.get("id") or "(未命名曲包)"
|
||
return os.path.basename(self.chart_path) if self.chart_path else "(未存檔)"
|
||
|
||
# ---------- 開啟 / 存檔 ----------
|
||
def open_path(self, path):
|
||
if path.lower().endswith(".zip"):
|
||
self.set_pack(open_pack(path))
|
||
self.say(f"已開啟曲包 {os.path.basename(path)}:" +
|
||
"、".join(f"{d} {len(c.notes)} 顆" for d, c in self.pack.charts.items()))
|
||
else:
|
||
self.open_lanes(path)
|
||
|
||
def open_lanes(self, path):
|
||
"""舊版 *.lanes.json:可編輯,Ctrl+S 時轉成曲包"""
|
||
if self.pack:
|
||
self.pack.close()
|
||
self.pack = None
|
||
self.chart = Chart.load(path)
|
||
self.chart_path = path
|
||
a = self.chart.audio
|
||
if a and not os.path.isabs(a):
|
||
a = os.path.join(os.path.dirname(path), a)
|
||
self.chart.audio = a
|
||
self.load_audio(a)
|
||
self.undo_stacks.clear()
|
||
self.selected = None
|
||
self.dirty = False
|
||
self.changed()
|
||
self.say(f"已開啟舊版譜面 {os.path.basename(path)},Ctrl+S 會轉成曲包")
|
||
|
||
def dialog_open(self):
|
||
path = self.ask_file("開啟曲包", [("Rhyculator 曲包", "*.zip"), ("舊版譜面", "*.lanes.json")])
|
||
if path:
|
||
self.open_path(path)
|
||
|
||
def save(self, ask=False):
|
||
if not self.pack:
|
||
self.convert_to_pack()
|
||
return
|
||
self.pack.sync_timing()
|
||
errors = validate_pack(self.pack)
|
||
if errors:
|
||
self.say("無法存檔:" + ";".join(errors[:3]) + ("…" if len(errors) > 3 else "") + "(I 編輯曲包資訊)")
|
||
return
|
||
path = self.pack.path
|
||
if ask or not path:
|
||
path = self.ask_file("儲存曲包", [("Rhyculator 曲包", "*.zip")], save=True,
|
||
initial=f"{self.pack.config.get('id') or 'song'}.zip")
|
||
if not path:
|
||
return
|
||
try:
|
||
save_pack(self.pack, path)
|
||
except Exception as e:
|
||
self.say(f"存檔失敗:{e}")
|
||
return
|
||
self.dirty = False
|
||
self.say(f"已儲存 {os.path.basename(path)}")
|
||
|
||
def convert_to_pack(self):
|
||
"""舊版 lanes / 匯入的譜面 → 曲包:補上封面與 config"""
|
||
image = self.ask_file("選擇封面圖片(會裁成正方形)", [("Image", "*.png *.jpg *.jpeg *.webp")])
|
||
if not image:
|
||
return
|
||
pack = SongPack(default_config(bpm=self.chart.bpm, beat_offset=self.chart.offset))
|
||
pack.set_music(self.chart.audio)
|
||
pack.set_image(image)
|
||
pack.charts[self.diff] = self.chart
|
||
self.set_pack(pack, self.diff)
|
||
if self.edit_config("新曲包資訊"):
|
||
self.save(ask=True)
|
||
|
||
def update_caption(self):
|
||
where = self.pack.path if self.pack and self.pack.path else (self.chart_path or "")
|
||
pygame.display.set_caption(("* " if self.dirty else "") + "Rhyculator Maker" + (f" — {where}" if where else ""))
|
||
|
||
def confirm_discard(self):
|
||
"""有未存檔的修改時詢問;回傳 True 表示可以繼續(已存檔或放棄修改)"""
|
||
if not self.dirty:
|
||
return True
|
||
from tkinter import messagebox
|
||
root, _, _ = self._dialog()
|
||
ans = messagebox.askyesnocancel("尚未存檔", "有尚未存檔的修改,要先存檔嗎?", parent=root)
|
||
root.destroy()
|
||
if ans is None:
|
||
return False
|
||
if ans:
|
||
self.save()
|
||
return not self.dirty
|
||
return True
|
||
|
||
def reopen_launcher(self):
|
||
"""回到啟動視窗:開啟其他曲包或建立新曲包"""
|
||
if not self.confirm_discard():
|
||
return
|
||
from launcher import run_launcher
|
||
res = run_launcher()
|
||
if not res:
|
||
return
|
||
kind, value = res
|
||
if kind == "open":
|
||
self.open_path(value)
|
||
else:
|
||
self.set_pack(value)
|
||
self.say(f"已建立新曲包 {os.path.basename(value.path)}")
|
||
|
||
def dialog_import(self):
|
||
path = self.ask_file("匯入 osu 譜面", [("osu!", "*.osu")])
|
||
if not path:
|
||
return
|
||
from importers import import_osu
|
||
try:
|
||
chart = import_osu(path)
|
||
except Exception as e:
|
||
self.say(f"匯入失敗:{e}")
|
||
return
|
||
if self.pack:
|
||
# 匯入到目前難度,沿用曲包的 BPM / 第一拍
|
||
self.push_undo()
|
||
self.chart.notes = chart.notes
|
||
self.changed()
|
||
self.say(f"已匯入 {len(chart.notes)} 顆到 {self.diff}")
|
||
return
|
||
chart.audio = os.path.join(os.path.dirname(path), chart.audio)
|
||
self.pack = None
|
||
self.chart = chart
|
||
self.chart_path = None
|
||
self.load_audio(chart.audio)
|
||
self.undo_stacks.clear()
|
||
self.changed()
|
||
self.say(f"已匯入 {len(chart.notes)} 顆,Ctrl+S 會建立曲包")
|
||
|
||
def dialog_export(self):
|
||
unplaced = sum(1 for n in self.chart.notes if not n.placed())
|
||
if unplaced:
|
||
self.say(f"還有 {unplaced} 顆未配置座標,請先到座標分頁按 Shift+A")
|
||
return
|
||
path = self.ask_file("匯出遊戲譜面(現行格式)", [("Rhyculator sheet", "*.json")], save=True,
|
||
initial=f"sheet_{DIFFS.index(self.diff) + 1}.json" if self.pack else "sheet.json")
|
||
if path:
|
||
self.chart.export_sheet_file(path)
|
||
self.say(f"已匯出 {len(self.chart.notes)} 顆 → {os.path.basename(path)}"
|
||
+ (f"(注意:{len(self.issues)} 個問題)" if self.issues else ""))
|
||
|
||
def set_bpm(self, bpm):
|
||
self.chart.bpm = bpm
|
||
if self.pack:
|
||
self.pack.config["bpm"] = bpm
|
||
self.pack.sync_timing()
|
||
self.dirty = True
|
||
|
||
def set_beat_offset(self, ms):
|
||
self.chart.offset = ms
|
||
if self.pack:
|
||
self.pack.config["beat_offset"] = ms
|
||
self.pack.sync_timing()
|
||
self.dirty = True
|
||
|
||
# ---------- 座標換算 ----------
|
||
def y_of(self, t):
|
||
return JUDGE_Y - (t - self.now()) * self.zoom
|
||
|
||
def t_of(self, y):
|
||
return self.now() + (JUDGE_Y - y) / self.zoom
|
||
|
||
def lane_at(self, x):
|
||
for lane in LANE_ORDER:
|
||
if lane_x(lane) <= x < lane_x(lane) + LANE_W:
|
||
return lane
|
||
return None
|
||
|
||
def note_at_mouse(self, x, y):
|
||
lane = self.lane_at(x)
|
||
if not lane:
|
||
return None
|
||
return self.chart.note_at(lane, self.t_of(y), 10 / self.zoom)
|
||
|
||
# ---------- 編輯 ----------
|
||
def add_note(self, lane, t0, t1, shift):
|
||
t0, t1 = self.chart.snap(t0), self.chart.snap(t1)
|
||
if t1 < t0:
|
||
t0, t1 = t1, t0
|
||
self.push_undo()
|
||
if t1 - t0 >= self.chart.beat_ms / self.chart.divisor * 0.9:
|
||
note = Note(t0, lane, "slide" if shift else "hold", t1)
|
||
else:
|
||
note = Note(t0, lane, "tap")
|
||
self.chart.add(note)
|
||
self.selected = note
|
||
self.changed()
|
||
|
||
def delete(self, note):
|
||
if note in self.chart.notes:
|
||
self.push_undo()
|
||
self.chart.notes.remove(note)
|
||
if self.selected is note:
|
||
self.selected = None
|
||
self.changed()
|
||
|
||
def move_selected(self, steps):
|
||
n = self.selected
|
||
if not n:
|
||
return
|
||
self.push_undo()
|
||
d = self.chart.beat_ms / self.chart.divisor * steps
|
||
n.t = self.chart.snap(n.t + d)
|
||
if n.end is not None:
|
||
n.end = self.chart.snap(n.end + d)
|
||
self.changed()
|
||
|
||
def set_lane(self, lane):
|
||
n = self.selected
|
||
if not n or n.lane == lane:
|
||
return
|
||
self.push_undo()
|
||
n.lane = lane
|
||
# 原座標若不在新區域就清掉
|
||
cells = n.path if n.type == "slide" else ([n.pos] if n.pos else [])
|
||
if any(not cell_allowed(lane, n.type, x, y) for x, y in cells):
|
||
n.pos, n.path, n.locked = None, None, False
|
||
self.changed()
|
||
|
||
def click_cell(self, x, y, shift):
|
||
n = self.selected
|
||
if not n:
|
||
self.say("先在左邊時間軸點選一顆音符")
|
||
return
|
||
if not cell_allowed(n.lane, n.type, x, y):
|
||
self.say(f"({x},{y}) 不在 {n.lane} 軌可用的區域")
|
||
return
|
||
self.push_undo()
|
||
if n.type == "slide":
|
||
if shift and n.path:
|
||
n.path = n.path + [(x, y)]
|
||
else:
|
||
n.path = [(x, y)]
|
||
else:
|
||
n.pos = (x, y)
|
||
n.locked = True
|
||
self.changed()
|
||
|
||
def auto(self, only_unplaced):
|
||
self.push_undo()
|
||
auto_place(self.chart, seed=1, only_unplaced=only_unplaced)
|
||
self.changed()
|
||
self.say(f"自動配置完成,{len(self.issues)} 個問題")
|
||
|
||
def finish_recording(self):
|
||
if not self.recorded:
|
||
return
|
||
self.push_undo()
|
||
added = 0
|
||
for lane, t in self.recorded:
|
||
st = self.chart.snap(t)
|
||
if not any(n.lane == lane and n.t == st for n in self.chart.notes):
|
||
self.chart.notes.append(Note(st, lane, "tap"))
|
||
added += 1
|
||
self.recorded = []
|
||
self.changed()
|
||
self.say(f"錄製完成:新增 {added} 顆(已吸附到 1/{self.chart.divisor} 拍)")
|
||
|
||
def toggle_play(self):
|
||
if not self.player:
|
||
return
|
||
if self.player.playing:
|
||
self.player.toggle()
|
||
self.time_ms = self.player.position_ms()
|
||
if self.recording:
|
||
self.finish_recording()
|
||
else:
|
||
self.player.seek(self.time_ms)
|
||
self.player.toggle()
|
||
|
||
# ---------- 事件 ----------
|
||
def handle(self, e):
|
||
mods = pygame.key.get_mods()
|
||
ctrl = mods & pygame.KMOD_CTRL
|
||
shift = mods & pygame.KMOD_SHIFT
|
||
|
||
if e.type == pygame.MOUSEWHEEL:
|
||
if ctrl:
|
||
self.zoom = max(0.05, min(1.5, self.zoom * (1.15 if e.y > 0 else 1 / 1.15)))
|
||
else:
|
||
step = self.chart.beat_ms / self.chart.divisor
|
||
self.seek(self.chart.snap(self.now() + e.y * step * 2))
|
||
return
|
||
|
||
if e.type == pygame.KEYDOWN:
|
||
k = e.key
|
||
if ctrl:
|
||
if k == pygame.K_z: self.undo()
|
||
elif k == pygame.K_s: self.save(ask=bool(shift))
|
||
elif k == pygame.K_o: self.reopen_launcher()
|
||
elif k == pygame.K_i: self.dialog_import()
|
||
elif k == pygame.K_e: self.dialog_export()
|
||
return
|
||
if self.recording and self.player and self.player.playing and k in (pygame.K_f, pygame.K_j, pygame.K_SPACE):
|
||
lane = {pygame.K_f: "L", pygame.K_j: "R", pygame.K_SPACE: "M"}[k]
|
||
self.recorded.append((lane, self.player.position_ms()))
|
||
return
|
||
if k in (pygame.K_SPACE, pygame.K_RETURN): self.toggle_play()
|
||
elif k == pygame.K_TAB: self.tab = "pos" if self.tab == "chart" else "chart"
|
||
elif k == pygame.K_h: self.show_help = not self.show_help
|
||
elif k == pygame.K_i: self.edit_config()
|
||
elif k == pygame.K_LEFTBRACKET: self.chart.divisor = max(1, self.chart.divisor // 2)
|
||
elif k == pygame.K_RIGHTBRACKET: self.chart.divisor = min(16, self.chart.divisor * 2)
|
||
elif k in (pygame.K_F1, pygame.K_F2, pygame.K_F3) and self.player and hasattr(self.player, "speed"):
|
||
self.player.speed = {pygame.K_F1: 0.5, pygame.K_F2: 0.75, pygame.K_F3: 1.0}[k]
|
||
elif k == pygame.K_k and self.player and hasattr(self.player, "hitsound"):
|
||
self.player.hitsound = not self.player.hitsound
|
||
elif k == pygame.K_r:
|
||
self.recording = not self.recording
|
||
if not self.recording:
|
||
self.finish_recording()
|
||
self.say("錄製模式:播放後按 F / 空白 / J" if self.recording else "錄製模式關閉")
|
||
elif k == pygame.K_b:
|
||
v = self.dialog_number("BPM", "BPM:", self.chart.bpm, True)
|
||
if v: self.set_bpm(v)
|
||
elif k == pygame.K_o:
|
||
v = self.dialog_number("第一拍", "第一拍時間(ms):", self.chart.offset, False)
|
||
if v is not None: self.set_beat_offset(v)
|
||
elif k == pygame.K_UP: self.move_selected(1)
|
||
elif k == pygame.K_DOWN: self.move_selected(-1)
|
||
elif k in (pygame.K_1, pygame.K_2, pygame.K_3):
|
||
self.set_lane({pygame.K_1: "L", pygame.K_2: "M", pygame.K_3: "R"}[k])
|
||
elif k in (pygame.K_DELETE, pygame.K_BACKSPACE) and self.selected:
|
||
self.delete(self.selected)
|
||
elif k == pygame.K_a and self.tab == "pos":
|
||
self.auto(only_unplaced=bool(shift))
|
||
elif k == pygame.K_u and self.selected:
|
||
self.push_undo()
|
||
self.selected.locked = False
|
||
self.changed()
|
||
return
|
||
|
||
if e.type == pygame.MOUSEBUTTONDOWN and e.button in (1, 3):
|
||
x, y = e.pos
|
||
# 難度下拉(只列啟用的難度)
|
||
if self.pack and self.dropdown_open:
|
||
self.dropdown_open = False
|
||
for d, r in zip(self.pack.enabled(), self.dropdown_items()):
|
||
if r.collidepoint(x, y):
|
||
self.switch_diff(d)
|
||
return
|
||
if self.pack and pygame.Rect(DD_RECT).collidepoint(x, y):
|
||
self.dropdown_open = True
|
||
return
|
||
# 右側難度勾選列
|
||
if self.pack and e.button == 1:
|
||
for d, box, lv in self.diff_bar_rects():
|
||
if box.collidepoint(x, y):
|
||
self.toggle_diff(d)
|
||
return
|
||
if lv.collidepoint(x, y) and d in self.pack.charts:
|
||
self.edit_diff_num(d)
|
||
return
|
||
# 分頁按鈕
|
||
if y < TOP:
|
||
if TAB_X <= x < TAB_X + 96: self.tab = "chart"
|
||
elif TAB_X + 96 <= x < TAB_X + 192: self.tab = "pos"
|
||
return
|
||
if self.tab == "pos" and x >= PANEL_X:
|
||
for cx in range(COLS):
|
||
for cy in range(ROWS):
|
||
if cell_rect(cx, cy).collidepoint(x, y) and e.button == 1:
|
||
self.click_cell(cx, cy, bool(shift))
|
||
return
|
||
lane = self.lane_at(x)
|
||
if not lane:
|
||
return
|
||
hit = self.note_at_mouse(x, y)
|
||
if e.button == 3:
|
||
if hit and self.tab == "chart":
|
||
self.delete(hit)
|
||
return
|
||
if hit:
|
||
self.selected = hit
|
||
return
|
||
if self.tab == "chart":
|
||
self.drag = (lane, self.t_of(y), bool(shift))
|
||
return
|
||
|
||
if e.type == pygame.MOUSEBUTTONUP and e.button == 1 and self.drag:
|
||
lane, t0, sh = self.drag
|
||
self.drag = None
|
||
self.add_note(lane, t0, self.t_of(e.pos[1]), sh)
|
||
|
||
# ---------- 繪製 ----------
|
||
def text(self, s, pos, color=C_TEXT, font=None):
|
||
img = (font or self.font).render(s, True, color)
|
||
self.screen.blit(img, pos)
|
||
return img.get_width()
|
||
|
||
def dropdown_items(self):
|
||
return [pygame.Rect(DD_RECT[0], TOP + i * 36, 220, 34) for i in range(len(self.pack.enabled()))]
|
||
|
||
def diff_bar_rects(self):
|
||
"""[(難度, 勾選框, Lv 文字區)]"""
|
||
out = []
|
||
for i, d in enumerate(DIFFS):
|
||
x = PANEL_X + 80 + i * 200
|
||
out.append((d, pygame.Rect(x, DIFF_BAR_Y, 110, 28), pygame.Rect(x + 112, DIFF_BAR_Y, 70, 28)))
|
||
return out
|
||
|
||
def draw_diff_bar(self):
|
||
if not self.pack:
|
||
return
|
||
self.text("難度", (PANEL_X + 20, DIFF_BAR_Y + 3), C_DIM)
|
||
for d, box, lv in self.diff_bar_rects():
|
||
on = d in self.pack.charts
|
||
mark = pygame.Rect(box.x, box.y + 4, 20, 20)
|
||
pygame.draw.rect(self.screen, C_JUDGE if on else (90, 90, 100), mark, 0 if on else 2, border_radius=4)
|
||
if on:
|
||
pygame.draw.lines(self.screen, (30, 30, 36), False,
|
||
[(mark.x + 4, mark.y + 10), (mark.x + 8, mark.y + 15), (mark.x + 16, mark.y + 5)], 3)
|
||
self.text(d, (box.x + 28, box.y + 3), C_TEXT if on else C_DIM)
|
||
if on:
|
||
num = self.pack.config.get(f"{d}_num")
|
||
pygame.draw.rect(self.screen, (48, 48, 60), lv, border_radius=6)
|
||
self.text(f"Lv.{num}" if num else "Lv.?", (lv.x + 10, lv.y + 3), C_TEXT if num else C_ERR)
|
||
pygame.draw.line(self.screen, (60, 60, 70), (PANEL_X + 10, DIFF_BAR_Y + 38), (W - 10, DIFF_BAR_Y + 38))
|
||
|
||
def toggle_diff(self, d):
|
||
p = self.pack
|
||
if d in p.charts:
|
||
if len(p.enabled()) == 1:
|
||
self.say("至少要保留一個難度")
|
||
return
|
||
n = len(p.charts[d].notes)
|
||
if n and not self.confirm("停用難度", f"{d} 有 {n} 顆音符,停用後存檔就會刪除這個難度。確定要停用嗎?"):
|
||
return
|
||
p.disable(d)
|
||
self.undo_stacks.pop(d, None)
|
||
if self.diff == d:
|
||
self.switch_diff(p.enabled()[0])
|
||
self.dirty = True
|
||
self.say(f"已停用 {d}(存檔後生效)")
|
||
else:
|
||
num = self.dialog_number("難度數字", f"{d} 的難度數字(1~99):", None, False)
|
||
if num is None:
|
||
return
|
||
if not 1 <= num <= 99:
|
||
self.say("難度數字需為 1~99")
|
||
return
|
||
p.enable(d, num)
|
||
self.dirty = True
|
||
self.switch_diff(d)
|
||
|
||
def edit_diff_num(self, d):
|
||
num = self.dialog_number("難度數字", f"{d} 的難度數字(1~99):", self.pack.config.get(f"{d}_num"), False)
|
||
if num is not None and 1 <= num <= 99:
|
||
self.pack.config[f"{d}_num"] = num
|
||
self.dirty = True
|
||
|
||
def confirm(self, title, msg):
|
||
from tkinter import messagebox
|
||
root, _, _ = self._dialog()
|
||
ok = messagebox.askyesno(title, msg, parent=root)
|
||
root.destroy()
|
||
return ok
|
||
|
||
def draw_topbar(self):
|
||
pygame.draw.rect(self.screen, C_PANEL, (0, 0, W, TOP))
|
||
x = 12
|
||
if self.pack:
|
||
r = pygame.Rect(DD_RECT)
|
||
pygame.draw.rect(self.screen, (60, 60, 75), r, border_radius=6)
|
||
self.text(self.diff, (r.x + 12, r.y + 5))
|
||
self.text("▼", (r.right - 26, r.y + 5), C_DIM)
|
||
x = r.right + 10
|
||
title = ("* " if self.dirty else "") + self.title()
|
||
while self.font.size(title)[0] > TAB_X - x - 10 and len(title) > 4:
|
||
title = title[:-2] + "…"
|
||
self.text(title, (x, 11))
|
||
for i, (key, label) in enumerate((("chart", "譜面"), ("pos", "座標"))):
|
||
r = pygame.Rect(TAB_X + i * 96, 6, 88, 32)
|
||
pygame.draw.rect(self.screen, (70, 70, 85) if self.tab == key else (40, 40, 50), r, border_radius=6)
|
||
self.text(label, (r.x + 26, r.y + 5))
|
||
t = self.now()
|
||
info = (f"BPM {self.chart.bpm:g} 第一拍 {self.chart.offset}ms 1/{self.chart.divisor} "
|
||
f"{int(t // 60000)}:{(t % 60000) / 1000:06.3f}")
|
||
if self.player and hasattr(self.player, "speed"):
|
||
info += f" {self.player.speed:g}x"
|
||
self.text(info, (TAB_X + 200, 11))
|
||
if self.recording:
|
||
pygame.draw.circle(self.screen, C_ERR, (W - 90, 22), 8)
|
||
self.text("REC", (W - 76, 11), C_ERR)
|
||
|
||
def draw_dropdown(self):
|
||
if not (self.pack and self.dropdown_open):
|
||
return
|
||
for d, r in zip(self.pack.enabled(), self.dropdown_items()):
|
||
pygame.draw.rect(self.screen, (70, 70, 88) if d == self.diff else (48, 48, 60), r, border_radius=6)
|
||
num = self.pack.config.get(f"{d}_num")
|
||
self.text(f"{d} {len(self.pack.charts[d].notes)} 顆" + (f" Lv.{num}" if num else ""), (r.x + 12, r.y + 6))
|
||
|
||
def draw_timeline(self):
|
||
top, bottom = TOP, H - 30
|
||
t_bottom, t_top = self.t_of(bottom), self.t_of(top)
|
||
|
||
# 波形
|
||
if self.wave is not None:
|
||
for py in range(top, bottom, 2):
|
||
idx = int(self.t_of(py) / 10)
|
||
if 0 <= idx < len(self.wave):
|
||
w = float(self.wave[idx]) * WAVE_W
|
||
pygame.draw.line(self.screen, (60, 90, 110), (WAVE_X + WAVE_W / 2 - w / 2, py), (WAVE_X + WAVE_W / 2 + w / 2, py))
|
||
|
||
# 軌道
|
||
for lane in LANE_ORDER:
|
||
pygame.draw.rect(self.screen, C_ZONE[lane], (lane_x(lane), top, LANE_W - 4, bottom - top))
|
||
self.text({"L": "左手", "M": "中", "R": "右手"}[lane], (lane_x(lane) + 40, bottom + 4), C_DIM, self.font_small)
|
||
|
||
# 格線
|
||
x0, x1 = LANE_X0, LANE_X0 + 3 * LANE_W - 4
|
||
for t, beat, bar in self.chart.grid_lines(t_bottom, t_top):
|
||
y = self.y_of(t)
|
||
color = C_LINE_BAR if bar else C_LINE_BEAT if beat else C_LINE_SUB
|
||
pygame.draw.line(self.screen, color, (x0, y), (x1, y), 2 if bar else 1)
|
||
|
||
# 音符
|
||
problem = {self.chart.notes[i] for i, _ in self.issues}
|
||
for n in self.chart.notes:
|
||
if n.end_time < t_bottom - 100 or n.t > t_top + 100:
|
||
continue
|
||
lx = lane_x(n.lane) + 8
|
||
w = LANE_W - 20
|
||
y0, y1 = self.y_of(n.t), self.y_of(n.end_time)
|
||
col = C_NOTE[n.type]
|
||
if n.type != "tap":
|
||
pygame.draw.rect(self.screen, tuple(c // 2 for c in col), (lx + 20, y1, w - 40, y0 - y1), border_radius=6)
|
||
pygame.draw.rect(self.screen, col, (lx, y0 - 8, w, 16), border_radius=5)
|
||
if n in problem:
|
||
pygame.draw.rect(self.screen, C_ERR, (lx - 3, y0 - 11, w + 6, 22), 2, border_radius=6)
|
||
if n is self.selected:
|
||
pygame.draw.rect(self.screen, C_SEL, (lx - 4, min(y0, y1) - 12, w + 8, abs(y0 - y1) + 24), 2, border_radius=6)
|
||
if self.tab == "pos" and not n.placed():
|
||
self.text("?", (lx + w + 2, y0 - 9), C_ERR, self.font_small)
|
||
elif self.tab == "pos" and n.locked:
|
||
self.text("鎖", (lx + w + 1, y0 - 9), C_DIM, self.font_small)
|
||
|
||
# 錄製中的點
|
||
for lane, t in self.recorded:
|
||
pygame.draw.circle(self.screen, C_JUDGE, (lane_x(lane) + LANE_W // 2, int(self.y_of(t))), 6)
|
||
|
||
# 拖曳預覽
|
||
if self.drag:
|
||
lane, t0, sh = self.drag
|
||
my = pygame.mouse.get_pos()[1]
|
||
y0, y1 = self.y_of(self.chart.snap(t0)), self.y_of(self.chart.snap(self.t_of(my)))
|
||
pygame.draw.rect(self.screen, C_SEL, (lane_x(lane) + 8, min(y0, y1) - 8, LANE_W - 20, abs(y0 - y1) + 16), 1)
|
||
|
||
pygame.draw.line(self.screen, C_JUDGE, (WAVE_X, JUDGE_Y), (x1, JUDGE_Y), 3)
|
||
|
||
def grid_events(self):
|
||
"""與遊戲相同展開:(hit_time, x, y, note, end_time)"""
|
||
for n in self.chart.notes:
|
||
if n.type == "slide" and n.path:
|
||
iv = (n.end_time - n.t) / max(1, len(n.path) - 1)
|
||
for j, (x, y) in enumerate(n.path):
|
||
yield n.t + iv * j, x, y, n, n.t + iv * j
|
||
elif n.pos:
|
||
yield n.t, n.pos[0], n.pos[1], n, n.end_time
|
||
|
||
def draw_grid(self):
|
||
self.text("5x6 預覽(與遊戲相同的出現時間)", (GRID_X, GRID_Y - 32), C_DIM)
|
||
for x in range(COLS):
|
||
for y in range(ROWS):
|
||
r = cell_rect(x, y)
|
||
pygame.draw.rect(self.screen, C_ZONE[lane_of_column(x)], r, border_radius=12)
|
||
pygame.draw.rect(self.screen, (90, 90, 100), r, 3, border_radius=12)
|
||
|
||
now = self.now()
|
||
playing = self.player and getattr(self.player, "playing", False)
|
||
sel = self.selected
|
||
|
||
# 選取音符可用的區域
|
||
if sel:
|
||
for x in allowed_cols(sel.lane, sel.type):
|
||
for y in range(ROWS):
|
||
pygame.draw.rect(self.screen, (200, 200, 210), cell_rect(x, y), 1, border_radius=12)
|
||
|
||
for t, x, y, n, end in self.grid_events():
|
||
if not (t - APPEAR_MS <= now <= end + EXPIRE_MS):
|
||
continue
|
||
d = now - t
|
||
scale = 0.5 if d < -200 else min(1.5, 1 + d / 400)
|
||
if n.type == "hold" and t <= now <= end:
|
||
scale = 1.0
|
||
r = cell_rect(x, y)
|
||
size = int(GRID_CELL * scale)
|
||
rr = pygame.Rect(0, 0, size, size)
|
||
rr.center = r.center
|
||
pygame.draw.rect(self.screen, C_NOTE[n.type], rr, 6, border_radius=12)
|
||
|
||
# 選取的音符(暫停時一律顯示)
|
||
if sel and not playing:
|
||
cells = sel.path if sel.type == "slide" and sel.path else ([sel.pos] if sel.pos else [])
|
||
for i, (x, y) in enumerate(cells):
|
||
r = cell_rect(x, y)
|
||
pygame.draw.rect(self.screen, C_SEL, r.inflate(-14, -14), 4, border_radius=10)
|
||
if sel.type == "slide":
|
||
self.text(str(i + 1), (r.x + 8, r.y + 4), C_SEL, self.font_small)
|
||
for (ax, ay), (bx, by) in zip(cells, cells[1:]):
|
||
pygame.draw.line(self.screen, C_NOTE["slide"], cell_rect(ax, ay).center, cell_rect(bx, by).center, 3)
|
||
|
||
info_y = GRID_Y + ROWS * (GRID_CELL + GRID_GAP) + 6
|
||
if sel:
|
||
where = sel.path if sel.type == "slide" else sel.pos
|
||
self.text(f"選取:{sel.lane} 軌 {sel.type} t={sel.t}" + (f"~{sel.end}" if sel.end else "")
|
||
+ f" 座標 {where}" + (" (已鎖定,U 解除)" if sel.locked else ""), (PANEL_X + 20, info_y), C_TEXT, self.font_small)
|
||
|
||
def draw_panel(self):
|
||
x = PANEL_X + 20
|
||
y = TOP + 16
|
||
if self.pack:
|
||
self.draw_diff_bar()
|
||
y = DIFF_BAR_Y + 50
|
||
if self.tab == "pos":
|
||
self.draw_grid()
|
||
y = GRID_Y + ROWS * (GRID_CELL + GRID_GAP) + 34
|
||
elif self.show_help:
|
||
self.text("說明(H 隱藏)", (x, y), C_DIM)
|
||
y += 30
|
||
for line in HELP:
|
||
self.text(line, (x, y), C_TEXT, self.font_small)
|
||
y += 24
|
||
y += 16
|
||
|
||
placed = sum(1 for n in self.chart.notes if n.placed())
|
||
self.text(f"音符 {len(self.chart.notes)}(L {sum(n.lane == 'L' for n in self.chart.notes)} / "
|
||
f"M {sum(n.lane == 'M' for n in self.chart.notes)} / R {sum(n.lane == 'R' for n in self.chart.notes)})"
|
||
f" 已配置 {placed} 問題 {len(self.issues)}", (x, y), C_ERR if self.issues else C_TEXT)
|
||
y += 26
|
||
if self.tab == "chart":
|
||
for i, msg in self.issues[:8]:
|
||
n = self.chart.notes[i]
|
||
self.text(f"t={n.t} {n.lane} {n.type}:{msg}", (x, y), C_ERR, self.font_small)
|
||
y += 20
|
||
|
||
def draw(self):
|
||
self.screen.fill(C_BG)
|
||
self.draw_timeline()
|
||
pygame.draw.rect(self.screen, C_PANEL, (PANEL_X, TOP, W - PANEL_X, H - TOP))
|
||
self.draw_panel()
|
||
self.draw_topbar()
|
||
self.draw_dropdown()
|
||
pygame.draw.rect(self.screen, C_PANEL, (0, H - 26, W, 26))
|
||
self.text(self.message, (12, H - 24), C_TEXT, self.font_small)
|
||
|
||
def run(self):
|
||
running = True
|
||
while running:
|
||
for e in pygame.event.get():
|
||
if e.type == pygame.QUIT:
|
||
running = not self.confirm_discard()
|
||
else:
|
||
self.handle(e)
|
||
self.draw()
|
||
pygame.display.flip()
|
||
caption = (self.dirty, self.pack.path if self.pack else self.chart_path)
|
||
if caption != getattr(self, "_caption", None):
|
||
self._caption = caption
|
||
self.update_caption()
|
||
self.clock.tick(120)
|
||
if self.player:
|
||
self.player.close()
|
||
pygame.quit()
|
||
|
||
|
||
def main():
|
||
ap = argparse.ArgumentParser(description="Rhyculator Maker")
|
||
ap.add_argument("chart", nargs="?", help="曲包 .zip 或舊版 *.lanes.json")
|
||
ap.add_argument("--diff", choices=("easy", "normal", "hard"), help="開啟時的難度(截圖用)")
|
||
ap.add_argument("--dropdown", action="store_true", help="截圖時展開難度選單")
|
||
ap.add_argument("--no-audio", action="store_true", help="不開音訊裝置")
|
||
ap.add_argument("--screenshot", help="不開視窗,輸出一張截圖後結束(測試用)")
|
||
ap.add_argument("--tab", default="chart", choices=("chart", "pos"))
|
||
ap.add_argument("--time", type=float, default=0, help="截圖時的時間(ms)")
|
||
ap.add_argument("--select", type=int, default=-1, help="截圖時選取第幾顆音符")
|
||
a = ap.parse_args()
|
||
|
||
if a.screenshot:
|
||
os.environ["SDL_VIDEODRIVER"] = "dummy"
|
||
|
||
# 沒有指定檔案時先開啟動視窗(拖入 / 選擇 zip,或建立新曲包)
|
||
new_pack = None
|
||
if not a.chart and not a.screenshot:
|
||
from launcher import run_launcher
|
||
res = run_launcher()
|
||
if not res:
|
||
return
|
||
kind, value = res
|
||
if kind == "open":
|
||
a.chart = value
|
||
else:
|
||
new_pack = value
|
||
|
||
ed = Editor(a.chart, audio_enabled=not (a.no_audio or a.screenshot))
|
||
if new_pack:
|
||
ed.set_pack(new_pack)
|
||
ed.say(f"已建立新曲包 {os.path.basename(new_pack.path)},開始製譜吧")
|
||
if a.screenshot:
|
||
ed.tab = a.tab
|
||
if a.diff and ed.pack:
|
||
ed.switch_diff(a.diff)
|
||
ed.dropdown_open = a.dropdown
|
||
ed.seek(a.time)
|
||
if 0 <= a.select < len(ed.chart.notes):
|
||
ed.selected = ed.chart.notes[a.select]
|
||
ed.draw()
|
||
pygame.image.save(ed.screen, a.screenshot)
|
||
print("saved", a.screenshot)
|
||
return
|
||
ed.run()
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|