一个好 van 的 6k 定轨音游
听说计数器很火,我也整一个:
::::success[游戏主体代码]
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>phithm</title>
<style>
:root {
--bg: #00052b;
--panel-bg: #0a1030;
--text: #cccccc;
--text-bright: #ffffff;
--border: #1e2a4a;
--accent: #4466aa;
}
* { margin:0; padding:0; box-sizing:border-box; }
body {
background: var(--bg); font-family: 'Segoe UI','PingFang SC','Microsoft YaHei',sans-serif;
display: flex; justify-content: center; align-items: center; min-height: 100vh;
user-select: none; -webkit-user-select: none; color: var(--text);
}
.main-container { display: flex; gap: 24px; align-items: flex-start; padding: 20px; flex-wrap: wrap; justify-content: center; }
.game-wrapper { position: relative; border-radius: 16px; overflow: hidden; box-shadow: 0 0 60px rgba(0,0,0,0.7), 0 0 0 2px var(--border); background: #00052b; flex-shrink: 0; }
canvas { display: block; background: #00052b; }
.side-panel {
background: var(--panel-bg); border-radius: 16px; padding: 20px 22px; border: 1px solid var(--border);
width: 340px; display: flex; flex-direction: column; gap: 14px; max-height: 700px; overflow-y: auto; flex-shrink: 0;
}
.side-panel h2 { font-size:1.2em; color:#fff; text-align:center; letter-spacing:2px; font-weight:600; }
label { font-size:0.82em; color:#aaa; font-weight:500; }
input[type="text"], textarea {
width:100%; background:#121a30; border:1px solid var(--border); color:#ddd; padding:9px 11px;
border-radius:8px; font-size:0.85em; font-family: 'SF Mono','Consolas','Monaco','PingFang SC',monospace;
resize:vertical; transition:border-color 0.2s;
}
input[type="text"]:focus, textarea:focus { outline:none; border-color:var(--accent); box-shadow:0 0 12px rgba(68,102,170,0.25); }
textarea { min-height:140px; max-height:280px; line-height:1.5; }
input[type="file"] { display:none; }
.btn {
display:inline-block; padding:10px 18px; border-radius:8px; border:none; cursor:pointer;
font-size:0.9em; font-weight:600; letter-spacing:1px; transition:all 0.2s; text-align:center; color:#fff;
}
.btn-primary { background:var(--accent); }
.btn-primary:hover { background:#5577bb; box-shadow:0 0 20px rgba(68,102,170,0.4); }
.btn-start { background:#2a8a4a; font-size:1em; padding:13px; letter-spacing:2px; border-radius:10px; }
.btn-start:hover { background:#33aa55; box-shadow:0 0 25px rgba(42,138,74,0.5); }
.btn-start:disabled { background:#333; cursor:not-allowed; color:#666; box-shadow:none; }
.btn-sm { padding:7px 13px; font-size:0.78em; border-radius:6px; background:#1a2a4a; color:#ccc; border:1px solid #2a3a5a; }
.btn-sm:hover { background:#2a3a5a; border-color:#4a5a7a; }
.btn-row { display:flex; gap:8px; flex-wrap:wrap; }
.stat-row { display:flex; justify-content:space-between; align-items:center; padding:6px 0; border-bottom:1px solid #1a2a4a; font-size:0.85em; }
.stat-label { color:#999; }
.stat-value { color:#fff; font-weight:600; font-variant-numeric:tabular-nums; font-family:'SF Mono','Consolas','Monaco',monospace; }
.stat-value.perfect { color:#88ccff; } .stat-value.good { color:#66dd88; } .stat-value.bad { color:#ee6666; } .stat-value.miss { color:#777; } .stat-value.combo { color:#ffcc44; }
.divider { border:none; border-top:1px solid #1e2a4a; margin:4px 0; }
.info-tip { font-size:0.72em; color:#556688; text-align:center; line-height:1.4; }
.key-hints { display:flex; gap:6px; justify-content:center; }
.key-hint {
display:inline-block; width:36px; height:36px; line-height:36px; text-align:center; border-radius:8px;
font-weight:700; font-size:0.9em; color:#fff; background:#121a30; border:2px solid #2a3a5a;
}
.key-hint.k1 { border-color:#ff6666; box-shadow:0 0 10px rgba(255,100,100,0.35); }
.key-hint.k2 { border-color:#ff9966; box-shadow:0 0 10px rgba(255,150,100,0.35); }
.key-hint.k3 { border-color:#ffcc44; box-shadow:0 0 10px rgba(255,200,68,0.35); }
.key-hint.k4 { border-color:#55ee66; box-shadow:0 0 10px rgba(85,238,102,0.35); }
.key-hint.k5 { border-color:#5599ee; box-shadow:0 0 10px rgba(85,153,238,0.35); }
.key-hint.k6 { border-color:#cc66ee; box-shadow:0 0 10px rgba(204,102,238,0.35); }
.speed-display { display:inline-block; background:#121a30; padding:4px 10px; border-radius:5px; font-weight:600; color:#fff; font-size:0.85em; }
.mode-indicator { display:inline-block; padding:3px 10px; border-radius:5px; font-size:0.75em; font-weight:600; margin-left:6px; }
.mode-music { background:#2a5a3a; color:#aaffaa; } .mode-nomusic { background:#3a4a2a; color:#ffcc88; }
@media (max-width:768px) {
.main-container { flex-direction:column; align-items:center; gap:16px; padding:10px; }
.side-panel { width:100%; max-width:500px; max-height:none; }
canvas { width:100%; height:auto; }
}
</style>
</head>
<body>
<div class="main-container">
<div class="game-wrapper">
<canvas id="gameCanvas"></canvas>
</div>
<div class="side-panel">
<h2>phithm</h2>
<div class="key-hints">
<span class="key-hint k1">1</span><span class="key-hint k2">2</span><span class="key-hint k3">3</span>
<span class="key-hint k4">4</span><span class="key-hint k5">5</span><span class="key-hint k6">6</span>
</div>
<p class="info-tip">使用数字键 1-6 击打对应轨道</p>
<hr class="divider">
<label>upload audio<span id="audioModeLabel" class="mode-indicator mode-nomusic">none audio</span></label>
<div class="btn-row">
<button class="btn btn-sm" onclick="document.getElementById('audioFileInput').click()">chose audio</button>
<span id="audioFileName" style="font-size:0.78em;color:#888;">未选择</span>
</div>
<input type="file" id="audioFileInput" accept="audio/*">
<label>picture URL (optional) </label>
<input type="text" id="artworkUrl" placeholder="https://example.com/artwork.jpg">
<div class="btn-row">
<button class="btn btn-sm" id="btnLoadArtwork">load</button>
</div>
<label>edit / upload chart</label>
<textarea id="chartInput" spellcheck="false">[[1000,1],[1500,2],[2000,3],[2500,4],[3000,5],[3500,6],[4000,1],[4200,2],[4400,3],[4600,4],[4800,5],[5000,6],[5500,1],[5700,3],[5900,5],[6100,2],[6300,4],[6500,6],[7000,1],[7200,1],[7500,2],[7700,2],[8000,3],[8200,3],[8500,4],[8700,4],[9000,5],[9200,5],[9500,6],[9700,6],[10000,1],[10200,3],[10400,5],[10600,2],[10800,4],[11000,6],[11500,1],[11500,3],[11500,5],[12000,2],[12000,4],[12000,6]]</textarea>
<div class="btn-row">
<button class="btn btn-sm" onclick="document.getElementById('chartFileInput').click()">📂 上传铺面</button>
<span id="chartFileName" style="font-size:0.78em;color:#888;"></span>
</div>
<input type="file" id="chartFileInput" accept=".json,.txt">
<label>BPM <span id="bpmLabel" class="speed-display">120</span></label>
<input type="range" id="bpmSlider" min="60" max="300" value="120" step="1" style="width:100%;accent-color:#4466aa;">
<div class="btn-row">
<button class="btn btn-start" id="btnStart">start</button>
<button class="btn btn-sm" id="btnStop" style="display:none;">stop</button>
</div>
<hr class="divider">
<div class="stat-row"><span class="stat-label">point</span><span class="stat-value" id="scoreDisplay">0</span></div>
<div class="stat-row"><span class="stat-label">combo</span><span class="stat-value combo" id="comboDisplay">0</span></div>
<div class="stat-row"><span class="stat-label">max combo</span><span class="stat-value" id="maxComboDisplay">0</span></div>
<div class="stat-row"><span class="stat-label perfect">Perfect</span><span class="stat-value perfect" id="perfectCount">0</span></div>
<div class="stat-row"><span class="stat-label good">Good</span><span class="stat-value good" id="goodCount">0</span></div>
<div class="stat-row"><span class="stat-label bad">Bad</span><span class="stat-value bad" id="badCount">0</span></div>
<div class="stat-row"><span class="stat-label miss">Miss</span><span class="stat-value miss" id="missCount">0</span></div>
<div class="stat-row"><span class="stat-label">total notes</span><span class="stat-value" id="totalNotesDisplay">0</span></div>
</div>
</div>
<script>
(function() {
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const audioFileInput = document.getElementById('audioFileInput');
const audioFileName = document.getElementById('audioFileName');
const audioModeLabel = document.getElementById('audioModeLabel');
const artworkUrlInput = document.getElementById('artworkUrl');
const btnLoadArtwork = document.getElementById('btnLoadArtwork');
const chartInput = document.getElementById('chartInput');
const chartFileInput = document.getElementById('chartFileInput');
const chartFileName = document.getElementById('chartFileName');
const bpmSlider = document.getElementById('bpmSlider');
const bpmLabel = document.getElementById('bpmLabel');
const btnStart = document.getElementById('btnStart');
const btnStop = document.getElementById('btnStop');
const scoreDisplay = document.getElementById('scoreDisplay');
const comboDisplay = document.getElementById('comboDisplay');
const maxComboDisplay = document.getElementById('maxComboDisplay');
const perfectCountEl = document.getElementById('perfectCount');
const goodCountEl = document.getElementById('goodCount');
const badCountEl = document.getElementById('badCount');
const missCountEl = document.getElementById('missCount');
const totalNotesDisplay = document.getElementById('totalNotesDisplay');
const CANVAS_WIDTH = 600;
const CANVAS_HEIGHT = 700;
canvas.width = CANVAS_WIDTH;
canvas.height = CANVAS_HEIGHT;
const BACKGROUND_COLOR = '#00052b';
const TRACK_COUNT = 6;
const TRACK_WIDTH = 78;
const TRACK_GAP = 8;
const TOTAL_TRACKS_WIDTH = TRACK_COUNT * TRACK_WIDTH + (TRACK_COUNT - 1) * TRACK_GAP;
const TRACK_START_X = (CANVAS_WIDTH - TOTAL_TRACKS_WIDTH) / 2;
const JUDGMENT_LINE_Y = 575;
const NOTE_START_Y = 35;
const NOTE_RADIUS = TRACK_WIDTH * 0.25; // 缩小音符 (原0.33)
const trackCenterX = [];
for (let i = 0; i < TRACK_COUNT; i++) {
trackCenterX.push(TRACK_START_X + i * (TRACK_WIDTH + TRACK_GAP) + TRACK_WIDTH / 2);
}
const trackGlowColors = ['#ff5555','#ff9955','#ffcc44','#55ee55','#5599ee','#cc55ee'];
const trackGlowColorsBright = ['#ff8888','#ffbb88','#ffdd77','#88ff88','#88bbff','#dd88ff'];
let gameRunning = false;
let gameEnded = false;
let gameStartTime = 0;
let audioEnabled = false;
let audioElement = null;
let chartData = [];
let particles = [];
let keyPressFlash = new Array(TRACK_COUNT).fill(0);
let artworkImage = null;
let artworkLoaded = false;
let totalScore = 0;
let comboCount = 0;
let maxComboCount = 0;
let perfectCount = 0;
let goodCount = 0;
let badCount = 0;
let missCount = 0;
let totalNotesCount = 0;
let judgmentScoreAccum = 0;
let comboScoreBonus = 0;
let visibleTime = 2000;
let audioFileURL = null;
let endTimeoutId = null;
function updateVisibleTimeFromBPM() {
const bpm = parseInt(bpmSlider.value);
bpmLabel.textContent = bpm;
visibleTime = (60 / bpm) * 4 * 1000;
}
bpmSlider.addEventListener('input', updateVisibleTimeFromBPM);
updateVisibleTimeFromBPM();
audioFileInput.addEventListener('change', function(e) {
const file = e.target.files[0];
if (file) {
if (audioFileURL) URL.revokeObjectURL(audioFileURL);
audioFileURL = URL.createObjectURL(file);
audioFileName.textContent = file.name;
audioModeLabel.textContent = 'music mode';
audioModeLabel.className = 'mode-indicator mode-music';
if (audioElement) audioElement.src = audioFileURL;
} else {
if (audioFileURL) URL.revokeObjectURL(audioFileURL);
audioFileURL = null;
audioFileName.textContent = '未选择';
audioModeLabel.textContent = 'none audio';
audioModeLabel.className = 'mode-indicator mode-nomusic';
}
});
chartFileInput.addEventListener('change', function(e) {
const file = e.target.files[0];
if (!file) return;
chartFileName.textContent = file.name;
const reader = new FileReader();
reader.onload = function(ev) {
chartInput.value = ev.target.result;
loadChart();
};
reader.readAsText(file);
});
function createAudioElement() {
if (audioElement) { audioElement.pause(); audioElement.remove(); }
audioElement = new Audio();
audioElement.preload = 'auto';
if (audioFileURL) audioElement.src = audioFileURL;
audioElement.addEventListener('ended', () => {
if (gameRunning && audioEnabled) endGame();
});
}
function loadArtwork(url) {
if (!url || url.trim() === '') {
artworkLoaded = false; artworkImage = null; return;
}
const img = new Image();
img.onload = () => { artworkImage = img; artworkLoaded = true; };
img.onerror = () => { artworkImage = null; artworkLoaded = false; alert('曲绘加载失败'); };
img.src = url.trim();
}
btnLoadArtwork.addEventListener('click', () => loadArtwork(artworkUrlInput.value.trim()));
artworkUrlInput.addEventListener('change', () => loadArtwork(artworkUrlInput.value));
artworkUrlInput.addEventListener('blur', () => loadArtwork(artworkUrlInput.value));
function parseChart(inputStr) {
try {
const parsed = JSON.parse(inputStr.trim());
if (!Array.isArray(parsed)) return null;
const result = [];
for (const entry of parsed) {
if (!Array.isArray(entry) || entry.length < 2) continue;
const time = parseInt(entry[0]), track = parseInt(entry[1]);
if (isNaN(time) || isNaN(track) || track < 1 || track > 6 || time < 0) continue;
result.push({ time, track: track - 1 });
}
result.sort((a,b) => a.time - b.time);
return result;
} catch (e) { return null; }
}
function loadChart() {
const parsed = parseChart(chartInput.value);
if (!parsed || parsed.length === 0) { alert('铺面格式错误!'); return false; }
chartData = parsed.map(n => ({ time:n.time, track:n.track, hit:false, missed:false, missTriggered:false }));
totalNotesCount = chartData.length;
totalNotesDisplay.textContent = totalNotesCount;
return true;
}
function spawnParticles(x, y, color, count = 18) {
for (let i = 0; i < count; i++) {
const angle = Math.random() * Math.PI * 2;
const speed = 1.5 + Math.random() * 6;
particles.push({
x, y, vx: Math.cos(angle)*speed, vy: Math.sin(angle)*speed - 2,
life: 300 + Math.random()*400, maxLife: 400, color, size: 1.5 + Math.random()*3.5
});
}
}
function updateParticles(dt) {
for (let i = particles.length-1; i >=0; i--) {
const p = particles[i];
p.x += p.vx; p.y += p.vy; p.vy += 0.02;
p.life -= dt;
if (p.life <= 0) particles.splice(i,1);
}
}
function drawParticles(ctx) {
for (const p of particles) {
const alpha = Math.max(0, p.life / p.maxLife);
let rgba = p.color;
if (p.color.startsWith('#')) {
const r = parseInt(p.color.slice(1,3),16), g = parseInt(p.color.slice(3,5),16), b = parseInt(p.color.slice(5,7),16);
rgba = `rgba(${r},${g},${b},${alpha})`;
} else if (!p.color.startsWith('rgba')) rgba = `rgba(255,255,255,${alpha})`;
ctx.fillStyle = rgba;
ctx.beginPath(); ctx.arc(p.x, p.y, p.size * alpha, 0, Math.PI*2); ctx.fill();
ctx.fillStyle = rgba.replace(/[\d.]+\)$/, `${alpha*0.5})`);
ctx.beginPath(); ctx.arc(p.x, p.y, p.size*2.5*alpha, 0, Math.PI*2); ctx.fill();
}
}
function getGameTime() {
if (!gameRunning) return 0;
if (audioEnabled && audioElement && audioElement.duration) {
return audioElement.currentTime * 1000;
} else {
return performance.now() - gameStartTime;
}
}
function getNoteY(noteTime, gameTime) {
const timeUntil = noteTime - gameTime;
const fraction = timeUntil / visibleTime;
return JUDGMENT_LINE_Y - fraction * (JUDGMENT_LINE_Y - NOTE_START_Y);
}
function findNearestNote(trackIndex, gameTime) {
let best = null, bestDist = Infinity;
for (const note of chartData) {
if (note.track !== trackIndex || note.hit || note.missTriggered) continue;
const diff = gameTime - note.time;
if (diff < -250 || diff > 120) continue;
const abs = Math.abs(diff);
if (abs < bestDist) { bestDist = abs; best = note; }
}
return best;
}
function judgeNote(note, gameTime) {
const diff = gameTime - note.time;
const abs = Math.abs(diff);
if (abs <= 80) return 'perfect';
if (abs <= 120) return 'good';
if (diff < -120 && diff >= -250) return 'bad';
return null;
}
function processHit(trackIndex) {
if (!gameRunning) return;
const gameTime = getGameTime();
const note = findNearestNote(trackIndex, gameTime);
if (!note) return;
const judgment = judgeNote(note, gameTime);
if (!judgment) return;
note.hit = true; note.missTriggered = true; note.judgment = judgment;
const cx = trackCenterX[trackIndex];
if (judgment === 'perfect') {
perfectCount++; comboCount++;
if (comboCount > maxComboCount) maxComboCount = comboCount;
spawnParticles(cx, JUDGMENT_LINE_Y, 'rgb(130,210,255)', 22);
keyPressFlash[trackIndex] = 180;
} else if (judgment === 'good') {
goodCount++; comboCount++;
if (comboCount > maxComboCount) maxComboCount = comboCount;
spawnParticles(cx, JUDGMENT_LINE_Y, 'rgb(100,220,120)', 16);
keyPressFlash[trackIndex] = 140;
} else if (judgment === 'bad') {
badCount++; comboCount = 0;
spawnParticles(cx, JUDGMENT_LINE_Y, 'rgb(240,90,90)', 14);
keyPressFlash[trackIndex] = 100;
}
updateScore(); updateUI();
checkAllNotesProcessed();
}
function checkMisses(gameTime) {
for (const note of chartData) {
if (note.hit || note.missTriggered) continue;
if (gameTime > note.time + 120) {
note.missTriggered = true; note.missed = true; note.judgment = 'miss';
missCount++; comboCount = 0;
}
}
}
function updateScore() {
const totalN = totalNotesCount || 1;
const base = 900000 / totalN;
judgmentScoreAccum = perfectCount * base + goodCount * base * 0.8;
comboScoreBonus = 100000 * (maxComboCount / totalN);
totalScore = Math.round(judgmentScoreAccum + comboScoreBonus);
if (totalScore > 1000000) totalScore = 1000000;
}
function updateUI() {
scoreDisplay.textContent = totalScore.toLocaleString();
comboDisplay.textContent = comboCount;
maxComboDisplay.textContent = maxComboCount;
perfectCountEl.textContent = perfectCount;
goodCountEl.textContent = goodCount;
badCountEl.textContent = badCount;
missCountEl.textContent = missCount;
totalNotesDisplay.textContent = totalNotesCount;
}
function clearEndTimeout() {
if (endTimeoutId) { clearTimeout(endTimeoutId); endTimeoutId = null; }
}
function checkAllNotesProcessed() {
if (!gameRunning || audioEnabled || gameEnded) return;
const allProcessed = chartData.every(n => n.missTriggered);
if (allProcessed && !endTimeoutId) {
endTimeoutId = setTimeout(() => { endGame(); }, 3000);
}
}
function resetGame() {
gameRunning = false; gameEnded = false; audioEnabled = false; gameStartTime = 0;
comboCount = 0; maxComboCount = 0; perfectCount = 0; goodCount = 0; badCount = 0; missCount = 0;
totalScore = 0; judgmentScoreAccum = 0; comboScoreBonus = 0;
particles = []; keyPressFlash = new Array(TRACK_COUNT).fill(0);
chartData = []; totalNotesCount = 0;
clearEndTimeout();
if (audioElement) { audioElement.pause(); audioElement.currentTime = 0; }
updateUI();
btnStart.style.display = ''; btnStop.style.display = 'none'; btnStart.disabled = false;
}
function startGame() {
if (!loadChart()) return;
if (totalNotesCount === 0) { alert('铺面为空!'); return; }
gameEnded = false;
comboCount = 0; maxComboCount = 0; perfectCount = 0; goodCount = 0; badCount = 0; missCount = 0;
totalScore = 0; judgmentScoreAccum = 0; comboScoreBonus = 0;
particles = []; keyPressFlash = new Array(TRACK_COUNT).fill(0);
clearEndTimeout();
for (const note of chartData) {
note.hit = false; note.missed = false; note.missTriggered = false; note.judgment = null;
}
updateUI();
if (audioElement && audioFileURL) {
audioEnabled = true;
audioElement.currentTime = 0;
audioElement.play().then(() => {
gameRunning = true; gameStartTime = performance.now();
btnStart.style.display = 'none'; btnStop.style.display = '';
}).catch(err => alert('音频播放失败:' + err.message));
} else {
audioEnabled = false;
gameRunning = true; gameStartTime = performance.now();
btnStart.style.display = 'none'; btnStop.style.display = '';
}
}
function endGame() {
if (!gameRunning || gameEnded) return;
gameRunning = false;
clearEndTimeout();
if (audioElement && audioEnabled) audioElement.pause();
for (const note of chartData) {
if (!note.hit && !note.missTriggered) {
note.missTriggered = true; note.missed = true; note.judgment = 'miss';
missCount++;
}
}
comboCount = 0;
updateScore(); updateUI();
gameEnded = true;
btnStart.style.display = ''; btnStop.style.display = 'none'; btnStart.disabled = false;
}
function stopGame() {
if (audioElement && audioEnabled) { audioElement.pause(); audioElement.currentTime = 0; }
resetGame();
}
function drawEndScreen(ctx) {
ctx.fillStyle = 'rgba(0, 5, 30, 0.85)';
ctx.fillRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
const p = totalScore;
let gradeText = '', gradeColor = '#ffffff';
if (p === 1000000) {
gradeText = 'φ'; gradeColor = '#ffd700';
} else if (maxComboCount === totalNotesCount && totalNotesCount > 0) {
gradeText = 'FC'; gradeColor = '#44aaff';
} else if (p >= 950000) {
gradeText = 'V';
} else if (p >= 920000) {
gradeText = 'S';
} else if (p >= 870000) {
gradeText = 'A';
} else if (p >= 820000) {
gradeText = 'B';
} else if (p >= 800000) {
gradeText = 'C';
} else {
gradeText = 'F';
}
ctx.textAlign = 'center';
ctx.font = 'bold 72px "PingFang SC","Microsoft YaHei",sans-serif';
ctx.fillStyle = gradeColor;
ctx.shadowColor = gradeColor; ctx.shadowBlur = 20;
ctx.fillText(gradeText, CANVAS_WIDTH/2, 260);
ctx.shadowBlur = 0;
ctx.font = 'bold 28px "PingFang SC","Microsoft YaHei",sans-serif';
ctx.fillStyle = '#ffffff';
ctx.fillText(totalScore.toLocaleString(), CANVAS_WIDTH/2, 340);
ctx.font = '16px "PingFang SC","Microsoft YaHei",sans-serif';
ctx.fillText(`Perfect: ${perfectCount} Good: ${goodCount} Bad: ${badCount} Miss: ${missCount}`, CANVAS_WIDTH/2, 410);
ctx.fillText(`Max Combo: ${maxComboCount} / ${totalNotesCount}`, CANVAS_WIDTH/2, 450);
ctx.font = '14px "PingFang SC","Microsoft YaHei",sans-serif';
ctx.fillStyle = '#888888';
ctx.fillText('点击 "start" 开始新游戏', CANVAS_WIDTH/2, 520);
}
function drawTopStats(ctx) {
ctx.save();
ctx.font = 'bold 18px "PingFang SC","Microsoft YaHei",sans-serif';
ctx.fillStyle = '#ffffff';
ctx.textAlign = 'center';
ctx.textBaseline = 'top';
ctx.fillText('phithm', CANVAS_WIDTH/2, 4);
ctx.font = 'bold 12px "PingFang SC","Microsoft YaHei",sans-serif';
ctx.textAlign = 'left';
ctx.fillText(`分数: ${totalScore.toLocaleString()}`, 12, 26);
ctx.fillText(`连击: ${comboCount} | 最大: ${maxComboCount}`, 12, 42);
ctx.textAlign = 'right';
ctx.fillText(`Perfect: ${perfectCount} Good: ${goodCount}`, CANVAS_WIDTH - 12, 26);
ctx.fillText(`Bad: ${badCount} Miss: ${missCount}`, CANVAS_WIDTH - 12, 42);
ctx.restore();
}
function drawTrackBackground(ctx) {
if (artworkLoaded && artworkImage) {
ctx.save(); ctx.globalAlpha = 0.28;
ctx.beginPath(); ctx.rect(0, NOTE_START_Y-10, CANVAS_WIDTH, JUDGMENT_LINE_Y-NOTE_START_Y+20); ctx.clip();
const iw = artworkImage.width, ih = artworkImage.height;
const areaW = CANVAS_WIDTH, areaH = JUDGMENT_LINE_Y-NOTE_START_Y+20;
const imgRatio = iw/ih, areaRatio = areaW/areaH;
let dw, dh, dx, dy;
if (imgRatio > areaRatio) { dh = areaH; dw = dh*imgRatio; dx = -(dw-areaW)/2; dy = NOTE_START_Y-10; }
else { dw = areaW; dh = dw/imgRatio; dx = 0; dy = NOTE_START_Y-10 + (areaH-dh)/2; }
ctx.drawImage(artworkImage, dx, dy, dw, dh);
ctx.restore();
}
for (let i=0; i<TRACK_COUNT; i++) {
const x = TRACK_START_X + i*(TRACK_WIDTH+TRACK_GAP);
ctx.fillStyle = 'rgba(0,5,30,0.25)';
ctx.fillRect(x, NOTE_START_Y-10, TRACK_WIDTH, JUDGMENT_LINE_Y-NOTE_START_Y+15);
ctx.strokeStyle = 'rgba(80,100,140,0.2)';
ctx.lineWidth=1;
ctx.strokeRect(x, NOTE_START_Y-10, TRACK_WIDTH, JUDGMENT_LINE_Y-NOTE_START_Y+15);
}
ctx.strokeStyle = 'rgba(255,255,255,0.25)';
ctx.lineWidth = 1.5;
ctx.setLineDash([4, 8]);
for (let i=0; i<TRACK_COUNT; i++) {
const cx = trackCenterX[i];
ctx.beginPath();
ctx.moveTo(cx, NOTE_START_Y - 5);
ctx.lineTo(cx, JUDGMENT_LINE_Y);
ctx.stroke();
}
ctx.setLineDash([]);
// 缩小判定圈 (原8/4改为6/3)
for (let i=0; i<TRACK_COUNT; i++) {
const cx = trackCenterX[i];
ctx.beginPath();
ctx.arc(cx, JUDGMENT_LINE_Y, 6, 0, Math.PI*2);
ctx.strokeStyle = '#ffffff';
ctx.lineWidth = 2;
ctx.stroke();
ctx.beginPath();
ctx.arc(cx, JUDGMENT_LINE_Y, 3, 0, Math.PI*2);
ctx.fillStyle = 'rgba(255,255,255,0.3)';
ctx.fill();
}
for (let i=0; i<TRACK_COUNT; i++) {
if (keyPressFlash[i] > 0) {
const alpha = keyPressFlash[i]/180;
const grad = ctx.createRadialGradient(trackCenterX[i], JUDGMENT_LINE_Y, 2, trackCenterX[i], JUDGMENT_LINE_Y, 55);
grad.addColorStop(0, trackGlowColorsBright[i].replace(')',`,${alpha})`).replace('rgb','rgba'));
grad.addColorStop(1, 'rgba(0,0,0,0)');
ctx.fillStyle = grad;
ctx.fillRect(trackCenterX[i]-60, JUDGMENT_LINE_Y-60, 120, 120);
}
}
}
function drawNote(ctx, note, gameTime) {
const y = getNoteY(note.time, gameTime);
if (y < -60 || y > CANVAS_HEIGHT+60) return;
const cx = trackCenterX[note.track];
let alpha = 1, glowColor = trackGlowColors[note.track], fillColor = '#ffffff', glowIntensity = 12; // 稍微减小发光强度
if (note.missed && note.missTriggered && !note.hit) {
alpha = 0.25; fillColor = '#555555'; glowIntensity = 4; glowColor = '#444444';
}
if (alpha <= 0) return;
ctx.save(); ctx.globalAlpha = alpha;
ctx.shadowColor = glowColor; ctx.shadowBlur = glowIntensity;
ctx.fillStyle = fillColor;
ctx.beginPath(); ctx.arc(cx, y, NOTE_RADIUS, 0, Math.PI*2); ctx.fill();
ctx.shadowBlur = 0;
const grad = ctx.createRadialGradient(cx-NOTE_RADIUS*0.3, y-NOTE_RADIUS*0.3, NOTE_RADIUS*0.1, cx, y, NOTE_RADIUS);
grad.addColorStop(0, 'rgba(255,255,255,0.8)'); grad.addColorStop(0.7, 'rgba(255,255,255,0.2)'); grad.addColorStop(1, 'rgba(255,255,255,0.1)');
ctx.fillStyle = grad;
ctx.beginPath(); ctx.arc(cx, y, NOTE_RADIUS, 0, Math.PI*2); ctx.fill();
ctx.restore();
}
function drawJudgmentText(ctx, note, gameTime) {
if (!note.hit || !note.judgment || note.judgment==='miss') return;
const y = getNoteY(note.time, gameTime);
const cx = trackCenterX[note.track];
const jY = Math.min(y+20, JUDGMENT_LINE_Y+30);
const elapsed = gameTime - note.time;
const fade = Math.max(0, 1 - elapsed/600);
if (fade<=0) return;
ctx.save(); ctx.globalAlpha = fade;
ctx.font = 'bold 14px "PingFang SC","Microsoft YaHei",sans-serif'; ctx.textAlign='center';
let text, color;
if (note.judgment==='perfect') { text='PERFECT'; color='#88ccff'; }
else if (note.judgment==='good') { text='GOOD'; color='#66dd88'; }
else if (note.judgment==='bad') { text='BAD'; color='#ee6666'; }
else { ctx.restore(); return; }
ctx.fillStyle = color; ctx.shadowColor=color; ctx.shadowBlur=10;
ctx.fillText(text, cx, jY);
ctx.shadowBlur=0; ctx.restore();
}
function drawTrackLabels(ctx) {
const ly = JUDGMENT_LINE_Y+30;
ctx.font = 'bold 14px "PingFang SC","Microsoft YaHei",sans-serif'; ctx.textAlign='center';
for (let i=0; i<TRACK_COUNT; i++) {
ctx.fillStyle = trackGlowColors[i]; ctx.globalAlpha=0.8;
ctx.fillText(i+1, trackCenterX[i], ly);
}
ctx.globalAlpha=1;
ctx.font = '10px "PingFang SC","Microsoft YaHei",sans-serif'; ctx.fillStyle='#667788';
ctx.fillText('按键', CANVAS_WIDTH/2, JUDGMENT_LINE_Y+52);
}
function render(currentGameTime) {
ctx.clearRect(0,0,CANVAS_WIDTH,CANVAS_HEIGHT);
ctx.fillStyle = BACKGROUND_COLOR;
ctx.fillRect(0,0,CANVAS_WIDTH,CANVAS_HEIGHT);
if (gameEnded) {
drawEndScreen(ctx);
return;
}
drawTrackBackground(ctx);
for (const note of chartData) {
if (note.hit && note.judgment!=='miss') continue;
if ((note.missTriggered && note.missed && !note.hit) || (!note.hit && !note.missTriggered))
drawNote(ctx, note, currentGameTime);
}
for (const note of chartData)
if (note.hit && note.judgment && note.judgment!=='miss') drawJudgmentText(ctx, note, currentGameTime);
drawParticles(ctx);
drawTrackLabels(ctx);
drawTopStats(ctx);
if (!gameRunning && totalNotesCount===0) {
ctx.fillStyle='rgba(255,255,255,0.5)'; ctx.font='18px "PingFang SC","Microsoft YaHei",sans-serif'; ctx.textAlign='center';
ctx.fillText('上传音乐或使用无音乐模式,加载铺面后开始', CANVAS_WIDTH/2, CANVAS_HEIGHT/2);
}
}
let lastFrameTime = performance.now();
function gameLoop(ts) {
const dt = ts - lastFrameTime; lastFrameTime = ts;
if (gameRunning) {
const gameTime = getGameTime();
checkMisses(gameTime);
updateParticles(dt);
for (let i=0; i<TRACK_COUNT; i++) if (keyPressFlash[i]>0) keyPressFlash[i] = Math.max(0, keyPressFlash[i]-dt);
if (!audioEnabled) checkAllNotesProcessed();
render(gameTime);
} else {
updateParticles(dt);
for (let i=0; i<TRACK_COUNT; i++) if (keyPressFlash[i]>0) keyPressFlash[i] = Math.max(0, keyPressFlash[i]-dt);
render(0);
}
requestAnimationFrame(gameLoop);
}
document.addEventListener('keydown', function(e) {
if (!gameRunning) return;
let track = -1;
if (e.key==='1') track=0; else if (e.key==='2') track=1; else if (e.key==='3') track=2;
else if (e.key==='4') track=3; else if (e.key==='5') track=4; else if (e.key==='6') track=5;
else return;
e.preventDefault();
processHit(track);
});
btnStart.addEventListener('click', startGame);
btnStop.addEventListener('click', stopGame);
function init() {
createAudioElement();
loadChart(); updateUI();
if (artworkUrlInput.value.trim()) loadArtwork(artworkUrlInput.value.trim());
updateVisibleTimeFromBPM();
lastFrameTime = performance.now();
requestAnimationFrame(gameLoop);
audioModeLabel.textContent = audioFileURL ? 'music mode' : 'none audio';
audioModeLabel.className = 'mode-indicator ' + (audioFileURL ? 'mode-music' : 'mode-nomusic');
}
init();
window.addEventListener('beforeunload', () => {
clearEndTimeout();
if (audioElement) { audioElement.pause(); audioElement.remove(); }
if (audioFileURL) URL.revokeObjectURL(audioFileURL);
});
})();
</script>
</body>
</html>
::::
另外,为了方便造谱,我还拿 AI 写了个
::::success[造谱代码]
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>铺面生成工具 - 音游制谱器</title>
<style>
:root {
--bg: #0a0a0f;
--surface: #141420;
--surface2: #1a1a2e;
--border: #2a2a40;
--text: #e0e0e8;
--text2: #a0a0b8;
--accent: #6c5ce7;
--accent2: #a29bfe;
--danger: #e74c3c;
--success: #2ecc71;
--warning: #f39c12;
--key1: #ff4757;
--key2: #ff6b35;
--key3: #ffc048;
--key4: #2ed573;
--key5: #1e90ff;
--key6: #a855f7;
--glow-1: rgba(255, 71, 87, 0.5);
--glow-2: rgba(255, 107, 53, 0.5);
--glow-3: rgba(255, 192, 72, 0.5);
--glow-4: rgba(46, 213, 115, 0.5);
--glow-5: rgba(30, 144, 255, 0.5);
--glow-6: rgba(168, 85, 247, 0.5);
--radius: 12px;
--radius-sm: 8px;
--transition: 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', 'Noto Sans SC', sans-serif;
background: var(--bg);
color: var(--text);
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
padding: 20px;
background-image:
radial-gradient(ellipse at 50% 0%, rgba(108, 92, 231, 0.08) 0%, transparent 60%),
radial-gradient(ellipse at 80% 100%, rgba(30, 144, 255, 0.05) 0%, transparent 50%),
radial-gradient(ellipse at 20% 80%, rgba(168, 85, 247, 0.04) 0%, transparent 50%);
}
.container {
width: 100%;
max-width: 700px;
background: var(--surface);
border-radius: 20px;
padding: 32px 28px 28px;
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5), 0 0 0 1px var(--border), 0 0 80px rgba(108, 92, 231, 0.06);
position: relative;
overflow: hidden;
}
.container::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
height: 3px;
background: linear-gradient(90deg, var(--key1), var(--key2), var(--key3), var(--key4), var(--key5), var(--key6));
border-radius: 20px 20px 0 0;
}
.header {
text-align: center;
margin-bottom: 24px;
}
.header h1 {
font-size: 1.8em;
font-weight: 700;
letter-spacing: -0.02em;
background: linear-gradient(135deg, #e0e0e8, #b0b0c8);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
margin-bottom: 4px;
}
.header .subtitle {
font-size: 0.85em;
color: var(--text2);
letter-spacing: 0.04em;
}
/* 音频上传区 */
.upload-section {
background: var(--surface2);
border: 2px dashed var(--border);
border-radius: var(--radius);
padding: 24px;
text-align: center;
cursor: pointer;
transition: all var(--transition);
margin-bottom: 20px;
position: relative;
}
.upload-section:hover {
border-color: var(--accent2);
background: rgba(108, 92, 231, 0.05);
}
.upload-section.has-file {
border-color: var(--success);
border-style: solid;
background: rgba(46, 213, 115, 0.04);
}
.upload-section input[type="file"] {
position: absolute;
inset: 0;
opacity: 0;
cursor: pointer;
}
.upload-icon {
font-size: 2.5em;
margin-bottom: 8px;
display: block;
}
.upload-text {
font-weight: 600;
font-size: 0.95em;
color: var(--text);
}
.upload-hint {
font-size: 0.78em;
color: var(--text2);
margin-top: 4px;
}
.file-name {
font-weight: 600;
color: var(--success);
font-size: 0.9em;
margin-top: 6px;
word-break: break-all;
}
.file-info {
font-size: 0.75em;
color: var(--text2);
margin-top: 2px;
}
/* 状态指示器 */
.status-bar {
display: flex;
align-items: center;
gap: 10px;
padding: 10px 16px;
border-radius: var(--radius-sm);
background: var(--surface2);
margin-bottom: 16px;
font-size: 0.85em;
}
.status-dot {
width: 10px;
height: 10px;
border-radius: 50%;
flex-shrink: 0;
}
.status-dot.idle {
background: #666;
}
.status-dot.ready {
background: var(--success);
box-shadow: 0 0 8px rgba(46, 213, 115, 0.5);
}
.status-dot.countdown {
background: var(--warning);
animation: pulse-dot 0.5s infinite alternate;
}
.status-dot.recording {
background: var(--danger);
animation: pulse-dot 0.35s infinite alternate;
}
.status-dot.finished {
background: var(--accent2);
box-shadow: 0 0 8px rgba(162, 155, 254, 0.5);
}
@keyframes pulse-dot {
to {
transform: scale(1.6);
opacity: 0.5;
}
}
/* 按钮 */
.btn-row {
display: flex;
gap: 10px;
flex-wrap: wrap;
margin-bottom: 16px;
}
.btn {
padding: 11px 22px;
border-radius: 25px;
border: none;
font-weight: 600;
font-size: 0.9em;
cursor: pointer;
letter-spacing: 0.02em;
transition: all var(--transition);
font-family: inherit;
position: relative;
overflow: hidden;
}
.btn:active {
transform: scale(0.96);
}
.btn:disabled {
opacity: 0.4;
cursor: not-allowed;
pointer-events: none;
}
.btn-primary {
background: var(--accent);
color: #fff;
box-shadow: 0 4px 16px rgba(108, 92, 231, 0.35);
}
.btn-primary:hover:not(:disabled) {
background: #7d6ff0;
box-shadow: 0 6px 22px rgba(108, 92, 231, 0.5);
}
.btn-stop {
background: var(--danger);
color: #fff;
box-shadow: 0 4px 14px rgba(231, 76, 60, 0.3);
}
.btn-stop:hover:not(:disabled) {
background: #f05045;
box-shadow: 0 6px 20px rgba(231, 76, 60, 0.45);
}
.btn-reset {
background: transparent;
color: var(--text2);
border: 1.5px solid var(--border);
}
.btn-reset:hover:not(:disabled) {
border-color: var(--text2);
color: var(--text);
}
.btn-copy {
background: var(--success);
color: #fff;
box-shadow: 0 4px 14px rgba(46, 213, 115, 0.3);
}
.btn-copy:hover:not(:disabled) {
background: #3be07a;
box-shadow: 0 6px 20px rgba(46, 213, 115, 0.45);
}
/* 倒计时覆盖层 */
.countdown-overlay {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.75);
display: flex;
align-items: center;
justify-content: center;
z-index: 100;
pointer-events: all;
}
.countdown-number {
font-size: 10em;
font-weight: 900;
color: #fff;
text-shadow: 0 0 60px rgba(255, 255, 255, 0.7), 0 0 120px rgba(108, 92, 231, 0.6);
animation: countdown-pop 0.9s cubic-bezier(0.175, 0.885, 0.32, 1.275);
user-select: none;
}
@keyframes countdown-pop {
0% {
transform: scale(2.5);
opacity: 0;
}
40% {
transform: scale(0.9);
opacity: 1;
}
100% {
transform: scale(1);
opacity: 1;
}
}
/* 按键指示器 */
.keys-display {
display: flex;
gap: 8px;
justify-content: center;
flex-wrap: wrap;
margin-bottom: 18px;
}
.key-indicator {
width: 50px;
height: 56px;
border-radius: var(--radius-sm);
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-weight: 700;
font-size: 0.85em;
transition: all 0.08s ease;
border: 2px solid transparent;
user-select: none;
cursor: default;
position: relative;
}
.key-indicator.k1 {
background: rgba(255, 71, 87, 0.15);
border-color: rgba(255, 71, 87, 0.3);
color: var(--key1);
}
.key-indicator.k2 {
background: rgba(255, 107, 53, 0.15);
border-color: rgba(255, 107, 53, 0.3);
color: var(--key2);
}
.key-indicator.k3 {
background: rgba(255, 192, 72, 0.15);
border-color: rgba(255, 192, 72, 0.3);
color: var(--key3);
}
.key-indicator.k4 {
background: rgba(46, 213, 115, 0.15);
border-color: rgba(46, 213, 115, 0.3);
color: var(--key4);
}
.key-indicator.k5 {
background: rgba(30, 144, 255, 0.15);
border-color: rgba(30, 144, 255, 0.3);
color: var(--key5);
}
.key-indicator.k6 {
background: rgba(168, 85, 247, 0.15);
border-color: rgba(168, 85, 247, 0.3);
color: var(--key6);
}
.key-indicator.flash {
transform: scale(1.12);
filter: brightness(2.2);
border-color: #fff !important;
box-shadow: 0 0 24px currentColor;
transition: all 0.04s ease;
}
.key-number {
font-size: 1.1em;
font-weight: 800;
}
.key-label {
font-size: 0.6em;
opacity: 0.7;
margin-top: 1px;
}
/* 进度条 */
.progress-container {
margin-bottom: 14px;
background: var(--surface2);
border-radius: 20px;
height: 6px;
overflow: hidden;
}
.progress-bar {
height: 100%;
background: linear-gradient(90deg, var(--accent), var(--accent2));
border-radius: 20px;
transition: width 0.1s linear;
width: 0%;
}
/* 实时记录 */
.live-notes {
background: var(--surface2);
border-radius: var(--radius);
padding: 14px 16px;
margin-bottom: 16px;
max-height: 180px;
overflow-y: auto;
font-family: 'SF Mono', 'Cascadia Code', 'Consolas', 'Menlo', monospace;
font-size: 0.78em;
color: var(--text2);
min-height: 50px;
line-height: 1.6;
word-break: break-all;
}
.live-notes .note-entry {
display: inline-block;
background: rgba(108, 92, 231, 0.2);
padding: 3px 8px;
border-radius: 4px;
margin: 2px 3px;
font-weight: 500;
color: #d0d0e0;
animation: fadeInNote 0.2s ease;
}
.live-notes .note-entry.multipress-hint {
background: rgba(255, 192, 72, 0.25);
color: #ffe0a0;
}
@keyframes fadeInNote {
from {
opacity: 0;
transform: translateY(-4px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
/* 结果区 */
.result-section {
background: var(--surface2);
border-radius: var(--radius);
padding: 16px;
margin-top: 8px;
display: none;
border: 1px solid var(--border);
}
.result-section.visible {
display: block;
animation: fadeInUp 0.4s ease;
}
@keyframes fadeInUp {
from {
opacity: 0;
transform: translateY(12px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.result-label {
font-weight: 700;
font-size: 0.9em;
margin-bottom: 8px;
color: var(--accent2);
letter-spacing: 0.03em;
}
.result-text {
background: #0a0a14;
border-radius: var(--radius-sm);
padding: 14px;
font-family: 'SF Mono', 'Cascadia Code', 'Consolas', 'Menlo', monospace;
font-size: 0.78em;
color: #c8d6e5;
overflow-x: auto;
white-space: pre-wrap;
word-break: break-all;
max-height: 300px;
overflow-y: auto;
line-height: 1.7;
border: 1px solid #1a1a30;
}
.stats-row {
display: flex;
gap: 14px;
flex-wrap: wrap;
margin-top: 10px;
font-size: 0.8em;
color: var(--text2);
}
.stat-item {
background: rgba(255, 255, 255, 0.03);
padding: 6px 12px;
border-radius: 15px;
font-weight: 500;
}
.stat-value {
color: var(--text);
font-weight: 700;
}
.toast {
position: fixed;
top: 20px;
left: 50%;
transform: translateX(-50%);
background: var(--success);
color: #fff;
padding: 10px 24px;
border-radius: 25px;
font-weight: 600;
font-size: 0.9em;
z-index: 200;
pointer-events: none;
animation: toastIn 0.3s ease, toastOut 0.3s ease 1.6s forwards;
box-shadow: 0 8px 24px rgba(46, 213, 115, 0.4);
}
@keyframes toastIn {
from {
opacity: 0;
transform: translateX(-50%) translateY(-20px);
}
to {
opacity: 1;
transform: translateX(-50%) translateY(0);
}
}
@keyframes toastOut {
from {
opacity: 1;
transform: translateX(-50%) translateY(0);
}
to {
opacity: 0;
transform: translateX(-50%) translateY(-20px);
}
}
/* 响应式 */
@media (max-width: 500px) {
.container {
padding: 20px 14px 16px;
border-radius: 14px;
}
.key-indicator {
width: 38px;
height: 44px;
font-size: 0.7em;
border-radius: 6px;
}
.btn {
padding: 9px 16px;
font-size: 0.8em;
border-radius: 20px;
}
.countdown-number {
font-size: 6em;
}
.header h1 {
font-size: 1.4em;
}
}
</style>
</head>
<body>
<div class="container">
<!-- 头部 -->
<div class="header">
<h1>🎵 铺面生成工具</h1>
<p class="subtitle">音游谱面制作器 · Chart Generator</p>
</div>
<!-- 音频上传区 -->
<div class="upload-section" id="uploadSection">
<input type="file" id="audioFileInput" accept="audio/*">
<span class="upload-icon">📁</span>
<p class="upload-text">点击上传音频文件</p>
<p class="upload-hint">支持 MP3 / WAV / OGG / FLAC 等常见格式</p>
<p class="file-name" id="fileNameDisplay" style="display:none;"></p>
<p class="file-info" id="fileInfoDisplay" style="display:none;"></p>
</div>
<!-- 状态栏 -->
<div class="status-bar">
<span class="status-dot idle" id="statusDot"></span>
<span id="statusText">等待上传音频</span>
<span style="margin-left:auto;font-size:0.78em;color:var(--text2);" id="timeDisplay">--:--</span>
</div>
<!-- 按键指示器 -->
<div class="keys-display" id="keysDisplay">
<div class="key-indicator k1" data-key="1"><span class="key-number">1</span><span class="key-label">Key</span></div>
<div class="key-indicator k2" data-key="2"><span class="key-number">2</span><span class="key-label">Key</span></div>
<div class="key-indicator k3" data-key="3"><span class="key-number">3</span><span class="key-label">Key</span></div>
<div class="key-indicator k4" data-key="4"><span class="key-number">4</span><span class="key-label">Key</span></div>
<div class="key-indicator k5" data-key="5"><span class="key-number">5</span><span class="key-label">Key</span></div>
<div class="key-indicator k6" data-key="6"><span class="key-number">6</span><span class="key-label">Key</span></div>
</div>
<!-- 进度条 -->
<div class="progress-container">
<div class="progress-bar" id="progressBar"></div>
</div>
<!-- 实时记录 -->
<div class="live-notes" id="liveNotes">
<span style="color:#555;">等待开始录制...</span>
</div>
<!-- 按钮 -->
<div class="btn-row">
<button class="btn btn-primary" id="btnStart" disabled>▶ 开始录制</button>
<button class="btn btn-stop" id="btnStop" disabled>⏹ 停止</button>
<button class="btn btn-reset" id="btnReset">↺ 重置</button>
</div>
<!-- 结果区 -->
<div class="result-section" id="resultSection">
<div class="result-label">📋 生成的铺面数据</div>
<div class="result-text" id="resultText"></div>
<div class="stats-row" id="statsRow"></div>
<div class="btn-row" style="margin-top:10px;">
<button class="btn btn-copy" id="btnCopy">📋 复制铺面数据</button>
</div>
</div>
</div>
<!-- 倒计时覆盖层(初始隐藏) -->
<div class="countdown-overlay" id="countdownOverlay" style="display:none;">
<span class="countdown-number" id="countdownNumber">3</span>
</div>
<!-- 隐藏的音频元素 -->
<audio id="audioPlayer" preload="auto" style="display:none;"></audio>
<script>
(function() {
// ============ DOM 元素 ============
const audioFileInput = document.getElementById('audioFileInput');
const uploadSection = document.getElementById('uploadSection');
const fileNameDisplay = document.getElementById('fileNameDisplay');
const fileInfoDisplay = document.getElementById('fileInfoDisplay');
const statusDot = document.getElementById('statusDot');
const statusText = document.getElementById('statusText');
const timeDisplay = document.getElementById('timeDisplay');
const progressBar = document.getElementById('progressBar');
const liveNotes = document.getElementById('liveNotes');
const btnStart = document.getElementById('btnStart');
const btnStop = document.getElementById('btnStop');
const btnReset = document.getElementById('btnReset');
const btnCopy = document.getElementById('btnCopy');
const resultSection = document.getElementById('resultSection');
const resultText = document.getElementById('resultText');
const statsRow = document.getElementById('statsRow');
const countdownOverlay = document.getElementById('countdownOverlay');
const countdownNumber = document.getElementById('countdownNumber');
const audioPlayer = document.getElementById('audioPlayer');
const keysDisplay = document.getElementById('keysDisplay');
const keyIndicators = keysDisplay.querySelectorAll('.key-indicator');
// ============ 状态变量 ============
let audioFile = null;
let audioObjectURL = null;
let appState = 'idle'; // idle | ready | countdown | recording | finished
let rawNotes = []; // { time: ms(浮点), key: 1-6 }
let recordingStartTime = null; // performance.now() 在音频开始播放时的值
let countdownTimerId = null;
let progressIntervalId = null;
let keyFlashTimers = {}; // 按键闪烁计时器
// ============ 常量 ============
const MULTIPRESS_THRESHOLD_MS = 10; // 多押阈值:10ms
const COUNTDOWN_SECONDS = 3;
// ============ 音频上传 ============
uploadSection.addEventListener('click', (e) => {
if (e.target === audioFileInput) return;
if (appState === 'recording' || appState === 'countdown') return;
audioFileInput.click();
});
audioFileInput.addEventListener('change', (e) => {
const file = e.target.files[0];
if (!file) return;
// 验证音频格式
const validTypes = ['audio/mpeg', 'audio/wav', 'audio/ogg', 'audio/flac',
'audio/x-wav', 'audio/webm', 'audio/aac', 'audio/mp4', 'audio/x-m4a',
'audio/opus', 'audio/x-ms-wma', 'audio/vnd.wave'
];
const isAudio = file.type.startsWith('audio/') || validTypes.includes(file.type) ||
/\.(mp3|wav|ogg|flac|m4a|aac|opus|webm|wma)$/i.test(file.name);
if (!isAudio) {
showToast('⚠️ 请上传有效的音频文件', '#f39c12');
return;
}
// 清理旧URL
if (audioObjectURL) {
URL.revokeObjectURL(audioObjectURL);
}
// 重置状态
resetAll(false);
audioFile = file;
audioObjectURL = URL.createObjectURL(file);
audioPlayer.src = audioObjectURL;
audioPlayer.load();
// 更新UI
fileNameDisplay.textContent = '✅ ' + file.name;
fileNameDisplay.style.display = 'block';
const sizeMB = (file.size / (1024 * 1024)).toFixed(2);
fileInfoDisplay.textContent = `大小: ${sizeMB} MB · 类型: ${file.type || '未知'}`;
fileInfoDisplay.style.display = 'block';
uploadSection.classList.add('has-file');
setAppState('ready');
liveNotes.innerHTML = '<span style="color:#555;">音频已加载,点击"开始录制"以启动...</span>';
showToast('✅ 音频已加载,准备就绪', '#2ecc71');
});
// ============ 拖拽上传支持 ============
uploadSection.addEventListener('dragover', (e) => {
e.preventDefault();
if (appState === 'recording' || appState === 'countdown') return;
uploadSection.style.borderColor = '#a29bfe';
uploadSection.style.background = 'rgba(108, 92, 231, 0.08)';
});
uploadSection.addEventListener('dragleave', (e) => {
e.preventDefault();
uploadSection.style.borderColor = '';
uploadSection.style.background = '';
});
uploadSection.addEventListener('drop', (e) => {
e.preventDefault();
uploadSection.style.borderColor = '';
uploadSection.style.background = '';
if (appState === 'recording' || appState === 'countdown') return;
const file = e.dataTransfer.files[0];
if (file) {
audioFileInput.files = e.dataTransfer.files;
audioFileInput.dispatchEvent(new Event('change'));
}
});
// ============ 开始录制 ============
btnStart.addEventListener('click', () => {
if (appState !== 'ready' && appState !== 'finished') return;
if (!audioFile) {
showToast('⚠️ 请先上传音频文件', '#f39c12');
return;
}
// 重置录制数据
rawNotes = [];
recordingStartTime = null;
resultSection.classList.remove('visible');
liveNotes.innerHTML = '<span style="color:#888;">准备开始...</span>';
progressBar.style.width = '0%';
timeDisplay.textContent = '00:00';
// 重置音频
audioPlayer.currentTime = 0;
audioPlayer.load();
// 开始倒计时
startCountdown();
});
function startCountdown() {
setAppState('countdown');
countdownOverlay.style.display = 'flex';
let remaining = COUNTDOWN_SECONDS;
// 显示初始数字
countdownNumber.textContent = remaining;
countdownNumber.style.animation = 'none';
void countdownNumber.offsetWidth;
countdownNumber.style.animation = 'countdown-pop 0.9s cubic-bezier(0.175, 0.885, 0.32, 1.275)';
if (countdownTimerId) clearInterval(countdownTimerId);
countdownTimerId = setInterval(() => {
remaining--;
if (remaining > 0) {
countdownNumber.textContent = remaining;
countdownNumber.style.animation = 'none';
void countdownNumber.offsetWidth;
countdownNumber.style.animation =
'countdown-pop 0.9s cubic-bezier(0.175, 0.885, 0.32, 1.275)';
} else if (remaining === 0) {
countdownNumber.textContent = 'GO!';
countdownNumber.style.color = '#2ecc71';
countdownNumber.style.textShadow = '0 0 80px rgba(46,213,115,0.9), 0 0 160px rgba(46,213,115,0.5)';
countdownNumber.style.animation = 'none';
void countdownNumber.offsetWidth;
countdownNumber.style.animation =
'countdown-pop 0.9s cubic-bezier(0.175, 0.885, 0.32, 1.275)';
} else {
// 倒计时结束
clearInterval(countdownTimerId);
countdownTimerId = null;
countdownOverlay.style.display = 'none';
countdownNumber.style.color = '#fff';
countdownNumber.style.textShadow =
'0 0 60px rgba(255,255,255,0.7), 0 0 120px rgba(108,92,231,0.6)';
beginRecording();
}
}, 1000);
}
function beginRecording() {
setAppState('recording');
recordingStartTime = performance.now();
rawNotes = [];
liveNotes.innerHTML = '<span style="color:#2ecc71;">● 录制中... 按下数字键 1~6 来标记音符</span>';
resultSection.classList.remove('visible');
progressBar.style.width = '0%';
timeDisplay.textContent = '00:00';
// 开始播放音频
audioPlayer.currentTime = 0;
const playPromise = audioPlayer.play();
if (playPromise !== undefined) {
playPromise.catch((err) => {
console.error('音频播放失败:', err);
showToast('⚠️ 音频播放失败,请检查文件格式', '#e74c3c');
setAppState('ready');
return;
});
}
// 更新进度条
if (progressIntervalId) clearInterval(progressIntervalId);
progressIntervalId = setInterval(updateProgress, 50);
// 监听音频结束
audioPlayer.addEventListener('ended', onAudioEnded, { once: true });
}
function onAudioEnded() {
if (appState !== 'recording') return;
stopRecordingAndGenerate();
}
btnStop.addEventListener('click', () => {
if (appState !== 'recording') return;
audioPlayer.pause();
audioPlayer.removeEventListener('ended', onAudioEnded);
stopRecordingAndGenerate();
});
function stopRecordingAndGenerate() {
if (progressIntervalId) {
clearInterval(progressIntervalId);
progressIntervalId = null;
}
// 确保进度条走到100%
progressBar.style.width = '100%';
const duration = audioPlayer.duration || 0;
const min = Math.floor(duration / 60);
const sec = Math.floor(duration % 60);
timeDisplay.textContent = String(min).padStart(2, '0') + ':' + String(sec).padStart(2, '0');
setAppState('finished');
liveNotes.innerHTML = '<span style="color:#a29bfe;">录制完成,正在生成铺面...</span>';
// 进行多押聚类处理
const processedNotes = clusterMultipress(rawNotes, MULTIPRESS_THRESHOLD_MS);
// 生成输出
generateOutput(processedNotes);
// 更新实时记录区显示聚类后的结果
updateLiveNotesWithProcessed(processedNotes);
}
// ============ 多押聚类算法 ============
function clusterMultipress(notes, thresholdMs) {
if (notes.length === 0) return [];
// 按时间排序
const sorted = [...notes].sort((a, b) => a.time - b.time);
// 聚类:相邻时间差 < thresholdMs 的归为一组
const clusters = [];
let currentCluster = [sorted[0]];
for (let i = 1; i < sorted.length; i++) {
const prev = sorted[i - 1];
const curr = sorted[i];
if (curr.time - prev.time < thresholdMs) {
// 属于同一组多押
currentCluster.push(curr);
} else {
// 开始新组
clusters.push(currentCluster);
currentCluster = [curr];
}
}
clusters.push(currentCluster);
// 每组使用组内第一个元素的时间戳
const result = [];
for (const cluster of clusters) {
const groupTime = cluster[0].time;
// 组内去重(相同键值只保留一个,但保留不同键值)
const seenKeys = new Set();
for (const note of cluster) {
if (!seenKeys.has(note.key)) {
seenKeys.add(note.key);
result.push({
time: Math.round(groupTime), // 四舍五入到整数毫秒
key: note.key,
isMultipress: cluster.length > 1
});
}
}
}
// 按时间排序(同时间的按键值排序)
result.sort((a, b) => {
if (a.time !== b.time) return a.time - b.time;
return a.key - b.key;
});
return result;
}
// ============ 生成输出 ============
function generateOutput(processedNotes) {
if (processedNotes.length === 0) {
resultText.textContent = '[]';
statsRow.innerHTML = '<span class="stat-item">总音符数: <span class="stat-value">0</span></span>';
resultSection.classList.add('visible');
liveNotes.innerHTML = '<span style="color:#888;">没有记录到任何音符。</span>';
return;
}
// 构建输出字符串(纯数字,不加'K',不带单位)
const lines = processedNotes.map(n => `[${n.time}, ${n.key}]`);
const output = '[\n ' + lines.join(',\n ') + '\n]';
resultText.textContent = output;
// 统计信息
const totalNotes = processedNotes.length;
const multipressGroups = new Set();
let maxMultipressSize = 1;
const timeKeyMap = {};
for (const n of processedNotes) {
if (!timeKeyMap[n.time]) timeKeyMap[n.time] = [];
timeKeyMap[n.time].push(n.key);
}
for (const [time, keys] of Object.entries(timeKeyMap)) {
if (keys.length > 1) {
multipressGroups.add(time);
if (keys.length > maxMultipressSize) maxMultipressSize = keys.length;
}
}
statsRow.innerHTML = `
<span class="stat-item">📝 总音符数: <span class="stat-value">${totalNotes}</span></span>
<span class="stat-item">🔗 多押组数: <span class="stat-value">${multipressGroups.size}</span></span>
<span class="stat-item">📐 最大多押: <span class="stat-value">${maxMultipressSize}键</span></span>
<span class="stat-item">⏱ 时间跨度: <span class="stat-value">${processedNotes[processedNotes.length-1].time - processedNotes[0].time} ms</span></span>
`;
resultSection.classList.add('visible');
resultSection.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
liveNotes.innerHTML =
'<span style="color:#a29bfe;">✅ 铺面已生成(见下方),点击"复制铺面数据"按钮即可复制。</span>';
}
function updateLiveNotesWithProcessed(processedNotes) {
if (processedNotes.length === 0) {
liveNotes.innerHTML = '<span style="color:#888;">没有记录到任何音符。</span>';
return;
}
const preview = processedNotes.slice(0, 50).map(n => {
const cls = n.isMultipress ? 'note-entry multipress-hint' : 'note-entry';
// 纯数字,无单位
return `<span class="${cls}">[${n.time}, ${n.key}]</span>`;
}).join(' ');
const more = processedNotes.length > 50 ?
` <span style="color:#888;">...共${processedNotes.length}条</span>` : '';
liveNotes.innerHTML = preview + more;
}
// ============ 按键监听 ============
document.addEventListener('keydown', (e) => {
// 只处理数字键1-6
const key = parseInt(e.key);
if (isNaN(key) || key < 1 || key > 6) return;
// 防止默认行为
e.preventDefault();
// 只在录制状态记录
if (appState !== 'recording') return;
if (recordingStartTime === null) return;
const elapsed = performance.now() - recordingStartTime;
rawNotes.push({
time: elapsed,
key: key
});
// 实时更新显示
updateLiveNotesRaw();
// 按键视觉反馈
flashKeyIndicator(key);
});
function updateLiveNotesRaw() {
if (rawNotes.length === 0) {
liveNotes.innerHTML = '<span style="color:#2ecc71;">● 录制中... 按下数字键 1~6 来标记音符</span>';
return;
}
const recent = rawNotes.slice(-30);
const preview = recent.map((n, i) => {
// 检查是否可能与下一个形成多押(简单的相邻检查)
let isMulti = false;
if (i < recent.length - 1) {
if (Math.abs(recent[i + 1].time - n.time) < MULTIPRESS_THRESHOLD_MS) {
isMulti = true;
}
}
if (i > 0 && !isMulti) {
if (Math.abs(n.time - recent[i - 1].time) < MULTIPRESS_THRESHOLD_MS) {
isMulti = true;
}
}
const cls = isMulti ? 'note-entry multipress-hint' : 'note-entry';
// 纯数字,无单位
return `<span class="${cls}">[${Math.round(n.time)}, ${n.key}]</span>`;
}).join(' ');
const totalHint = rawNotes.length > 30 ?
` <span style="color:#888;">...共${rawNotes.length}条</span>` : '';
liveNotes.innerHTML =
'<span style="color:#2ecc71;font-size:0.7em;">● REC </span>' + preview + totalHint;
}
function flashKeyIndicator(key) {
const indicator = keysDisplay.querySelector(`.key-indicator[data-key="${key}"]`);
if (!indicator) return;
indicator.classList.add('flash');
// 清除之前的计时器
if (keyFlashTimers[key]) {
clearTimeout(keyFlashTimers[key]);
}
keyFlashTimers[key] = setTimeout(() => {
indicator.classList.remove('flash');
}, 120);
}
// ============ 进度更新 ============
function updateProgress() {
if (!audioPlayer.duration || audioPlayer.duration === Infinity) return;
const progress = (audioPlayer.currentTime / audioPlayer.duration) * 100;
progressBar.style.width = Math.min(progress, 100) + '%';
const current = audioPlayer.currentTime;
const min = Math.floor(current / 60);
const sec = Math.floor(current % 60);
timeDisplay.textContent = String(min).padStart(2, '0') + ':' + String(sec).padStart(2, '0');
}
// ============ 复制按钮 ============
btnCopy.addEventListener('click', () => {
const text = resultText.textContent;
if (!text || text === '[]') {
showToast('⚠️ 没有可复制的铺面数据', '#f39c12');
return;
}
copyToClipboard(text);
});
function copyToClipboard(text) {
if (navigator.clipboard && navigator.clipboard.writeText) {
navigator.clipboard.writeText(text).then(() => {
showToast('✅ 已复制到剪贴板!', '#2ecc71');
}).catch(() => {
fallbackCopy(text);
});
} else {
fallbackCopy(text);
}
}
function fallbackCopy(text) {
const textarea = document.createElement('textarea');
textarea.value = text;
textarea.style.position = 'fixed';
textarea.style.left = '-9999px';
textarea.style.top = '-9999px';
document.body.appendChild(textarea);
textarea.focus();
textarea.select();
try {
document.execCommand('copy');
showToast('✅ 已复制到剪贴板!', '#2ecc71');
} catch (err) {
showToast('❌ 复制失败,请手动选择文本复制', '#e74c3c');
}
document.body.removeChild(textarea);
}
// ============ 重置按钮 ============
btnReset.addEventListener('click', () => {
if (appState === 'countdown') {
// 取消倒计时
if (countdownTimerId) {
clearInterval(countdownTimerId);
countdownTimerId = null;
}
countdownOverlay.style.display = 'none';
countdownNumber.style.color = '#fff';
countdownNumber.style.textShadow =
'0 0 60px rgba(255,255,255,0.7), 0 0 120px rgba(108,92,231,0.6)';
}
if (appState === 'recording') {
audioPlayer.pause();
audioPlayer.removeEventListener('ended', onAudioEnded);
if (progressIntervalId) {
clearInterval(progressIntervalId);
progressIntervalId = null;
}
}
resetAll(true);
showToast('🔄 已重置', '#a29bfe');
});
function resetAll(clearFile) {
if (countdownTimerId) {
clearInterval(countdownTimerId);
countdownTimerId = null;
}
if (progressIntervalId) {
clearInterval(progressIntervalId);
progressIntervalId = null;
}
countdownOverlay.style.display = 'none';
countdownNumber.style.color = '#fff';
countdownNumber.style.textShadow =
'0 0 60px rgba(255,255,255,0.7), 0 0 120px rgba(108,92,231,0.6)';
rawNotes = [];
recordingStartTime = null;
progressBar.style.width = '0%';
timeDisplay.textContent = '--:--';
resultSection.classList.remove('visible');
resultText.textContent = '';
statsRow.innerHTML = '';
audioPlayer.pause();
audioPlayer.removeEventListener('ended', onAudioEnded);
audioPlayer.currentTime = 0;
liveNotes.innerHTML = '<span style="color:#555;">等待开始录制...</span>';
// 清除按键闪烁
for (const key in keyFlashTimers) {
clearTimeout(keyFlashTimers[key]);
const indicator = keysDisplay.querySelector(`.key-indicator[data-key="${key}"]`);
if (indicator) indicator.classList.remove('flash');
}
keyFlashTimers = {};
if (clearFile) {
audioFile = null;
if (audioObjectURL) {
URL.revokeObjectURL(audioObjectURL);
audioObjectURL = null;
}
audioPlayer.src = '';
fileNameDisplay.style.display = 'none';
fileInfoDisplay.style.display = 'none';
uploadSection.classList.remove('has-file');
audioFileInput.value = '';
setAppState('idle');
} else {
// 保留文件,回到ready状态
if (audioFile) {
setAppState('ready');
liveNotes.innerHTML = '<span style="color:#555;">音频已加载,点击"开始录制"以启动...</span>';
} else {
setAppState('idle');
}
}
}
// ============ 状态管理 ============
function setAppState(state) {
appState = state;
statusDot.className = 'status-dot ' + state;
switch (state) {
case 'idle':
statusText.textContent = '等待上传音频';
btnStart.disabled = true;
btnStop.disabled = true;
btnReset.disabled = false;
break;
case 'ready':
statusText.textContent = '已就绪';
btnStart.disabled = false;
btnStop.disabled = true;
btnReset.disabled = false;
break;
case 'countdown':
statusText.textContent = '倒计时中...';
btnStart.disabled = true;
btnStop.disabled = true;
btnReset.disabled = false;
break;
case 'recording':
statusText.textContent = '🔴 录制中 - 按下数字键1~6';
btnStart.disabled = true;
btnStop.disabled = false;
btnReset.disabled = false;
break;
case 'finished':
statusText.textContent = '录制完成 - 铺面已生成';
btnStart.disabled = false;
btnStop.disabled = true;
btnReset.disabled = false;
btnStart.textContent = '🔄 重新录制';
break;
}
if (state !== 'finished') {
btnStart.textContent = '▶ 开始录制';
}
}
// ============ Toast提示 ============
function showToast(message, color) {
// 移除已有toast
const existing = document.querySelector('.toast');
if (existing) existing.remove();
const toast = document.createElement('div');
toast.className = 'toast';
toast.textContent = message;
toast.style.background = color || '#2ecc71';
toast.style.boxShadow = `0 8px 24px ${color || 'rgba(46,213,115,0.4)'}`;
document.body.appendChild(toast);
setTimeout(() => {
if (toast.parentNode) toast.remove();
}, 2000);
}
// ============ 初始状态 ============
setAppState('idle');
btnStart.disabled = true;
btnStop.disabled = true;
liveNotes.innerHTML = '<span style="color:#555;">请上传音频文件以开始...</span>';
// ============ 页面关闭前清理 ============
window.addEventListener('beforeunload', () => {
if (audioObjectURL) {
URL.revokeObjectURL(audioObjectURL);
}
if (countdownTimerId) clearInterval(countdownTimerId);
if (progressIntervalId) clearInterval(progressIntervalId);
for (const key in keyFlashTimers) {
clearTimeout(keyFlashTimers[key]);
}
});
console.log('🎵 铺面生成工具已就绪');
console.log(' - 上传音频文件');
console.log(' - 点击"开始录制"');
console.log(' - 等待3秒倒计时');
console.log(' - 在音乐播放时按下数字键 1~6');
console.log(' - 多押阈值: ' + MULTIPRESS_THRESHOLD_MS + 'ms');
console.log(' - 音频结束后自动生成铺面');
console.log(' - 输出格式: [[下落时间(ms), 音符类型(1~6)]]');
})();
</script>
</body>
</html>
::::