(() => { "use strict"; const $ = (selector, root = document) => root.querySelector(selector); const $$ = (selector, root = document) => Array.from(root.querySelectorAll(selector)); const room = $("#room"); const shell = $("#game-shell"); const log = $("#log"); const chips = $("#chips"); const progressText = $("#progress-text"); const progressPercent = $("#progress-percent"); const progressTrack = $("#progress-track"); const progressBar = $("#progress-bar"); const modal = $("#modal"); const voucherCode = $("#voucher-code"); const voucherRecipient = $("#voucher-recipient"); const voucherDate = $("#voucher-date"); const voucherNote = $("#voucher-note"); const copyButton = $("#copy-code"); const playAgainButton = $("#play-again"); const soundButton = $("#sound-toggle"); const confettiCanvas = $("#confetti"); const confettiContext = confettiCanvas.getContext("2d"); const reduceMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches; const GLASS_OBJECTS = new Set(["spiegel", "klok"]); const DEBRIS_COLORS = { spiegel: ["#d9f2f7", "#a9d6e1", "#ffffff", "#7fb3c2"], schilderij: ["#c99a3f", "#4c8b9b", "#f8d9a0", "#6b4425"], klok: ["#f3e4c1", "#c99a3f", "#3d2a1c"], kast: ["#7b5330", "#b9553f", "#d09a45", "#4f7d75"], zetel: ["#4e837d", "#6b9d96", "#39716b"], tafel: ["#8a5b34", "#6d4527", "#d6b15b", "#5f3b20"], deur: ["#8a5b34", "#744924", "#c99a3f"], plant: ["#b2603d", "#4f8747", "#67a05a", "#8d4328"] }; const TOOL_LABELS = { hamer: "hamer", koevoet: "koevoet" }; const HIT_LINES = { hamer: ["Bonk!", "Krak!", "Goeie tik!", "Dat klinkt bevredigend."], koevoet: ["Krak!", "Wrikken maar.", "Iets lossers.", "De vijzen geven mee."] }; const state = { tool: "hamer", config: null, objects: new Map(), brokenCount: 0, soundOn: true, finished: false, audio: null, lastFocus: null, confettiFrame: null, confettiParticles: [] }; try { state.soundOn = window.localStorage.getItem("jos-sloop-geluid") !== "uit"; } catch { state.soundOn = true; } function pick(list) { return list[Math.floor(Math.random() * list.length)]; } function wait(ms) { return new Promise((resolve) => window.setTimeout(resolve, ms)); } function setLog(message, kind = "normal") { log.textContent = message; log.classList.toggle("is-warning", kind === "warning"); log.classList.toggle("is-done", kind === "done"); } function updateSoundButton() { soundButton.setAttribute("aria-pressed", String(state.soundOn)); const label = state.soundOn ? "Geluid dempen" : "Geluid aanzetten"; soundButton.setAttribute("aria-label", label); soundButton.title = label; } function ensureAudio() { if (!state.soundOn) { return null; } if (!state.audio) { const AudioContextClass = window.AudioContext || window.webkitAudioContext; if (!AudioContextClass) { return null; } try { state.audio = new AudioContextClass(); } catch { return null; } } if (state.audio.state === "suspended") { state.audio.resume().catch(() => {}); } return state.audio; } function playTone({ freq = 200, endFreq = freq, type = "sine", duration = 0.16, gain = 0.15, delay = 0 }) { const context = ensureAudio(); if (!context) { return; } const start = context.currentTime + delay; const oscillator = context.createOscillator(); const volume = context.createGain(); oscillator.type = type; oscillator.frequency.setValueAtTime(Math.max(20, freq), start); oscillator.frequency.exponentialRampToValueAtTime(Math.max(20, endFreq), start + duration); volume.gain.setValueAtTime(0.0001, start); volume.gain.exponentialRampToValueAtTime(Math.max(0.0001, gain), start + 0.012); volume.gain.exponentialRampToValueAtTime(0.0001, start + duration); oscillator.connect(volume).connect(context.destination); oscillator.start(start); oscillator.stop(start + duration + 0.03); } function playNoise({ duration = 0.2, gain = 0.2, frequency = 900, delay = 0 } = {}) { const context = ensureAudio(); if (!context) { return; } const frames = Math.max(1, Math.floor(context.sampleRate * duration)); const buffer = context.createBuffer(1, frames, context.sampleRate); const data = buffer.getChannelData(0); for (let index = 0; index < frames; index += 1) { data[index] = (Math.random() * 2 - 1) * (1 - index / frames); } const source = context.createBufferSource(); source.buffer = buffer; const filter = context.createBiquadFilter(); filter.type = "bandpass"; filter.frequency.value = frequency; filter.Q.value = 0.8; const volume = context.createGain(); volume.gain.value = gain; source.connect(filter).connect(volume).connect(context.destination); source.start(context.currentTime + delay); } function playHit(tool) { if (tool === "hamer") { playTone({ freq: 190, endFreq: 58, type: "triangle", duration: 0.18, gain: 0.3 }); playNoise({ duration: 0.1, gain: 0.14, frequency: 1400 }); } else { playTone({ freq: 95, endFreq: 48, type: "sawtooth", duration: 0.22, gain: 0.18 }); playNoise({ duration: 0.16, gain: 0.1, frequency: 620 }); } } function playWrong() { playTone({ freq: 310, endFreq: 190, type: "square", duration: 0.11, gain: 0.09 }); playTone({ freq: 170, endFreq: 120, type: "triangle", duration: 0.16, gain: 0.08, delay: 0.08 }); } function playBreak(objectId) { if (GLASS_OBJECTS.has(objectId)) { playNoise({ duration: 0.5, gain: 0.32, frequency: 3400 }); playTone({ freq: 1750, endFreq: 260, type: "triangle", duration: 0.42, gain: 0.13 }); playNoise({ duration: 0.24, gain: 0.12, frequency: 1800, delay: 0.12 }); } else { playNoise({ duration: 0.34, gain: 0.26, frequency: 720 }); playTone({ freq: 125, endFreq: 42, type: "sawtooth", duration: 0.32, gain: 0.2 }); } } function playFanfare() { const notes = [523.25, 659.25, 783.99, 1046.5]; notes.forEach((frequency, index) => { playTone({ freq: frequency, endFreq: frequency, type: "triangle", duration: 0.28, gain: 0.13, delay: index * 0.13 }); }); playTone({ freq: 1318.5, endFreq: 1318.5, type: "sine", duration: 0.6, gain: 0.1, delay: 0.55 }); } function selectTool(tool) { if (!TOOL_LABELS[tool]) { return; } state.tool = tool; $$(".tool-btn").forEach((button) => { const active = button.dataset.tool === tool; button.classList.toggle("is-active", active); button.setAttribute("aria-pressed", String(active)); }); } function objectCenter(element) { const rect = element.getBoundingClientRect(); return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 }; } function spawnSwing(x, y, tool, good) { const source = $(`.tool-btn[data-tool="${tool}"] svg`); if (!source) { return; } const wrap = document.createElement("div"); wrap.className = `swing${good ? "" : " bad"}`; wrap.style.left = `${x}px`; wrap.style.top = `${y}px`; wrap.appendChild(source.cloneNode(true)); document.body.appendChild(wrap); window.setTimeout(() => wrap.remove(), 460); } function spawnDebris(x, y, colors, count, power = 1) { if (reduceMotion) { return; } for (let index = 0; index < count; index += 1) { const size = 5 + Math.random() * 8; const particle = document.createElement("span"); particle.className = "debris"; particle.style.width = `${size}px`; particle.style.height = `${size}px`; particle.style.left = `${x}px`; particle.style.top = `${y}px`; particle.style.marginLeft = `${-size / 2}px`; particle.style.marginTop = `${-size / 2}px`; particle.style.background = pick(colors); particle.style.clipPath = Math.random() > 0.5 ? "polygon(50% 0, 100% 100%, 0 72%)" : "polygon(0 15%, 100% 0, 75% 100%, 10% 88%)"; document.body.appendChild(particle); const angle = Math.random() * Math.PI * 2; const speed = (45 + Math.random() * 135) * power; const dx = Math.cos(angle) * speed; const dy = Math.sin(angle) * speed - (35 + Math.random() * 65) * power; const rotation = (Math.random() * 2 - 1) * 520; particle.animate( [ { transform: "translate(0, 0) rotate(0deg)", opacity: 1 }, { transform: `translate(${dx}px, ${dy + 260 * power}px) rotate(${rotation}deg)`, opacity: 0 } ], { duration: 520 + Math.random() * 520, easing: "cubic-bezier(.12,.62,.35,1)" } ).onfinish = () => particle.remove(); } } function spawnFloatText(x, y, text, bad = false) { if (reduceMotion) { return; } const node = document.createElement("span"); node.className = `float-text${bad ? " bad" : ""}`; node.textContent = text; node.style.left = `${x}px`; node.style.top = `${y}px`; document.body.appendChild(node); window.setTimeout(() => node.remove(), 850); } function leaveRubble(object) { const roomRect = room.getBoundingClientRect(); const objectRect = object.element.getBoundingClientRect(); if (roomRect.width === 0 || roomRect.height === 0) { return; } const x = ((objectRect.left + objectRect.width / 2 - roomRect.left) / roomRect.width) * 100; const objectBottom = ((objectRect.bottom - roomRect.top) / roomRect.height) * 100; const y = Math.min(93, Math.max(78, objectBottom + 1)); const colors = DEBRIS_COLORS[object.meta.id] || ["#8a6a49", "#5f452f"]; const pile = document.createElement("span"); pile.className = "rubble"; pile.style.left = `${x}%`; pile.style.top = `${y}%`; const pieces = 5 + Math.floor(Math.random() * 4); for (let index = 0; index < pieces; index += 1) { const piece = document.createElement("i"); piece.style.left = `${8 + Math.random() * 78}%`; piece.style.top = `${12 + Math.random() * 70}%`; piece.style.width = `${12 + Math.random() * 22}%`; piece.style.height = `${14 + Math.random() * 28}%`; piece.style.background = pick(colors); piece.style.transform = `rotate(${Math.random() * 120 - 60}deg)`; piece.style.clipPath = Math.random() > 0.5 ? "polygon(50% 0, 100% 100%, 0 74%)" : "polygon(0 16%, 100% 0, 76% 100%, 8% 86%)"; pile.appendChild(piece); } room.appendChild(pile); } function shakeShell() { if (reduceMotion) { return; } shell.classList.remove("is-shaking"); void shell.offsetWidth; shell.classList.add("is-shaking"); window.setTimeout(() => shell.classList.remove("is-shaking"), 260); } function updateProgress() { const total = state.objects.size; const percentage = total === 0 ? 0 : Math.round((state.brokenCount / total) * 100); progressText.textContent = `${state.brokenCount} / ${total} stukken gesloopt`; progressPercent.textContent = `${percentage}%`; progressBar.style.width = `${percentage}%`; progressTrack.setAttribute("aria-valuenow", String(percentage)); room.style.setProperty("--chaos", total === 0 ? "0" : String(state.brokenCount / total)); } function hitObject(object, event) { if (!object || object.broken || state.finished || !state.config) { return; } ensureAudio(); const hasPointer = typeof event.clientX === "number" && (event.clientX !== 0 || event.clientY !== 0); const point = hasPointer ? { x: event.clientX, y: event.clientY } : objectCenter(object.element); const correctTool = state.tool === object.meta.tool; spawnSwing(point.x, point.y, state.tool, correctTool); object.element.classList.remove("is-hit"); void object.element.offsetWidth; object.element.classList.add("is-hit"); window.setTimeout(() => object.element.classList.remove("is-hit"), 300); if (!correctTool) { object.wrong += 1; playWrong(); shakeShell(); spawnDebris(point.x, point.y, ["#c8bda6", "#8f826b"], 6, 0.55); spawnFloatText(point.x, point.y - 12, "BONK?", true); const extra = object.wrong >= 2 ? ` ${object.meta.hint}` : " Probeer eens een ander werktuig."; setLog(`Met de ${TOOL_LABELS[state.tool]} op de ${object.meta.label.toLowerCase()}? Dat werkt niet.${extra}`, "warning"); return; } object.hits += 1; const stage = Math.min(3, Math.ceil((object.hits / object.meta.hp) * 3)); object.element.dataset.stage = String(stage); playHit(state.tool); shakeShell(); spawnDebris(point.x, point.y, DEBRIS_COLORS[object.meta.id] || ["#c8bda6"], 5 + object.hits * 2, 0.75); spawnFloatText(point.x, point.y - 12, state.tool === "hamer" ? "BONK" : "KRAK"); const remaining = object.meta.hp - object.hits; if (remaining > 0) { const line = pick(HIT_LINES[state.tool]); const suffix = remaining === 1 ? "nog 1 slag" : `nog ${remaining} slagen`; setLog(`${line} De ${object.meta.label.toLowerCase()} heeft ${suffix} nodig.`); return; } breakObject(object, point); } function breakObject(object, point) { object.broken = true; state.brokenCount += 1; object.element.dataset.stage = "3"; object.element.classList.add("is-broken"); object.element.disabled = true; const center = objectCenter(object.element); const colors = DEBRIS_COLORS[object.meta.id] || ["#c8bda6"]; spawnDebris(center.x, center.y, colors, object.meta.id === "spiegel" ? 38 : 26, 1.35); if (object.meta.id === "spiegel") { spawnDebris(center.x, center.y, ["#ffffff", "#e8fbff", "#bfe8f1"], 18, 1.1); } playBreak(object.meta.id); leaveRubble(object); setLog(object.meta.done, "done"); if (object.chip) { object.chip.classList.add("done"); } updateProgress(); if (state.brokenCount === state.objects.size) { finishGame(); } } function buildChips() { chips.innerHTML = ""; state.objects.forEach((object) => { const chip = document.createElement("button"); chip.type = "button"; chip.className = "chip"; chip.textContent = object.meta.label; chip.addEventListener("click", () => { if (object.broken) { setLog(`${object.meta.label} is al gesloopt. ${object.meta.done}`); return; } object.element.classList.remove("pulse"); void object.element.offsetWidth; object.element.classList.add("pulse"); window.setTimeout(() => object.element.classList.remove("pulse"), 700); const hint = object.wrong >= 2 ? ` ${object.meta.hint}` : ""; setLog(`Nog te slopen: ${object.meta.label.toLowerCase()}.${hint}`); }); object.chip = chip; chips.appendChild(chip); }); } function applyConfig(config) { const setText = (selector, value) => { const node = $(selector); if (node && value) { node.textContent = value; } }; setText("#recipient-name", config.recipient); setText("#footer-name", config.recipient); setText("#event-date", config.eventDate); setText("#footer-date", config.eventDate); setText("#game-title", config.title); setText("#game-subtitle", config.subtitle); setText("#voucher-date", config.eventDate); setText("#voucher-recipient", `Voor ${config.recipient}`); if (config.title) { document.title = config.title; } } function buildObjects(config) { const elements = new Map( $$(".object").map((element) => [element.dataset.id, element]) ); config.objects.forEach((meta) => { const element = elements.get(meta.id); if (!element) { console.warn(`Geen tekenwerk gevonden voor object "${meta.id}".`); return; } const object = { meta, element, hits: 0, wrong: 0, broken: false, chip: null }; element.disabled = false; element.setAttribute("aria-label", `${meta.label} slopen`); element.addEventListener("click", (event) => hitObject(object, event)); state.objects.set(meta.id, object); elements.delete(meta.id); }); state.brokenCount = 0; updateProgress(); buildChips(); } async function finishGame() { state.finished = true; room.style.setProperty("--chaos", "1"); setLog("Alles is gesloopt. Achter de spiegel zat een envelop met je cadeaubon...", "done"); window.setTimeout(() => { openModal(); launchConfetti(); playFanfare(); }, 650); } function openModal() { state.lastFocus = document.activeElement; voucherCode.textContent = "code wordt gezocht..."; voucherNote.textContent = ""; voucherNote.style.color = ""; modal.hidden = false; window.setTimeout(() => copyButton.focus(), 80); requestVoucher(); } async function requestVoucher() { const completed = Array.from(state.objects.values()) .filter((object) => object.broken) .map((object) => object.meta.id); try { const response = await fetch("/api/reveal", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ completed }) }); const data = await response.json().catch(() => ({})); if (!response.ok || !data.ok) { throw new Error(data.error || "De code kon niet worden opgehaald."); } voucherCode.textContent = data.code; voucherRecipient.textContent = `Voor ${data.recipient || state.config.recipient}`; voucherDate.textContent = data.eventDate || state.config.eventDate; voucherNote.textContent = "De code staat klaar. Kopieer hem of houd deze pagina open."; } catch (error) { voucherCode.textContent = "—"; voucherNote.textContent = `${error.message} Herlaad de pagina en probeer opnieuw.`; voucherNote.style.color = "#a33b22"; } } function resetGame() { state.finished = false; state.brokenCount = 0; state.objects.forEach((object) => { object.hits = 0; object.wrong = 0; object.broken = false; object.element.disabled = false; object.element.classList.remove("is-broken", "is-hit", "pulse"); delete object.element.dataset.stage; if (object.chip) { object.chip.classList.remove("done"); } }); room.style.setProperty("--chaos", "0"); updateProgress(); setLog("Nieuwe kamer, zelfde sloopwoede. Alles moet weg, ook de spiegel."); modal.hidden = true; voucherCode.textContent = "..."; voucherNote.textContent = ""; stopConfetti(); $$(".debris, .swing, .float-text, .rubble").forEach((node) => node.remove()); copyButton.classList.remove("is-copied"); copyButton.textContent = "Kopieer"; const activeTool = $(".tool-btn.is-active"); if (activeTool) { activeTool.focus(); } else if (state.lastFocus && typeof state.lastFocus.focus === "function") { state.lastFocus.focus(); } } function resizeConfetti() { const ratio = Math.min(2, window.devicePixelRatio || 1); confettiCanvas.width = Math.floor(window.innerWidth * ratio); confettiCanvas.height = Math.floor(window.innerHeight * ratio); confettiContext.setTransform(ratio, 0, 0, ratio, 0, 0); } function launchConfetti() { if (reduceMotion) { return; } resizeConfetti(); const colors = ["#ffc93c", "#e86f2b", "#f6ead2", "#6da34d", "#4f837c", "#d2573f"]; state.confettiParticles = Array.from({ length: 170 }, () => ({ x: Math.random() * window.innerWidth, y: -30 - Math.random() * window.innerHeight * 0.5, vx: (Math.random() - 0.5) * 130, vy: 80 + Math.random() * 170, width: 5 + Math.random() * 7, height: 8 + Math.random() * 10, rotation: Math.random() * Math.PI, spin: (Math.random() - 0.5) * 11, color: pick(colors) })); if (state.confettiFrame) { window.cancelAnimationFrame(state.confettiFrame); } let last = performance.now(); const tick = (now) => { const delta = Math.min(0.05, (now - last) / 1000); last = now; confettiContext.clearRect(0, 0, window.innerWidth, window.innerHeight); let visible = 0; state.confettiParticles.forEach((particle) => { particle.vy += 190 * delta; particle.x += particle.vx * delta; particle.y += particle.vy * delta; particle.rotation += particle.spin * delta; if (particle.y < window.innerHeight + 40) { visible += 1; } confettiContext.save(); confettiContext.translate(particle.x, particle.y); confettiContext.rotate(particle.rotation); confettiContext.fillStyle = particle.color; confettiContext.fillRect(-particle.width / 2, -particle.height / 2, particle.width, particle.height); confettiContext.restore(); }); if (visible > 0) { state.confettiFrame = window.requestAnimationFrame(tick); } else { state.confettiFrame = null; confettiContext.clearRect(0, 0, window.innerWidth, window.innerHeight); } }; state.confettiFrame = window.requestAnimationFrame(tick); window.setTimeout(stopConfetti, 8000); } function stopConfetti() { if (state.confettiFrame) { window.cancelAnimationFrame(state.confettiFrame); state.confettiFrame = null; } state.confettiParticles = []; confettiContext.clearRect(0, 0, window.innerWidth, window.innerHeight); } function legacyCopy(text) { const field = document.createElement("textarea"); field.value = text; field.setAttribute("readonly", ""); field.style.position = "fixed"; field.style.opacity = "0"; document.body.appendChild(field); field.select(); try { document.execCommand("copy"); } catch { } field.remove(); } async function copyCode() { const code = voucherCode.textContent.trim(); if (!code || code === "..." || code.startsWith("code wordt")) { return; } try { await navigator.clipboard.writeText(code); } catch { legacyCopy(code); } copyButton.textContent = "Gekopieerd"; copyButton.classList.add("is-copied"); voucherNote.textContent = "De code staat op je klembord."; voucherNote.style.color = ""; window.setTimeout(() => { copyButton.textContent = "Kopieer"; copyButton.classList.remove("is-copied"); }, 2200); } function bindEvents() { $$(".tool-btn").forEach((button) => { button.addEventListener("click", () => selectTool(button.dataset.tool)); }); document.addEventListener("keydown", (event) => { if (event.key === "1") { selectTool("hamer"); } else if (event.key === "2") { selectTool("koevoet"); } }); soundButton.addEventListener("click", () => { state.soundOn = !state.soundOn; try { window.localStorage.setItem("jos-sloop-geluid", state.soundOn ? "aan" : "uit"); } catch { } updateSoundButton(); if (state.soundOn) { playTone({ freq: 660, endFreq: 880, type: "triangle", duration: 0.12, gain: 0.09 }); } }); copyButton.addEventListener("click", copyCode); playAgainButton.addEventListener("click", resetGame); window.addEventListener("resize", () => { if (state.confettiParticles.length > 0) { resizeConfetti(); } }); } async function init() { $$(".object").forEach((element) => { element.disabled = true; }); updateSoundButton(); bindEvents(); try { const response = await fetch("/api/config", { cache: "no-store" }); if (!response.ok) { throw new Error("De spellijn is niet bereikbaar."); } const config = await response.json(); state.config = config; applyConfig(config); buildObjects(config); setLog("Kies je werktuig en sla de kamer kort en klein. Alles moet weg, ook de spiegel."); } catch (error) { setLog(`De kamer kon niet geladen worden: ${error.message}`, "warning"); progressText.textContent = "Niet geladen"; progressPercent.textContent = "—"; } } init(); })();