Switchyard Seven Preview
by NovaCaptain32483 lines19.8 KB
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="description" content="Read each train's letter and set the two switches before it passes. Keep every shipment on its route.">
<title>Switchyard Seven · Preview</title>
<style>:root {
color-scheme: dark;
--accent: #ffd492;
--ink: #2e3341;
--paper: #f3f6ff;
--dim: #bcc9dc;
font: 16px/1.5 system-ui, sans-serif;
}
* { box-sizing: border-box; }
body {
margin: 0;
background: radial-gradient(ellipse at 78% 0%, color-mix(in srgb, var(--ink), var(--accent) 15%), var(--ink) 60%);
color: var(--paper);
}
main { max-width: 920px; margin: auto; padding: clamp(10px, 3vw, 30px); }
header { display: flex; justify-content: space-between; align-items: end; gap: .75rem; margin-bottom: .75rem; flex-wrap: wrap; }
h1, h2, p { margin: 0; }
h1 { font-size: clamp(1.5rem, 5vw, 2.7rem); line-height: 1.05; letter-spacing: -.045em; }
h2 { font-size: clamp(1.1rem, 5vw, 2.4rem); line-height: 1.05; letter-spacing: -.04em; }
.kicker { color: var(--accent); font: 750 .72rem/1.2 ui-monospace, monospace; letter-spacing: .12em; margin-bottom: .38rem; }
.tools { display: flex; gap: .4rem; flex-wrap: wrap; }
button {
border: 1px solid color-mix(in srgb, var(--accent), transparent 66%);
background: var(--ink);
color: var(--paper);
border-radius: 8px;
font: 700 .82rem/1.15 system-ui, sans-serif;
padding: .48rem .67rem;
min-height: 40px;
cursor: pointer;
}
button.primary { color: var(--ink); background: var(--accent); }
button:hover:enabled { border-color: var(--accent); filter: brightness(1.13); }
button:focus-visible, canvas:focus-visible, summary:focus-visible { outline: 3px solid var(--accent); outline-offset: 2px; }
button:disabled { opacity: .55; cursor: default; }
.cabinet { position: relative; overflow: clip; border: 1px solid color-mix(in srgb, var(--accent), transparent 62%); border-radius: 14px; background: var(--ink); box-shadow: 0 14px 60px #0006; }
canvas { display: block; width: 100%; height: auto; touch-action: none; }
#overlay { position: absolute; inset: 0; display: grid; place-items: center; padding: 8px; background: #07101abd; overflow: auto; }
#overlay[hidden] { display: none; }
.card {
width: min(100%, 470px);
padding: clamp(9px, 2.4vw, 24px);
background: color-mix(in srgb, var(--ink), #202e42 22%);
border: 1px solid color-mix(in srgb, var(--accent), transparent 54%);
border-radius: 12px;
}
#message { font-size: clamp(.78rem, 2.7vw, 1rem); margin: .45rem 0 .55rem; }
#record { margin-top: .45rem; color: var(--dim); font-size: .74rem; }
.status { display: flex; gap: .3rem 1rem; flex-wrap: wrap; justify-content: space-between; padding: .62rem .12rem; font-size: .85rem; font-weight: 700; }
#goal { color: var(--accent); }
#touch button { min-width: 48px; min-height: 44px; touch-action: none; }
#help, details { color: var(--dim); font-size: .82rem; margin: .5rem .12rem; }
@media (max-width: 420px) {
#overlay { align-items: start; }
#overlay button { min-height: 34px; padding: .35rem .48rem; font-size: .74rem; }
.card { padding: 8px; }
#message { margin: .27rem 0 .36rem; }
}
</style>
</head>
<body>
<main>
<header>
<div><p class="kicker">D3MONGAMES / TRAIN DISPATCH / PREVIEW</p><h1>Switchyard Seven · Preview</h1></div>
<div class="tools"><button id="audio" aria-pressed="false">Sound off</button><button id="pause" disabled>Pause</button></div>
</header>
<section class="cabinet" aria-label="Game">
<canvas id="board" width="720" height="432" tabindex="0" aria-label="Switchyard Seven · Preview playfield"></canvas>
<div id="overlay">
<section class="card" aria-labelledby="card-title">
<p class="kicker" id="eyebrow">PLAYABLE PREVIEW</p>
<h2 id="card-title">Switchyard Seven · Preview</h2>
<p id="message">Read each train's letter and set the two switches before it passes. Keep every shipment on its route.</p>
<div class="tools" id="choices"></div>
<p id="record"></p>
</section>
</div>
</section>
<div class="status"><p id="status">Choose a game mode.</p><p id="goal"></p></div>
<div id="touch" class="tools" aria-label="Game controls"></div>
<p id="help">Toggle Switch 1 with Space and Switch 2 with X, or tap either switch. A goes up at Switch 1. B goes straight at both. C goes down at Switch 2.</p>
<details><summary>How progress works</summary><p>This preview includes one stage. Replay to improve your score and medals. The full edition includes 12 campaign stages and a daily challenge.</p></details>
<noscript>JavaScript is required to play.</noscript>
</main>
<script>const preview = true;
const routes = ["A", "B", "C"];
const colors = ["#ffd492", "#a8f1c7", "#bcd5ff"];
const game = {
slug: "switchyard-seven",
title: "Switchyard Seven",
genre: "TRAIN DISPATCH",
pitch: "Read each train's letter and set the two switches before it passes. Keep every shipment on its route.",
controls: "Toggle Switch 1 with Space and Switch 2 with X, or tap either switch. A goes up at Switch 1. B goes straight at both. C goes down at Switch 2.",
accent: "#ffd492",
ink: "#2e3341",
levels: 12,
buttons: [["act", "Switch 1"], ["mark", "Switch 2"]],
create() { return {"timetable":[{"time":1,"route":2,"speed":119.58909163158387},{"time":2.4864020029455425,"route":0,"speed":117.68683447455987},{"time":4.057556398846209,"route":2,"speed":112.59795349370688},{"time":5.610499970447273,"route":1,"speed":117.36459613312036},{"time":7.097798069026322,"route":1,"speed":112.23173177847639},{"time":8.597569430209697,"route":0,"speed":113.23438110295683},{"time":10.073155580814928,"route":2,"speed":121.04697651276365},{"time":11.558166163302959,"route":1,"speed":113.97867701388896},{"time":13.176022650822997,"route":0,"speed":109.83223694888875},{"time":14.795920568853617,"route":2,"speed":110.4139668229036}],"t":0,"queued":0,"trains":[],"switches":[false,false],"delivered":0,"lost":0,"combo":0,"score":0,"flash":0}; },
input(s, action, chime) {
const index = action === "act" ? 0 : action === "mark" ? 1 : -1;
if (index >= 0) {
s.switches[index] = !s.switches[index];
chime(index ? 475 : 390);
}
},
tap(s, x, _y, chime) { this.input(s, x < 355 ? "act" : "mark", chime); },
update(s, dt, _down, chime) {
s.t += dt;
s.flash = Math.max(0, s.flash - dt);
while (s.queued < s.timetable.length && s.timetable[s.queued].time <= s.t) {
s.trains.push({ ...s.timetable[s.queued++], x: -25, branch: -1 });
}
for (const train of s.trains) {
const old = train.x;
train.x += train.speed * dt;
if (old < 241 && train.x >= 241 && s.switches[0]) train.branch = 0;
if (old < 454 && train.x >= 454 && train.branch < 0) train.branch = s.switches[1] ? 2 : 1;
if (train.x < 682) continue;
if (train.branch === train.route) {
s.delivered++;
s.combo++;
s.score += 175 + s.combo * 16;
chime(580 + train.route * 110);
} else {
s.lost++;
s.combo = 0;
s.flash = .4;
chime(190);
}
}
s.trains = s.trains.filter(train => train.x < 682);
if (s.lost >= 4 || s.delivered + s.lost === s.timetable.length) {
const clear = s.lost < 4;
return { clear, medals: s.lost === 0 ? 3 : s.lost === 1 ? 2 : 1, score: s.score,
message: clear ? s.delivered + " trains reached the right destination. Long runs build a score bonus." : "Four trains went off route. Switches lock each train's route as it passes." };
}
},
status(s) { return s.delivered + "/" + s.timetable.length + " delivered · " + s.lost + "/4 wrong routes · " + s.combo + " chain"; },
draw(s, { box, circle, line, label }) {
box(0, 0, 720, 432, s.flash ? "#513746" : "#303d4c");
for (let i = 0; i < 24; i++) {
const x = 25 + i * 29;
line(x, 204, x, 230, 2, "#625967");
}
line(0, 216, 692, 216, 7, "#abb5c2");
line(241, 216, 323, 115, 7, "#abb5c2");
line(323, 115, 692, 115, 7, "#abb5c2");
line(454, 216, 536, 317, 7, "#abb5c2");
line(536, 317, 692, 317, 7, "#abb5c2");
line(236, 216, s.switches[0] ? 271 : 276, s.switches[0] ? 182 : 216, 5, "#ffd492");
line(450, 216, s.switches[1] ? 482 : 490, s.switches[1] ? 250 : 216, 5, "#ffd492");
for (const [index, x] of [241, 454].entries()) {
box(x - 62, 251, 124, 40, "#212d3c", 8);
label("SWITCH " + (index + 1), x, 272, 14, "#ffd492", "center");
}
for (const [index, y] of [115, 216, 317].entries()) {
box(665, y - 24, 50, 48, colors[index], 8);
label(routes[index], 690, y, 24, "#293245", "center");
}
for (const train of s.trains) {
const { x } = train;
let y = 216;
if (train.branch === 0) y -= Math.max(0, Math.min(101, (x - 241) / 82 * 101));
if (train.branch === 2) y += Math.max(0, Math.min(101, (x - 454) / 82 * 101));
box(x - 21, y - 16, 42, 28, colors[train.route], 6);
circle(x - 12, y + 11, 5, "#25303b");
circle(x + 12, y + 11, 5, "#25303b");
label(routes[train.route], x, y - 4, 16, "#25303b", "center");
}
const incoming = s.timetable[s.queued];
if (incoming) label("NEXT TRAIN " + routes[incoming.route], 25, 34, 15, colors[incoming.route]);
}
};
const board = document.querySelector("#board");
const ctx = board.getContext("2d");
const ui = Object.fromEntries(["overlay", "eyebrow", "card-title", "message", "choices", "record", "status", "goal", "touch", "audio", "pause"].map(id => [id, document.getElementById(id)]));
const campaignCount = preview ? 1 : game.levels;
const saveKey = "d3mg-collection-v1:" + game.slug + (preview ? ":preview" : "");
const dateKey = date => date.toISOString().slice(0, 10);
const today = () => dateKey(new Date());
function hash(text) {
let value = 2166136261;
for (const character of text) value = Math.imul(value ^ character.charCodeAt(0), 16777619);
return value >>> 0;
}
function random(seed) {
return () => {
seed = (seed + 0x6d2b79f5) | 0;
let value = Math.imul(seed ^ seed >>> 15, seed | 1);
value ^= value + Math.imul(value ^ value >>> 7, value | 61);
return ((value ^ value >>> 14) >>> 0) / 4294967296;
};
}
function readProgress() {
const empty = { levels: {}, days: {}, streak: 0, last: "" };
try {
const record = JSON.parse(localStorage.getItem(saveKey));
if (record?.levels && record.days) return { ...empty, ...record };
} catch {}
return empty;
}
function saveProgress() {
try { localStorage.setItem(saveKey, JSON.stringify(progress)); } catch {}
}
function box(x, y, width, height, color, radius = 0) {
ctx.fillStyle = color;
ctx.beginPath();
ctx.roundRect(x, y, width, height, radius);
ctx.fill();
}
function circle(x, y, radius, color) {
ctx.fillStyle = color;
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2);
ctx.fill();
}
function line(x, y, endX, endY, width, color) {
ctx.strokeStyle = color;
ctx.lineWidth = width;
ctx.lineCap = "round";
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(endX, endY);
ctx.stroke();
}
function label(text, x, y, size, color = "#f3f6ff", align = "left") {
ctx.fillStyle = color;
ctx.textAlign = align;
ctx.textBaseline = "middle";
ctx.font = "700 " + size + "px system-ui, sans-serif";
ctx.fillText(text, x, y);
}
const art = { ctx, box, circle, line, label, accent: game.accent, ink: game.ink };
const progress = readProgress();
const down = new Set();
const actions = new Map([
["ArrowLeft", "left"], ["a", "left"], ["ArrowRight", "right"], ["d", "right"],
["ArrowUp", "up"], ["w", "up"], ["ArrowDown", "down"], ["s", "down"],
[" ", "act"], ["Enter", "act"], ["z", "undo"], ["x", "mark"]
]);
for (let digit = 1; digit <= 9; digit++) actions.set(String(digit), "digit" + digit);
actions.set("Backspace", "erase");
actions.set("Delete", "erase");
let audioContext, soundOn = false;
function chime(frequency = 560) {
if (!soundOn || !audioContext || audioContext.state !== "running") return;
const note = audioContext.createOscillator();
const volume = audioContext.createGain();
const time = audioContext.currentTime;
note.type = "sine";
note.frequency.value = frequency;
volume.gain.setValueAtTime(.065, time);
volume.gain.exponentialRampToValueAtTime(.001, time + .14);
note.connect(volume).connect(audioContext.destination);
note.start(time);
note.stop(time + .15);
}
let phase = "menu";
let level = 1;
let daily = false;
let date = today();
let state;
function highestStage() {
let stage = 1;
while (stage < campaignCount && progress.levels[stage]) stage++;
return stage;
}
function prepare(stage, isDaily, day) {
level = stage;
daily = isDaily;
date = day;
const seed = hash(game.slug + "/" + (isDaily ? "daily/" + day : "stage/" + stage));
state = game.create({ stage, daily: isDaily, seed, rng: random(seed) });
down.clear();
}
function showCard(heading, title, message, buttons, record = "") {
ui.eyebrow.textContent = heading;
ui["card-title"].textContent = title;
ui.message.textContent = message;
ui.record.textContent = record;
ui.choices.replaceChildren();
for (const [name, callback, disabled] of buttons) {
const button = document.createElement("button");
button.type = "button";
button.textContent = name;
button.disabled = !!disabled;
if (!ui.choices.children.length) button.className = "primary";
button.addEventListener("click", callback);
ui.choices.append(button);
}
ui.overlay.hidden = false;
}
function menu(focus = true) {
phase = "menu";
prepare(highestStage(), false, today());
ui.pause.disabled = true;
if (preview) {
showCard("PLAYABLE PREVIEW", game.title, game.pitch, [["Play preview", () => begin(1, false)]], "One stage · Keyboard and touch");
if (focus) ui.choices.querySelector("button").focus();
return;
}
const earned = Object.values(progress.levels).reduce((sum, entry) => sum + entry.medals, 0);
const count = Object.keys(progress.levels).length;
const dailyRecord = progress.days[today()];
const yesterday = new Date();
yesterday.setUTCDate(yesterday.getUTCDate() - 1);
const activeStreak = progress.last === today() || progress.last === dateKey(yesterday) ? progress.streak : 0;
showCard("CAMPAIGN AND DAILY CHALLENGE", game.title, game.pitch, [
[count ? "Continue stage " + highestStage() : "Play stage 1", () => begin(highestStage(), false)],
["Daily challenge", () => begin(3, true)],
["Stage select", chooseStage, count === 0]
], count + "/" + campaignCount + " stages cleared · " + earned + "/" + (campaignCount * 3) + " medals" +
(dailyRecord ? " · Daily best " + dailyRecord.score : "") +
(activeStreak ? " · " + activeStreak + "-day streak" : ""));
if (focus) ui.choices.querySelector("button").focus();
}
function chooseStage() {
const buttons = [];
for (let stage = 1; stage <= campaignCount; stage++) {
const result = progress.levels[stage];
buttons.push(["Stage " + stage + (result ? " · " + "★".repeat(result.medals) : ""), () => begin(stage, false), stage > highestStage()]);
}
buttons.push(["Menu", menu]);
showCard("CAMPAIGN", "Choose a stage", "Clear each stage to open the next. Replay earlier stages to improve your medals.", buttons);
ui.choices.querySelector("button").focus();
}
function begin(stage, isDaily, day = today()) {
prepare(stage, isDaily, day);
phase = "play";
ui.pause.disabled = false;
ui.pause.textContent = "Pause";
ui.overlay.hidden = true;
board.focus({ preventScroll: true });
chime(420);
}
function pause() {
if (phase === "paused") {
phase = "play";
ui.overlay.hidden = true;
ui.pause.textContent = "Pause";
board.focus({ preventScroll: true });
return;
}
if (phase !== "play") return;
phase = "paused";
down.clear();
ui.pause.textContent = "Resume";
showCard("TAKE A BREAK", "Paused", "Your run is waiting.", [
["Resume", pause], ["Restart", () => begin(level, daily, date)], ["Menu", menu]
]);
ui.choices.querySelector("button").focus();
}
function finish(result) {
phase = "result";
down.clear();
ui.pause.disabled = true;
if (result.clear || daily) {
const shelf = daily ? progress.days : progress.levels;
const id = daily ? date : level;
const old = shelf[id];
shelf[id] = { score: Math.max(old?.score ?? 0, result.score), medals: Math.max(old?.medals ?? 0, result.clear ? result.medals : 0) };
if (daily && result.clear && (!progress.last || date > progress.last)) {
const previous = new Date(date + "T00:00:00Z");
previous.setUTCDate(previous.getUTCDate() - 1);
progress.streak = dateKey(previous) === progress.last ? progress.streak + 1 : 1;
progress.last = date;
}
saveProgress();
}
chime(result.clear ? 810 : 210);
const buttons = [["Replay", () => begin(level, daily, date)], ["Menu", menu]];
if (result.clear && !daily && level < campaignCount) buttons.unshift(["Next stage", () => begin(level + 1, false)]);
showCard(preview ? "PLAYABLE PREVIEW" : daily ? "DAILY CHALLENGE" : "STAGE " + level, result.clear ? "Challenge cleared" : "Run complete",
result.message, buttons, "Score " + result.score + (result.clear ? " · " + "★".repeat(result.medals) + "☆".repeat(3 - result.medals) : ""));
ui.choices.querySelector("button").focus();
}
function trigger(action) {
if (phase !== "play") return;
if (!down.has(action)) game.input?.(state, action, chime);
down.add(action);
}
document.addEventListener("keydown", event => {
if (event.key === "Escape" || event.key.toLowerCase() === "p") {
if (!event.repeat && (phase === "play" || phase === "paused")) {
event.preventDefault();
pause();
}
return;
}
if (phase !== "play" || event.target.closest("button, summary")) return;
const action = actions.get(event.key.length === 1 ? event.key.toLowerCase() : event.key);
if (action) {
event.preventDefault();
trigger(action);
}
});
document.addEventListener("keyup", event => down.delete(actions.get(event.key.length === 1 ? event.key.toLowerCase() : event.key)));
document.addEventListener("visibilitychange", () => { if (document.hidden && phase === "play") pause(); });
window.addEventListener("blur", () => down.clear());
board.addEventListener("pointerdown", event => {
if (phase !== "play") return;
const bounds = board.getBoundingClientRect();
game.tap?.(state, (event.clientX - bounds.x) * 720 / bounds.width, (event.clientY - bounds.y) * 432 / bounds.height, chime);
});
for (const [action, text] of game.buttons) {
const button = document.createElement("button");
button.type = "button";
button.textContent = text;
button.addEventListener("pointerdown", event => {
event.preventDefault();
button.setPointerCapture(event.pointerId);
trigger(action);
});
for (const eventName of ["pointerup", "pointercancel", "lostpointercapture"]) {
button.addEventListener(eventName, () => down.delete(action));
}
button.addEventListener("click", event => {
if (event.detail === 0) { trigger(action); down.delete(action); }
});
ui.touch.append(button);
}
ui.pause.addEventListener("click", pause);
ui.audio.addEventListener("click", async () => {
soundOn = !soundOn;
if (soundOn && window.AudioContext) {
audioContext ??= new AudioContext();
await audioContext.resume().catch(() => {});
chime();
}
ui.audio.textContent = soundOn ? "Sound on" : "Sound off";
ui.audio.setAttribute("aria-pressed", soundOn);
});
let last = performance.now();
function frame(now) {
const dt = Math.min((now - last) / 1000, .05);
last = now;
if (phase === "play") {
const result = game.update(state, dt, down, chime);
if (result) finish(result);
}
game.draw(state, art);
const status = game.status(state);
if (ui.status.textContent !== status) ui.status.textContent = status;
ui.goal.textContent = preview ? "Preview · Stage 1" : daily ? "Daily · " + date : "Campaign · " + level + "/" + campaignCount;
requestAnimationFrame(frame);
}
menu(false);
requestAnimationFrame(frame);
</script>
</body>
</html>
Game Source: Switchyard Seven Preview
Creator: NovaCaptain32
Libraries: none
Complexity: complex (483 lines, 19.8 KB)
The full source code is displayed above on this page.
Remix Instructions
To remix this game, copy the source code above and modify it. Add a ARCADELAB header at the top with "remix_of: switchyard-seven-preview-novacaptain32" to link back to the original. Then publish at arcadelab.ai/publish.