Files
apmanageur/jeux/zipline.html
T

931 lines
28 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!DOCTYPE html>
<html lang="fr" data-theme="dark">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<title>Zip (LinkedIn) - AP Manageur</title>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; user-select: none; }
:root, html[data-theme="dark"] {
--bg: #071326;
--card-bg: #0d1d36;
--panel-box: #132746;
--border: #223c68;
--text: #eef4ff;
--muted: #9aa8c5;
--blue: #5ca7ff;
--blue-btn-text: #071326;
--board-bg: #050d1a;
--cell-bg: #0d1d36;
--cell-border: #1a345e;
--cell-hover: #16315c;
--cell-visited: rgba(92, 167, 255, 0.28);
--path-stroke: #5ca7ff;
--wall-color: #ff6b6b;
--node-color: #ffffff;
}
html[data-theme="light"] {
--bg: #f2f5fa;
--card-bg: #ffffff;
--panel-box: #e9eef7;
--border: #d2dcec;
--text: #15203a;
--muted: #5b6b8c;
--blue: #1e6ef0;
--blue-btn-text: #ffffff;
--board-bg: #f8fafc;
--cell-bg: #ffffff;
--cell-border: #d2dcec;
--cell-hover: #e9eef7;
--cell-visited: rgba(30, 110, 240, 0.15);
--path-stroke: #1e6ef0;
--wall-color: #ef4444;
--node-color: #0f172a;
}
html[data-theme="winxp"] {
--bg: #ece9d8;
--card-bg: #ece9d8;
--panel-box: #ffffff;
--border: #7f9db9;
--text: #000000;
--muted: #444444;
--blue: #0055ea;
--blue-btn-text: #ffffff;
--board-bg: #ffffff;
--cell-bg: #f5f5f5;
--cell-border: #7f9db9;
--cell-hover: #e0e8f5;
--cell-visited: rgba(0, 85, 234, 0.18);
--path-stroke: #0055ea;
--wall-color: #cc0000;
--node-color: #000000;
font-family: 'Tahoma', sans-serif !important;
}
html[data-theme="macos"][data-macos-mode="light"],
html[data-theme="macos"]:not([data-macos-mode="dark"]) {
--bg: #f5f5f7;
--card-bg: #ffffff;
--panel-box: #f2f2f7;
--border: rgba(0, 0, 0, 0.12);
--text: #1d1d1f;
--muted: #86868b;
--blue: #0071e3;
--blue-btn-text: #ffffff;
--board-bg: #f2f2f7;
--cell-bg: #ffffff;
--cell-border: rgba(0, 0, 0, 0.08);
--cell-hover: #e5e5ea;
--cell-visited: rgba(0, 113, 227, 0.15);
--path-stroke: #0071e3;
--wall-color: #ff3b30;
--node-color: #1d1d1f;
}
html[data-theme="macos"][data-macos-mode="dark"] {
--bg: #1e1e1e;
--card-bg: #2d2d2d;
--panel-box: #3a3a3c;
--border: rgba(255, 255, 255, 0.15);
--text: #f5f5f7;
--muted: #98989d;
--blue: #0a84ff;
--blue-btn-text: #ffffff;
--board-bg: #1c1c1e;
--cell-bg: #2c2c2e;
--cell-border: rgba(255, 255, 255, 0.1);
--cell-hover: #3a3a3c;
--cell-visited: rgba(10, 132, 255, 0.25);
--path-stroke: #0a84ff;
--wall-color: #ff453a;
--node-color: #f5f5f7;
}
html[data-theme="futuristic"] {
--bg: #050811;
--card-bg: #091124;
--panel-box: #0f1c3a;
--border: #00f0ff;
--text: #e6f6ff;
--muted: #64b5f6;
--blue: #00f0ff;
--blue-btn-text: #050811;
--board-bg: #030712;
--cell-bg: #0b1730;
--cell-border: rgba(0, 240, 255, 0.25);
--cell-hover: #13254e;
--cell-visited: rgba(0, 240, 255, 0.25);
--path-stroke: #00f0ff;
--wall-color: #ff3366;
--node-color: #e6f6ff;
}
html[data-theme="hacker"] {
--bg: #000000;
--card-bg: #051206;
--panel-box: #0a1f0c;
--border: #00ff41;
--text: #00ff41;
--muted: #008f11;
--blue: #00ff41;
--blue-btn-text: #000000;
--board-bg: #000000;
--cell-bg: #020a04;
--cell-border: rgba(0, 255, 65, 0.25);
--cell-hover: #07240c;
--cell-visited: rgba(0, 255, 65, 0.25);
--path-stroke: #00ff41;
--wall-color: #ff3333;
--node-color: #00ff41;
}
body {
background: var(--bg);
color: var(--text);
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
min-height: 100vh;
overflow-x: hidden;
padding: 10px;
transition: background 0.3s ease, color 0.3s ease;
}
.game-container {
background: var(--card-bg);
border: 1px solid var(--border);
border-radius: 14px;
padding: 16px 20px;
box-shadow: 0 10px 30px rgba(0,0,0,0.5), 0 0 20px rgba(92,167,255,0.12);
max-width: 540px;
width: 100%;
display: flex;
flex-direction: column;
align-items: center;
position: relative;
transition: all 0.3s ease;
}
.top-bar {
width: 100%;
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 12px;
font-size: 13px;
}
.title-badge {
display: flex;
align-items: center;
gap: 6px;
font-weight: 700;
color: var(--blue);
font-size: 16px;
}
.level-selector select {
background: var(--panel-box);
color: var(--text);
border: 1px solid var(--border);
padding: 5px 10px;
border-radius: 6px;
font-size: 12px;
cursor: pointer;
}
.stats-bar {
width: 100%;
display: flex;
justify-content: space-between;
align-items: center;
background: var(--panel-box);
padding: 8px 14px;
border-radius: 8px;
border: 1px solid var(--border);
margin-bottom: 14px;
font-size: 13px;
}
.stats-bar strong {
color: var(--blue);
}
.progress-bar-wrap {
width: 100%;
height: 6px;
background: var(--board-bg);
border-radius: 3px;
overflow: hidden;
margin-bottom: 14px;
border: 1px solid var(--border);
}
.progress-bar-fill {
height: 100%;
width: 0%;
background: linear-gradient(90deg, var(--blue), #32d583);
transition: width 0.2s ease;
}
.board-container {
position: relative;
background: var(--board-bg);
border: 3px solid var(--border);
border-radius: 12px;
padding: 8px;
box-shadow: inset 0 0 20px rgba(0,0,0,0.5);
touch-action: none;
transition: all 0.3s ease;
}
.grid {
display: grid;
gap: 6px;
position: relative;
}
.cell {
width: 58px;
height: 58px;
background: var(--cell-bg);
border: 1px solid var(--cell-border);
border-radius: 8px;
display: flex;
align-items: center;
justify-content: center;
font-size: 20px;
font-weight: 800;
cursor: pointer;
position: relative;
transition: background 0.15s ease, transform 0.1s ease, border-color 0.15s ease;
}
.cell:hover {
background: var(--cell-hover);
}
.cell.visited {
background: var(--cell-visited);
border-color: var(--path-stroke);
}
.cell.current {
background: var(--blue);
color: var(--blue-btn-text);
box-shadow: 0 0 14px var(--blue);
transform: scale(1.04);
}
.cell.number-node {
color: var(--node-color);
font-family: monospace;
font-size: 22px;
text-shadow: 0 0 8px rgba(255, 255, 255, 0.3);
}
.cell.number-node::after {
content: '';
position: absolute;
inset: 4px;
border: 2px dashed rgba(255, 255, 255, 0.35);
border-radius: 6px;
pointer-events: none;
}
.cell.number-node.visited-num {
color: #32d583;
text-shadow: 0 0 10px rgba(50, 213, 131, 0.8);
}
.cell.wall-right { border-right: 4px solid var(--wall-color) !important; }
.cell.wall-bottom { border-bottom: 4px solid var(--wall-color) !important; }
/* SVG overlay for path */
.path-svg {
position: absolute;
top: 8px;
left: 8px;
width: calc(100% - 16px);
height: calc(100% - 16px);
pointer-events: none;
z-index: 10;
overflow: visible !important;
}
.path-line {
fill: none;
stroke: var(--path-stroke, #5ca7ff);
stroke-width: 7;
stroke-linecap: round;
stroke-linejoin: round;
filter: drop-shadow(0 0 6px var(--path-stroke, #5ca7ff));
}
.bottom-actions {
display: flex;
gap: 10px;
margin-top: 16px;
width: 100%;
}
.btn {
flex: 1;
padding: 9px 12px;
border-radius: 8px;
font-weight: 600;
font-size: 13px;
cursor: pointer;
border: 1px solid var(--border);
background: var(--panel-box);
color: var(--text);
transition: all 0.15s ease;
display: flex;
align-items: center;
justify-content: center;
gap: 6px;
}
.btn:hover { background: var(--cell-hover); border-color: var(--blue); }
.btn.primary {
background: var(--blue);
color: var(--blue-btn-text);
border-color: var(--blue);
font-weight: 700;
}
.btn.primary:hover { opacity: 0.9; }
.instructions {
margin-top: 12px;
font-size: 11px;
color: #9aa8c5;
text-align: center;
line-height: 1.4;
}
/* Win overlay */
.win-overlay {
position: absolute;
inset: 0;
background: rgba(7, 19, 38, 0.92);
border-radius: 12px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 12px;
z-index: 20;
backdrop-filter: blur(4px);
}
.win-overlay h2 {
color: #32d583;
font-size: 26px;
letter-spacing: 1px;
animation: pop 0.4s ease;
}
@keyframes pop {
0% { transform: scale(0.6); opacity: 0; }
80% { transform: scale(1.1); }
100% { transform: scale(1); opacity: 1; }
}
</style>
</head>
<body>
<div class="game-container">
<div class="top-bar">
<div class="title-badge">⚡ <span>Zip</span> <span style="font-size:11px;color:#9aa8c5;font-weight:normal">(LinkedIn)</span></div>
<div class="level-selector">
<select id="levelSelect" onchange="loadSelectedLevel()">
<option value="1">Niveau 1 (5×5 Facile)</option>
<option value="2">Niveau 2 (5×5 Intermédiaire)</option>
<option value="3">Niveau 3 (6×6 Expert)</option>
<option value="random">Générateur infini 🎲</option>
</select>
</div>
</div>
<div class="stats-bar">
<div>Cases : <strong id="cellCount">1 / 25</strong></div>
<div>Objectif : <strong id="nextTargetNum">Atteindre le 2</strong></div>
<div>⏱️ <strong id="timerDisplay">00:00</strong></div>
</div>
<div class="progress-bar-wrap">
<div id="progressBar" class="progress-bar-fill"></div>
</div>
<div class="board-container" id="boardContainer">
<svg id="pathSvg" class="path-svg"></svg>
<div id="gridEl" class="grid"></div>
<div id="winOverlay" class="win-overlay" style="display:none">
<h2>🎉 FÉLICITATIONS !</h2>
<p style="color:#eef4ff;font-size:14px">Grille entièrement résolue !</p>
<p id="winTime" style="color:#5ca7ff;font-size:13px;font-weight:bold"></p>
<button class="btn primary" onclick="nextLevelOrReplay()" style="margin-top:8px;padding:8px 24px">Niveau suivant ➡️</button>
</div>
</div>
<div class="bottom-actions">
<button class="btn" onclick="undoMove()">↩️ Annuler</button>
<button class="btn" onclick="resetCurrentLevel()">🔄 Recommencer</button>
<button class="btn primary" onclick="generateRandomLevel()">🎲 Nouveau défi</button>
</div>
<div class="instructions">
Reliez tous les chiffres dans l'ordre (1 ➔ 2 ➔ 3...) en passant par <strong>TOUTES les cases</strong> de la grille exactement une fois, sans croiser les murs rouges ! (Glissez ou cliquez)
</div>
</div>
<script>
// Theme Management
function setTheme(theme, macosMode) {
if (!theme) theme = 'dark';
document.documentElement.dataset.theme = theme;
if (theme === 'macos' && macosMode) {
document.documentElement.dataset.macosMode = macosMode;
} else {
delete document.documentElement.dataset.macosMode;
}
}
const urlParams = new URLSearchParams(window.location.search);
setTheme(urlParams.get('theme') || 'dark', urlParams.get('macosMode'));
window.addEventListener('message', e => {
if (e.data && e.data.type === 'themeChange') {
setTheme(e.data.theme, e.data.macosMode);
}
});
// Audio synthesizer
let audioCtx = null;
function playBeep(type) {
try {
if (!audioCtx) audioCtx = new (window.AudioContext || window.webkitAudioContext)();
if (audioCtx.state === 'suspended') audioCtx.resume();
const osc = audioCtx.createOscillator();
const gain = audioCtx.createGain();
osc.connect(gain);
gain.connect(audioCtx.destination);
const now = audioCtx.currentTime;
if (type === 'step') {
osc.type = 'sine';
osc.frequency.setValueAtTime(440, now);
gain.gain.setValueAtTime(0.04, now);
gain.gain.exponentialRampToValueAtTime(0.001, now + 0.05);
osc.start(now); osc.stop(now + 0.05);
} else if (type === 'checkpoint') {
osc.type = 'triangle';
osc.frequency.setValueAtTime(587.33, now);
osc.frequency.setValueAtTime(880, now + 0.08);
gain.gain.setValueAtTime(0.08, now);
gain.gain.exponentialRampToValueAtTime(0.001, now + 0.2);
osc.start(now); osc.stop(now + 0.2);
} else if (type === 'undo') {
osc.type = 'sawtooth';
osc.frequency.setValueAtTime(300, now);
osc.frequency.linearRampToValueAtTime(200, now + 0.05);
gain.gain.setValueAtTime(0.04, now);
gain.gain.exponentialRampToValueAtTime(0.001, now + 0.05);
osc.start(now); osc.stop(now + 0.05);
} else if (type === 'win') {
osc.type = 'triangle';
[523.25, 659.25, 783.99, 1046.5].forEach((freq, i) => {
const o = audioCtx.createOscillator();
const g = audioCtx.createGain();
o.connect(g); g.connect(audioCtx.destination);
o.frequency.setValueAtTime(freq, now + i * 0.1);
g.gain.setValueAtTime(0.08, now + i * 0.1);
g.gain.exponentialRampToValueAtTime(0.001, now + i * 0.1 + 0.3);
o.start(now + i * 0.1); o.stop(now + i * 0.1 + 0.3);
});
}
} catch (e) {}
}
// Curated Levels
const LEVELS = {
1: {
width: 5,
height: 5,
numbers: { '0,0': 1, '4,0': 2, '4,4': 3, '0,4': 4, '2,2': 5 },
vWalls: new Set(['1,1', '3,2']),
hWalls: new Set(['2,1', '1,3'])
},
2: {
width: 5,
height: 5,
numbers: { '0,2': 1, '2,0': 2, '4,2': 3, '2,4': 4, '2,2': 5 },
vWalls: new Set(['0,1', '3,3']),
hWalls: new Set(['1,1', '3,1'])
},
3: {
width: 6,
height: 6,
numbers: { '0,0': 1, '5,0': 2, '0,5': 3, '5,5': 4, '2,2': 5, '3,3': 6 },
vWalls: new Set(['1,1', '3,2', '4,4']),
hWalls: new Set(['2,1', '1,4', '3,3'])
}
};
let currentConfig = null;
let path = [];
let isDrawing = false;
let timerInterval = null;
let secondsElapsed = 0;
let maxNumber = 1;
function startTimer() {
if (timerInterval) clearInterval(timerInterval);
secondsElapsed = 0;
updateTimerDisplay();
timerInterval = setInterval(() => {
secondsElapsed++;
updateTimerDisplay();
}, 1000);
}
function updateTimerDisplay() {
const m = String(Math.floor(secondsElapsed / 60)).padStart(2, '0');
const s = String(secondsElapsed % 60).padStart(2, '0');
document.getElementById('timerDisplay').textContent = `${m}:${s}`;
}
function initLevel(config) {
currentConfig = config;
path = [];
document.getElementById('winOverlay').style.display = 'none';
// Find highest number in numbers
maxNumber = Math.max(...Object.values(config.numbers));
// Find cell with '1' and make it start
let startKey = null;
for (const [k, v] of Object.entries(config.numbers)) {
if (v === 1) startKey = k;
}
if (startKey) {
const [x, y] = startKey.split(',').map(Number);
path.push({ x, y });
}
renderGrid();
renderPath();
updateStats();
startTimer();
}
function renderGrid() {
const grid = document.getElementById('gridEl');
const { width, height, numbers, vWalls, hWalls } = currentConfig;
grid.style.gridTemplateColumns = `repeat(${width}, 1fr)`;
grid.innerHTML = '';
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const cell = document.createElement('div');
cell.className = 'cell';
cell.dataset.x = x;
cell.dataset.y = y;
const key = `${x},${y}`;
if (numbers[key] !== undefined) {
cell.classList.add('number-node');
cell.textContent = numbers[key];
}
if (vWalls && vWalls.has(key)) cell.classList.add('wall-right');
if (hWalls && hWalls.has(key)) cell.classList.add('wall-bottom');
// Events
cell.addEventListener('pointerdown', (e) => onPointerDown(x, y, e));
cell.addEventListener('pointerenter', (e) => onPointerEnter(x, y, e));
grid.appendChild(cell);
}
}
}
function updateStats() {
const total = currentConfig.width * currentConfig.height;
const count = path.length;
document.getElementById('cellCount').textContent = `${count} / ${total}`;
const pct = Math.round((count / total) * 100);
document.getElementById('progressBar').style.width = `${pct}%`;
// Next expected number
let nextExpected = 2;
for (const p of path) {
const key = `${p.x},${p.y}`;
const num = currentConfig.numbers[key];
if (num && num === nextExpected) {
nextExpected++;
}
}
if (nextExpected <= maxNumber) {
document.getElementById('nextTargetNum').textContent = `Atteindre le ${nextExpected}`;
} else if (count < total) {
document.getElementById('nextTargetNum').textContent = `Couvrir les ${total - count} case(s) restante(s)`;
} else {
document.getElementById('nextTargetNum').textContent = `Terminé ! 🎉`;
}
}
function canMoveTo(from, to) {
// Orthogonal adjacent only
const dx = Math.abs(from.x - to.x);
const dy = Math.abs(from.y - to.y);
if (dx + dy !== 1) return false;
// Check walls
const { vWalls, hWalls } = currentConfig;
if (to.x === from.x + 1) { // Moving Right
if (vWalls && vWalls.has(`${from.x},${from.y}`)) return false;
} else if (to.x === from.x - 1) { // Moving Left
if (vWalls && vWalls.has(`${to.x},${to.y}`)) return false;
} else if (to.y === from.y + 1) { // Moving Down
if (hWalls && hWalls.has(`${from.x},${from.y}`)) return false;
} else if (to.y === from.y - 1) { // Moving Up
if (hWalls && hWalls.has(`${from.x},${to.y}`)) return false;
}
// Check numbers constraint: if 'to' is a numbered cell, it MUST be the next expected number
const toKey = `${to.x},${to.y}`;
const toNum = currentConfig.numbers[toKey];
if (toNum !== undefined) {
let highestVisited = 1;
for (const p of path) {
const num = currentConfig.numbers[`${p.x},${p.y}`];
if (num && num > highestVisited) highestVisited = num;
}
if (toNum !== highestVisited + 1) {
return false;
}
}
return true;
}
function onPointerDown(x, y, e) {
isDrawing = true;
const head = path[path.length - 1];
// If clicked on an earlier path point, backtrack to it!
const existingIdx = path.findIndex(p => p.x === x && p.y === y);
if (existingIdx !== -1 && existingIdx < path.length - 1) {
path = path.slice(0, existingIdx + 1);
playBeep('undo');
renderPath();
updateStats();
return;
}
if (head && canMoveTo(head, { x, y })) {
stepTo(x, y);
}
}
function onPointerEnter(x, y, e) {
if (!isDrawing) return;
const head = path[path.length - 1];
if (!head) return;
// Backtrack if moving back to previous cell
if (path.length >= 2) {
const prev = path[path.length - 2];
if (prev.x === x && prev.y === y) {
path.pop();
playBeep('undo');
renderPath();
updateStats();
return;
}
}
// Check if already visited
if (path.some(p => p.x === x && p.y === y)) return;
if (canMoveTo(head, { x, y })) {
stepTo(x, y);
}
}
window.addEventListener('pointerup', () => { isDrawing = false; });
function stepTo(x, y) {
path.push({ x, y });
const key = `${x},${y}`;
if (currentConfig.numbers[key] !== undefined) {
playBeep('checkpoint');
} else {
playBeep('step');
}
renderPath();
updateStats();
checkWin();
}
function undoMove() {
if (path.length > 1) {
path.pop();
playBeep('undo');
renderPath();
updateStats();
}
}
function resetCurrentLevel() {
if (path.length > 0) {
path = [path[0]];
renderPath();
updateStats();
startTimer();
}
}
function renderPath() {
const cells = document.querySelectorAll('.cell');
const head = path[path.length - 1];
// Clear states
cells.forEach(c => {
c.classList.remove('visited', 'current', 'visited-num');
});
// Visited cells
path.forEach((p, idx) => {
const c = document.querySelector(`.cell[data-x="${p.x}"][data-y="${p.y}"]`);
if (c) {
c.classList.add('visited');
if (idx === path.length - 1) c.classList.add('current');
if (currentConfig.numbers[`${p.x},${p.y}`] !== undefined) {
c.classList.add('visited-num');
}
}
});
// Draw SVG polyline
const svg = document.getElementById('pathSvg');
const grid = document.getElementById('gridEl');
if (!svg || !grid) return;
svg.innerHTML = '';
const w = grid.offsetWidth;
const h = grid.offsetHeight;
svg.setAttribute('width', w);
svg.setAttribute('height', h);
svg.setAttribute('viewBox', `0 0 ${w} ${h}`);
svg.style.width = w + 'px';
svg.style.height = h + 'px';
if (path.length < 2) return;
const points = path.map(p => {
const c = document.querySelector(`.cell[data-x="${p.x}"][data-y="${p.y}"]`);
if (!c) return '0,0';
const cx = c.offsetLeft + c.offsetWidth / 2;
const cy = c.offsetTop + c.offsetHeight / 2;
return `${cx},${cy}`;
}).join(' ');
const poly = document.createElementNS('http://www.w3.org/2000/svg', 'polyline');
poly.setAttribute('points', points);
poly.setAttribute('class', 'path-line');
svg.appendChild(poly);
}
function checkWin() {
const total = currentConfig.width * currentConfig.height;
if (path.length !== total) return;
// Verify all numbers in sequence
let lastNum = 0;
for (const p of path) {
const num = currentConfig.numbers[`${p.x},${p.y}`];
if (num !== undefined) {
if (num !== lastNum + 1) return;
lastNum = num;
}
}
if (lastNum === maxNumber) {
// VICTORY!
if (timerInterval) clearInterval(timerInterval);
playBeep('win');
document.getElementById('winTime').textContent = `Temps : ${document.getElementById('timerDisplay').textContent}`;
document.getElementById('winOverlay').style.display = 'flex';
}
}
function loadSelectedLevel() {
const val = document.getElementById('levelSelect').value;
if (val === 'random') {
generateRandomLevel();
} else {
initLevel(LEVELS[val]);
}
}
function nextLevelOrReplay() {
const sel = document.getElementById('levelSelect');
const cur = parseInt(sel.value, 10);
if (cur < 3) {
sel.value = String(cur + 1);
loadSelectedLevel();
} else {
generateRandomLevel();
}
}
// Procedural Generator for Infinite Random Levels
function generateRandomLevel() {
document.getElementById('levelSelect').value = 'random';
const w = 5, h = 5;
const total = w * h;
// Self-avoiding walk generator with Warnsdorff heuristic
let walk = [];
let attempts = 0;
while (attempts++ < 100) {
walk = tryGenerateHamiltonianPath(w, h);
if (walk.length === total) break;
}
if (walk.length < total) {
// Fallback to level 1 if failed
initLevel(LEVELS[1]);
return;
}
// Pick checkpoints: 1 at start, and 4 more evenly spaced along the walk
const numbers = {};
const indices = [0, Math.floor(total * 0.25), Math.floor(total * 0.5), Math.floor(total * 0.75), total - 1];
indices.forEach((idx, numIdx) => {
const pt = walk[idx];
numbers[`${pt.x},${pt.y}`] = numIdx + 1;
});
// Add a couple of random walls that don't block the solution
const vWalls = new Set();
const hWalls = new Set();
const solutionEdges = new Set();
for (let i = 0; i < walk.length - 1; i++) {
const a = walk[i], b = walk[i+1];
if (b.x === a.x + 1) solutionEdges.add(`V:${a.x},${a.y}`);
else if (a.x === b.x + 1) solutionEdges.add(`V:${b.x},${b.y}`);
else if (b.y === a.y + 1) solutionEdges.add(`H:${a.x},${a.y}`);
else if (a.y === b.y + 1) solutionEdges.add(`H:${a.x},${b.y}`);
}
for (let y = 0; y < h; y++) {
for (let x = 0; x < w; x++) {
if (x < w - 1 && !solutionEdges.has(`V:${x},${y}`) && Math.random() < 0.15) {
vWalls.add(`${x},${y}`);
}
if (y < h - 1 && !solutionEdges.has(`H:${x},${y}`) && Math.random() < 0.15) {
hWalls.add(`${x},${y}`);
}
}
}
initLevel({ width: w, height: h, numbers, vWalls, hWalls });
}
function tryGenerateHamiltonianPath(w, h) {
const visited = new Set();
const path = [];
const startX = Math.floor(Math.random() * w);
const startY = Math.floor(Math.random() * h);
function dfs(x, y) {
path.push({ x, y });
visited.add(`${x},${y}`);
if (path.length === w * h) return true;
const neighbors = [
{ x: x + 1, y }, { x: x - 1, y }, { x, y: y + 1 }, { x, y: y - 1 }
].filter(n => n.x >= 0 && n.x < w && n.y >= 0 && n.y < h && !visited.has(`${n.x},${n.y}`));
// Sort by Warnsdorff's heuristic (fewest unvisited neighbors first)
neighbors.sort((a, b) => {
const degA = countUnvisitedNeighbors(a.x, a.y, w, h, visited);
const degB = countUnvisitedNeighbors(b.x, b.y, w, h, visited);
return degA - degB;
});
for (const n of neighbors) {
if (dfs(n.x, n.y)) return true;
}
path.pop();
visited.delete(`${x},${y}`);
return false;
}
dfs(startX, startY);
return path;
}
function countUnvisitedNeighbors(x, y, w, h, visited) {
return [{ x: x + 1, y }, { x: x - 1, y }, { x, y: y + 1 }, { x, y: y - 1 }]
.filter(n => n.x >= 0 && n.x < w && n.y >= 0 && n.y < h && !visited.has(`${n.x},${n.y}`)).length;
}
// Keyboard support (Undo: Z or Backspace)
window.addEventListener('keydown', e => {
if (e.key === 'z' || e.key === 'Z' || e.key === 'Backspace') {
undoMove();
}
});
window.addEventListener('resize', () => { renderPath(); });
initLevel(LEVELS[1]);
</script>
</body>
</html>