fertig-classic-games/src/games/superkart/SuperKartEditor.js

713 lines
27 KiB
JavaScript

// Super Kart track editor. Secret entrance: index.html?superkart-editor=1
// (see PreloadScene). Mirrors the Peggle editor workflow: load (existing
// track from assets/gamedata/superkart/ or any local .json) → edit →
// Test Play → ⬇ Export Track (track-NNN.json) + ⬇ Export Cups Index
// (cups.json), then hand-drop the files into assets/gamedata/superkart/.
//
// The track is a closed centerline spline with per-point width; item rows and
// boost pads are arc-length addressed so they ride along with spline edits.
// A live validation strip runs the same checks tools/verifySuperKart.js does.
import * as Phaser from 'phaser';
import { GAME_WIDTH, GAME_HEIGHT, COLORS } from '../../config.js';
import { Button } from '../../ui/Button.js';
import { playSound, SFX } from '../../ui/Sounds.js';
import { buildTrackModel, validateTrack, projectToSpline, roadPoint } from './SuperKartTrack.js';
import { rasterizeTrack } from './SuperKartRaster.js';
const FONT = 'm6x11, "Julius Sans One"';
const BOARD_X = 70;
const BOARD_Y = 70;
const BOARD_SIZE = 940;
const GAMEDATA = 'assets/gamedata/superkart';
const TOOLS = [
['move', 'Move'],
['point', 'Add Point'],
['start', 'Start Line'],
['itemrow', 'Item Row'],
['boost', 'Boost Pad'],
['coin', 'Coin'],
['water', 'Water Poly'],
['deep', 'Deep Poly'],
['wall', 'Wall Line'],
['decor', 'Decor'],
['hazard', 'Hazard'],
['delete', 'Delete'],
];
export default class SuperKartEditor extends Phaser.Scene {
constructor() { super('SuperKartEditor'); }
init(data) {
this.resume = !!data?.resume;
}
create() {
this.rules = this.cache.json.get('superkart-rules');
this.themes = Object.keys(this.rules?.themes ?? { speedway: 1 }).filter((t) => !t.startsWith('_'));
if (this.resume) {
this.track = this.registry.get('superkart-editor-state') ?? this.defaultTrack();
} else {
this.track = this.defaultTrack();
}
this.tool = 'move';
this.selected = -1; // selected spline point index
this.draftPoly = []; // in-progress water/deep/wall points
this.undoStack = [];
this.model = null;
this.issues = [];
this.previewDirty = true;
this.previewTimer = 0;
this.cameraBg = this.add.rectangle(GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH, GAME_HEIGHT, 0x101018);
this.add.rectangle(BOARD_X + BOARD_SIZE / 2, BOARD_Y + BOARD_SIZE / 2, BOARD_SIZE + 8, BOARD_SIZE + 8, 0x000000)
.setStrokeStyle(2, COLORS.accent);
this.previewImg = null;
this.g = this.add.graphics().setDepth(5);
// cups.json is lazy-loaded by the game, so the editor fetches it itself.
this.cupsIndex = { version: 1, cups: [], tracks: [] };
fetch(`${GAMEDATA}/cups.json`).then((r) => r.json())
.then((d) => { this.cupsIndex = d; this.refreshLoadOptions(); })
.catch(() => {});
this.buildToolbar();
this.buildLoadPanel();
this.bindPointer();
this.bindKeys();
this.rebuildModel();
}
defaultTrack() {
const spline = [];
for (let i = 0; i < 10; i += 1) {
const a = (i / 10) * Math.PI * 2;
spline.push({
x: Math.round(2048 + Math.cos(a) * 1250),
y: Math.round(2048 + Math.sin(a) * 1250),
w: 110,
});
}
return {
version: 1,
id: 'track-013',
name: 'New Track',
theme: this.themes?.[0] ?? 'speedway',
laps: 5,
world: 4096,
spline,
startIndex: 0,
surfaces: [],
walls: [],
boosts: [],
itemRows: [],
hazards: [],
decor: [],
coins: [],
};
}
// ── Coordinate transforms ────────────────────────────────────────────────
toBoard(wx, wy) {
const k = BOARD_SIZE / this.track.world;
return [BOARD_X + wx * k, BOARD_Y + wy * k];
}
toWorld(bx, by) {
const k = this.track.world / BOARD_SIZE;
return [(bx - BOARD_X) * k, (by - BOARD_Y) * k];
}
onBoard(p) {
return p.x >= BOARD_X && p.x <= BOARD_X + BOARD_SIZE && p.y >= BOARD_Y && p.y <= BOARD_Y + BOARD_SIZE;
}
// ── Toolbar / chrome ─────────────────────────────────────────────────────
buildToolbar() {
const tx = BOARD_X + BOARD_SIZE + 90;
const bw = 250;
this.add.text(tx + bw / 2, 34, 'SUPER KART EDITOR', {
fontFamily: FONT, fontSize: '30px', color: '#ffd028',
}).setOrigin(0.5);
this.toolButtons = {};
TOOLS.forEach(([id, label], i) => {
const col = i % 2;
const row = Math.floor(i / 2);
const b = new Button(this, tx + col * (bw / 2 + 8) + bw / 4, 92 + row * 62, label,
() => this.setTool(id), { width: bw / 2, height: 52, fontSize: 18 });
this.toolButtons[id] = b;
});
this.setTool('move');
let y = 92 + Math.ceil(TOOLS.length / 2) * 62 + 20;
const half = bw / 2 + 8;
this.metaName = new Button(this, tx + bw / 2, y, `Name: ${this.track.name}`, () => {
const name = window.prompt('Track name:', this.track.name);
if (name) { this.track.name = name; this.metaName.setLabel(`Name: ${name}`); }
}, { width: bw + 8, height: 48, fontSize: 17, variant: 'ghost' });
y += 58;
this.metaFile = new Button(this, tx + bw / 2, y, `File: ${this.track.id}.json`, () => {
const id = window.prompt('Track id (file will be <id>.json):', this.track.id);
if (id) { this.track.id = id; this.metaFile.setLabel(`File: ${id}.json`); }
}, { width: bw + 8, height: 48, fontSize: 17, variant: 'ghost' });
y += 58;
this.metaTheme = new Button(this, tx + half / 2 - 4, y, `Theme: ${this.track.theme}`, () => {
const i = (this.themes.indexOf(this.track.theme) + 1) % this.themes.length;
this.track.theme = this.themes[i];
this.metaTheme.setLabel(`Theme: ${this.track.theme}`);
this.markDirty();
}, { width: half - 8, height: 48, fontSize: 15, variant: 'ghost' });
this.metaLaps = new Button(this, tx + half + half / 2 - 4, y, `Laps: ${this.track.laps}`, () => {
this.track.laps = { 3: 5, 5: 7, 7: 3 }[this.track.laps] ?? 5;
this.metaLaps.setLabel(`Laps: ${this.track.laps}`);
}, { width: half - 8, height: 48, fontSize: 15, variant: 'ghost' });
y += 70;
new Button(this, tx + bw / 2, y, '▶ Test Play', () => this.testPlay(), { width: bw + 8, height: 56, fontSize: 22 });
y += 66;
new Button(this, tx + bw / 2, y, '⬇ Export Track', () => this.exportTrack(), { width: bw + 8, height: 52, fontSize: 19 });
y += 62;
new Button(this, tx + bw / 2, y, '⬇ Export Cups Index', () => this.exportCups(), { width: bw + 8, height: 52, fontSize: 19 });
y += 62;
new Button(this, tx + half / 2 - 4, y, 'Undo (Z)', () => this.undo(), { width: half - 8, height: 48, fontSize: 16, variant: 'ghost' });
new Button(this, tx + half + half / 2 - 4, y, 'New Track', () => {
this.pushUndo();
this.track = this.defaultTrack();
this.selected = -1;
this.rebuildModel();
}, { width: half - 8, height: 48, fontSize: 16, variant: 'ghost' });
y += 58;
new Button(this, tx + bw / 2, y, 'Exit Editor', () => { window.location.search = ''; },
{ width: bw + 8, height: 48, fontSize: 17, variant: 'ghost' });
this.helpText = this.add.text(tx, y + 46, '', {
fontFamily: FONT, fontSize: '15px', color: COLORS.mutedHex, wordWrap: { width: bw + 20 },
});
this.issueText = this.add.text(BOARD_X, BOARD_Y + BOARD_SIZE + 8, '', {
fontFamily: FONT, fontSize: '18px', color: COLORS.dangerHex,
});
}
setTool(id) {
this.tool = id;
this.draftPoly = [];
for (const [tid, b] of Object.entries(this.toolButtons)) b.setActive(tid === id);
const help = {
move: 'Drag spline points. Drag the small square handle to set road width. Click a point to select; Del removes it.',
point: 'Click near a segment to insert a control point there; click elsewhere to append at the nearest end.',
start: 'Click a control point to put the start/finish line there.',
itemrow: 'Click the road to drop a row of 4 item boxes at that spot.',
boost: 'Click the road to place a boost pad (uses the clicked lane).',
coin: 'Click the road to place a single coin.',
water: 'Click to outline a water pool. Press Enter to close it.',
deep: 'Click to outline a deep pit. Press Enter to close it.',
wall: 'Click to draw a wall polyline. Press Enter to finish.',
decor: 'Click off-road to stamp scenery (cycles through the theme set).',
hazard: 'Click to place a static hazard object.',
delete: 'Click near any placed object (row, boost, coin, poly, wall, decor, hazard) to remove it.',
};
this.helpText?.setText(help[id] ?? '');
}
// ── Load ─────────────────────────────────────────────────────────────────
buildLoadPanel() {
const rx = BOARD_X + BOARD_SIZE + 90 + 250 + 40;
const rw = 460;
const input = 'background:#1e1a12; color:#f2ead8; border:1px solid #ffd028; border-radius:6px; padding:7px 9px; font-size:15px; width:100%;';
const el = document.createElement('div');
el.style.cssText = `width:${rw}px; font-family:"Julius Sans One",sans-serif; color:${COLORS.textHex};`;
el.innerHTML = `
<div style="background:#0a0a12ee; border:2px solid #ffd028; border-radius:14px; padding:16px 20px;">
<div style="font-size:20px; color:#ffd028; text-align:center; margin-bottom:10px;">LOAD TRACK</div>
<select id="sk-load" style="${input} margin-bottom:10px;"><option value="">— load from ${GAMEDATA}/ —</option></select>
<input id="sk-fileinput" type="file" accept=".json" style="width:100%; font-size:14px; color:${COLORS.textHex};">
<div id="sk-load-warn" style="color:${COLORS.dangerHex}; font-size:14px; min-height:20px; margin-top:8px;"></div>
</div>`;
this.loadDom = this.add.dom(rx + rw / 2, 220, el).setDepth(20);
const q = (id) => el.querySelector(id);
this.loadSelect = q('#sk-load');
this.loadWarn = q('#sk-load-warn');
this.loadSelect.addEventListener('change', (ev) => {
const file = ev.target.value;
if (file) this.loadFromManifest(file);
ev.target.value = '';
});
q('#sk-fileinput').addEventListener('change', (ev) => {
const f = ev.target.files?.[0];
if (!f) return;
const reader = new FileReader();
reader.onload = () => {
try { this.loadTrack(JSON.parse(reader.result), f.name); } catch (_) { this.flashLoadWarn(`Could not parse ${f.name}`); }
};
reader.readAsText(f);
ev.target.value = '';
});
this.refreshLoadOptions();
}
refreshLoadOptions() {
if (!this.loadSelect) return;
const opts = [`<option value="">— load from ${GAMEDATA}/ —</option>`,
...(this.cupsIndex?.tracks ?? []).map((t) => `<option value="${t.file}">${t.id} · ${t.name}</option>`)].join('');
this.loadSelect.innerHTML = opts;
}
flashLoadWarn(msg) {
if (!this.loadWarn) return;
this.loadWarn.textContent = msg;
this.time.delayedCall(4000, () => { if (this.loadWarn) this.loadWarn.textContent = ''; });
}
async loadFromManifest(file) {
try {
const res = await fetch(`${GAMEDATA}/${file}`);
if (!res.ok) throw new Error('not found');
this.loadTrack(await res.json(), file);
} catch (_) {
this.flashLoadWarn(`Could not load ${file}`);
}
}
loadTrack(rawData, fileName) {
let data;
try { data = JSON.parse(JSON.stringify(rawData)); } catch (_) { data = null; }
if (!data || !Array.isArray(data.spline) || data.spline.length < 3) {
this.flashLoadWarn(`${fileName}: not a valid track file`);
return;
}
this.pushUndo();
const d = this.defaultTrack();
this.track = {
version: data.version ?? 1,
id: data.id ?? d.id,
name: data.name ?? d.name,
theme: this.themes.includes(data.theme) ? data.theme : (this.themes?.[0] ?? 'speedway'),
laps: data.laps ?? d.laps,
world: data.world ?? d.world,
spline: data.spline,
startIndex: Phaser.Math.Clamp(data.startIndex ?? 0, 0, data.spline.length - 1),
surfaces: data.surfaces ?? [],
walls: data.walls ?? [],
boosts: data.boosts ?? [],
itemRows: data.itemRows ?? [],
hazards: data.hazards ?? [],
decor: data.decor ?? [],
coins: data.coins ?? [],
};
this.selected = -1;
this.draftPoly = [];
this.metaName?.setLabel(`Name: ${this.track.name}`);
this.metaFile?.setLabel(`File: ${this.track.id}.json`);
this.metaTheme?.setLabel(`Theme: ${this.track.theme}`);
this.metaLaps?.setLabel(`Laps: ${this.track.laps}`);
this.rebuildModel();
playSound(this, SFX.UI_CHIME);
this.flash(`Loaded ${fileName}`);
}
// ── Input ────────────────────────────────────────────────────────────────
bindPointer() {
this.dragging = -1; // spline point being dragged
this.draggingWidth = -1; // width handle being dragged
this.input.on('pointerdown', (p) => {
if (!this.onBoard(p)) return;
const [wx, wy] = this.toWorld(p.x, p.y);
this.handleClick(wx, wy, p);
});
this.input.on('pointermove', (p) => {
if (this.dragging >= 0) {
const [wx, wy] = this.toWorld(p.x, p.y);
const pt = this.track.spline[this.dragging];
pt.x = Math.round(Phaser.Math.Clamp(wx, 160, this.track.world - 160));
pt.y = Math.round(Phaser.Math.Clamp(wy, 160, this.track.world - 160));
this.markDirty();
} else if (this.draggingWidth >= 0) {
const [wx, wy] = this.toWorld(p.x, p.y);
const pt = this.track.spline[this.draggingWidth];
pt.w = Math.round(Phaser.Math.Clamp(Math.hypot(wx - pt.x, wy - pt.y), 50, 260));
this.markDirty();
}
});
this.input.on('pointerup', () => {
if (this.dragging >= 0 || this.draggingWidth >= 0) this.rebuildModel();
this.dragging = -1;
this.draggingWidth = -1;
});
}
bindKeys() {
this.input.keyboard.on('keydown-Z', () => this.undo());
this.input.keyboard.on('keydown-ENTER', () => this.closeDraft());
this.input.keyboard.on('keydown-DELETE', () => this.deleteSelected());
this.input.keyboard.on('keydown-BACKSPACE', () => this.deleteSelected());
this.input.keyboard.on('keydown-OPEN_BRACKET', () => this.nudgeWidth(-10));
this.input.keyboard.on('keydown-CLOSED_BRACKET', () => this.nudgeWidth(10));
}
nudgeWidth(d) {
if (this.selected < 0) return;
const pt = this.track.spline[this.selected];
pt.w = Phaser.Math.Clamp(pt.w + d, 50, 260);
this.markDirty();
this.rebuildModel();
}
deleteSelected() {
if (this.selected < 0 || this.track.spline.length <= 4) return;
this.pushUndo();
this.track.spline.splice(this.selected, 1);
if (this.track.startIndex >= this.track.spline.length) this.track.startIndex = 0;
this.selected = -1;
this.rebuildModel();
}
handleClick(wx, wy, pointer) {
const spline = this.track.spline;
const nearPoint = () => {
let best = -1;
let bd = 90 * (this.track.world / BOARD_SIZE) / 10; // ~40 world units
spline.forEach((pt, i) => {
const d = Math.hypot(pt.x - wx, pt.y - wy);
if (d < bd) { bd = d; best = i; }
});
return best;
};
switch (this.tool) {
case 'move': {
const i = nearPoint();
if (i >= 0) {
// Width handle sits at the point's road edge; grabbing near the edge
// ring drags width, grabbing the center drags position.
const pt = spline[i];
const d = Math.hypot(pt.x - wx, pt.y - wy);
this.selected = i;
if (Math.abs(d - pt.w) < 26) this.draggingWidth = i;
else this.dragging = i;
this.pushUndo();
} else this.selected = -1;
this.draw();
break;
}
case 'point': {
this.pushUndo();
// Insert on the nearest segment (projected), else append after nearest.
let bestSeg = -1;
let bd = Infinity;
for (let i = 0; i < spline.length; i += 1) {
const a = spline[i];
const b = spline[(i + 1) % spline.length];
const d = distToSeg(wx, wy, a, b);
if (d < bd) { bd = d; bestSeg = i; }
}
const w = Math.round((spline[bestSeg].w + spline[(bestSeg + 1) % spline.length].w) / 2);
spline.splice(bestSeg + 1, 0, { x: Math.round(wx), y: Math.round(wy), w });
if (this.track.startIndex > bestSeg) this.track.startIndex += 1;
this.selected = bestSeg + 1;
this.rebuildModel();
break;
}
case 'start': {
const i = nearPoint();
if (i >= 0) {
this.pushUndo();
this.track.startIndex = i;
this.rebuildModel();
}
break;
}
case 'itemrow':
case 'boost':
case 'coin': {
if (!this.model) break;
const proj = projectToSpline(this.model, wx, wy);
if (proj.d > 300) break;
this.pushUndo();
if (this.tool === 'itemrow') {
this.track.itemRows.push({ s: Math.round(proj.s), count: 4 });
} else if (this.tool === 'boost') {
this.track.boosts.push({ s: Math.round(proj.s), lane: Math.round(Phaser.Math.Clamp(proj.laneT, -0.7, 0.7) * 10) / 10 });
} else {
this.track.coins.push({ x: Math.round(wx), y: Math.round(wy) });
}
this.rebuildModel();
break;
}
case 'water':
case 'deep':
case 'wall':
this.draftPoly.push([Math.round(wx), Math.round(wy)]);
if (pointer.event?.detail >= 2) this.closeDraft(); // double click also closes
this.draw();
break;
case 'decor': {
this.pushUndo();
const list = this.rules?.themes?.[this.track.theme]?.decor ?? ['tree'];
const sprite = list[(this.track.decor.length) % list.length];
this.track.decor.push({ sprite, x: Math.round(wx), y: Math.round(wy) });
this.markDirty();
this.draw();
break;
}
case 'hazard':
this.pushUndo();
this.track.hazards.push({ type: 'pipe', x: Math.round(wx), y: Math.round(wy) });
this.draw();
break;
case 'delete': this.deleteNearest(wx, wy); break;
default: break;
}
}
closeDraft() {
if (this.draftPoly.length < 2) { this.draftPoly = []; this.draw(); return; }
this.pushUndo();
if (this.tool === 'wall') {
this.track.walls.push({ pts: this.draftPoly, closed: false });
} else if (this.draftPoly.length >= 3) {
this.track.surfaces.push({ type: this.tool === 'water' ? 'water' : 'deep', poly: this.draftPoly });
}
this.draftPoly = [];
this.rebuildModel();
}
deleteNearest(wx, wy) {
const candidates = [];
this.track.itemRows.forEach((row, i) => {
const p = this.model ? roadPoint(this.model, row.s, 0) : null;
if (p) candidates.push({ d: Math.hypot(p.x - wx, p.y - wy), del: () => this.track.itemRows.splice(i, 1) });
});
this.track.boosts.forEach((bp, i) => {
const p = this.model ? roadPoint(this.model, bp.s, bp.lane) : null;
if (p) candidates.push({ d: Math.hypot(p.x - wx, p.y - wy), del: () => this.track.boosts.splice(i, 1) });
});
this.track.coins.forEach((c, i) => candidates.push({ d: Math.hypot(c.x - wx, c.y - wy), del: () => this.track.coins.splice(i, 1) }));
this.track.decor.forEach((dc, i) => candidates.push({ d: Math.hypot(dc.x - wx, dc.y - wy), del: () => this.track.decor.splice(i, 1) }));
this.track.hazards.forEach((hz, i) => candidates.push({ d: Math.hypot(hz.x - wx, hz.y - wy), del: () => this.track.hazards.splice(i, 1) }));
this.track.surfaces.forEach((sf, i) => {
const pts = sf.poly ?? [];
for (const [px, py] of pts) candidates.push({ d: Math.hypot(px - wx, py - wy), del: () => this.track.surfaces.splice(i, 1) });
});
this.track.walls.forEach((wl, i) => {
for (const [px, py] of wl.pts) candidates.push({ d: Math.hypot(px - wx, py - wy), del: () => this.track.walls.splice(i, 1) });
});
candidates.sort((a, b) => a.d - b.d);
if (candidates[0] && candidates[0].d < 220) {
this.pushUndo();
candidates[0].del();
this.rebuildModel();
}
}
// ── Undo / model / preview ───────────────────────────────────────────────
pushUndo() {
this.undoStack.push(JSON.stringify(this.track));
if (this.undoStack.length > 60) this.undoStack.shift();
}
undo() {
const snap = this.undoStack.pop();
if (!snap) return;
this.track = JSON.parse(snap);
this.selected = -1;
this.rebuildModel();
}
markDirty() {
this.previewDirty = true;
this.previewTimer = 0;
this.draw();
}
rebuildModel() {
try {
this.model = buildTrackModel(this.track);
this.issues = validateTrack(this.model);
} catch (err) {
this.model = null;
this.issues = [`track invalid: ${err.message}`];
}
this.issueText?.setText(this.issues.length ? `⚠ ${this.issues.join(' • ')}` : '');
this.markDirty();
}
refreshPreview() {
if (!this.model) return;
const theme = this.rules?.themes?.[this.track.theme] ?? {
terrain: '#3a5a35', terrainSpeckle: '#4a6a3c', road: '#6e6252', roadEdge: '#524a3e',
water: '#3a5f52', deep: '#233a2e', fog: '#c2d0a8',
};
const canvas = rasterizeTrack(this.model, theme, 1024);
if (this.textures.exists('superkart-editor-preview')) this.textures.remove('superkart-editor-preview');
this.textures.addCanvas('superkart-editor-preview', canvas);
this.previewImg?.destroy();
this.previewImg = this.add.image(BOARD_X + BOARD_SIZE / 2, BOARD_Y + BOARD_SIZE / 2, 'superkart-editor-preview')
.setDisplaySize(BOARD_SIZE, BOARD_SIZE).setDepth(1);
}
update(time, delta) {
if (this.previewDirty) {
this.previewTimer += delta;
if (this.previewTimer > 350) { // debounce: rasterize after edits settle
this.previewDirty = false;
this.refreshPreview();
}
}
}
// ── Overlay drawing ──────────────────────────────────────────────────────
draw() {
const g = this.g;
g.clear();
const spline = this.track.spline;
// Centerline through the model samples (smooth) or raw points as fallback.
g.lineStyle(2, 0x68d0ff, 0.8);
const pts = this.model?.samples ?? spline;
g.beginPath();
pts.forEach((p, i) => {
const [bx, by] = this.toBoard(p.x, p.y);
if (i) g.lineTo(bx, by); else g.moveTo(bx, by);
});
g.closePath();
g.strokePath();
// Control points + width rings + start marker.
spline.forEach((pt, i) => {
const [bx, by] = this.toBoard(pt.x, pt.y);
const k = BOARD_SIZE / this.track.world;
g.lineStyle(1.5, i === this.selected ? 0xffd028 : 0xffffff, 0.5);
g.strokeCircle(bx, by, pt.w * k);
g.fillStyle(i === this.track.startIndex ? 0x38b048 : i === this.selected ? 0xffd028 : 0xffffff, 1);
g.fillCircle(bx, by, i === this.selected ? 7 : 5);
});
// Item rows / boosts / coins.
if (this.model) {
g.fillStyle(0xb078ff, 1);
for (const row of this.track.itemRows) {
const p = roadPoint(this.model, row.s, 0);
const [bx, by] = this.toBoard(p.x, p.y);
g.fillRect(bx - 5, by - 5, 10, 10);
}
g.fillStyle(0xffd028, 1);
for (const bp of this.track.boosts) {
const p = roadPoint(this.model, bp.s, bp.lane);
const [bx, by] = this.toBoard(p.x, p.y);
g.fillTriangle(bx - 6, by + 5, bx + 6, by + 5, bx, by - 7);
}
}
g.fillStyle(0xffe878, 1);
for (const c of this.track.coins) {
const [bx, by] = this.toBoard(c.x, c.y);
g.fillCircle(bx, by, 3);
}
g.fillStyle(0x88ff88, 0.9);
for (const dc of this.track.decor) {
const [bx, by] = this.toBoard(dc.x, dc.y);
g.fillRect(bx - 4, by - 4, 8, 8);
}
g.fillStyle(0xff8888, 0.9);
for (const hz of this.track.hazards) {
const [bx, by] = this.toBoard(hz.x, hz.y);
g.fillCircle(bx, by, 5);
}
// Draft polygon in progress.
if (this.draftPoly.length) {
g.lineStyle(2, this.tool === 'wall' ? 0xff6a00 : 0x68d0ff, 1);
g.beginPath();
this.draftPoly.forEach(([x, y], i) => {
const [bx, by] = this.toBoard(x, y);
if (i) g.lineTo(bx, by); else g.moveTo(bx, by);
});
g.strokePath();
for (const [x, y] of this.draftPoly) {
const [bx, by] = this.toBoard(x, y);
g.fillStyle(0xffffff, 1);
g.fillCircle(bx, by, 3);
}
}
}
// ── Test play / export ───────────────────────────────────────────────────
testPlay() {
if (this.issues.length) {
playSound(this, SFX.MASTERMIND_DENIED);
return;
}
this.registry.set('superkart-editor-state', JSON.parse(JSON.stringify(this.track)));
this.scene.start('SuperKartGame', {
game: { slug: 'superkart', name: 'Super Kart' },
testTrack: JSON.parse(JSON.stringify(this.track)),
returnToEditor: true,
});
}
download(name, obj) {
const a = document.createElement('a');
a.href = URL.createObjectURL(new Blob([`${JSON.stringify(obj, null, 2)}\n`], { type: 'application/json' }));
a.download = name;
a.click();
setTimeout(() => URL.revokeObjectURL(a.href), 5000);
}
exportTrack() {
if (this.issues.length) {
playSound(this, SFX.MASTERMIND_DENIED);
return;
}
this.download(`${this.track.id}.json`, this.track);
playSound(this, SFX.UI_CHIME);
this.flash(`Saved ${this.track.id}.json — drop it into ${GAMEDATA}/`);
}
exportCups() {
const idx = JSON.parse(JSON.stringify(this.cupsIndex ?? { version: 1, cups: [], tracks: [] }));
idx.tracks = (idx.tracks ?? []).filter((t) => t.id !== this.track.id);
idx.tracks.push({ id: this.track.id, name: this.track.name, theme: this.track.theme, file: `${this.track.id}.json` });
// If no cup lists this track yet, append it to the emptiest cup.
const inCup = (idx.cups ?? []).some((c) => c.tracks.includes(this.track.id));
if (!inCup && idx.cups?.length) {
idx.cups.sort((a, b) => a.tracks.length - b.tracks.length)[0].tracks.push(this.track.id);
idx.cups.sort((a, b) => a.id.localeCompare(b.id));
}
this.download('cups.json', idx);
playSound(this, SFX.UI_CHIME);
this.flash(`Saved cups.json — drop it into ${GAMEDATA}/ (review cup assignment)`);
}
flash(msg) {
this.flashText?.destroy();
this.flashText = this.add.text(BOARD_X + BOARD_SIZE / 2, BOARD_Y + 24, msg, {
fontFamily: FONT, fontSize: '20px', color: '#ffd028',
backgroundColor: '#000000cc', padding: { x: 12, y: 6 },
}).setOrigin(0.5).setDepth(20);
this.time.delayedCall(4200, () => this.flashText?.destroy());
}
}
function distToSeg(x, y, a, b) {
const abx = b.x - a.x;
const aby = b.y - a.y;
const len2 = abx * abx + aby * aby || 1e-6;
const t = Phaser.Math.Clamp(((x - a.x) * abx + (y - a.y) * aby) / len2, 0, 1);
return Math.hypot(x - (a.x + abx * t), y - (a.y + aby * t));
}