File size: 29,954 Bytes
5f9262c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
// Dig Drone: game screen (fixed-tick loop, crisp canvas, sound, haptics, upgrades, idle drone, daily dig, share card,
// Fun Pass). (c) 2026 CyberMax. All rights reserved.
import { makeRun, shareText as coreShare, botCol, HZ, COLS, TS, VIEW_W as W, VIEW_H as H, T, ORE, BIOMES, LAYER_EMOJI, biomeOf,
  UPGRADES, DAILY_RIG, upgradeCost, idleCoins } from './core.js';
import { dayNumber, dateOf, count, store, toast, share, intents, download, canvasBlob, pwa, themeToggle, rr } from './cmx.js';
import * as pass from './funpass.js';

const GAME = 'delvewren';
const PATH = '/games/dig-drone/';
const $ = (id) => document.getElementById(id);
const cv = $('c');
const ctx = cv.getContext('2d');
const TAU = Math.PI * 2;
const LOOKS = {
  ember: { name: 'Ember', tier: 'free', body: '#FF8A3D', belly: '#FFD9A8', wing: '#E2621B', drill: '#AEB8C6' },
  berry: { name: 'Berry', tier: 'pass', body: '#FF5FA2', belly: '#FFD6E8', wing: '#D93C80', drill: '#C9B6FF' },
  lagoon: { name: 'Lagoon', tier: 'pass', body: '#22C3B5', belly: '#C8FFF6', wing: '#109488', drill: '#FFD45C' },
};
const todayIso = new Date().toISOString().slice(0, 10);
const todayNum = dayNumber(todayIso);

pass.init({ game: GAME, name: 'Dig Drone', perks: ['Every past Daily Dig in the archive', 'Berry and Lagoon wren looks'],
  free: 'Digging, every upgrade, the drone and the Daily Dig stay free for everyone.',
  extra: 'The Fun Pass adds every past Daily Dig and 2 wren looks.',
  preview: ['past daily digs', '2 looks'] });
const canUse = (s) => s.tier === 'free' || pass.isPro();
let look = LOOKS[store('delvewren:look')] && canUse(LOOKS[store('delvewren:look')]) ? store('delvewren:look') : 'ember';
let muted = !!store('delvewren:mute');
const save = store('delvewren:save') || { coins: 0, lv: { drill: 0, tank: 0, magnet: 0, value: 0 }, best: 0, runs: 0 };
const persist = () => store('delvewren:save', save);
let mode = { kind: 'dig' };
let run, acc = 0, last = performance.now(), hold = false, holdCol = null, keyDir = 0, keyHold = false, started = false, endShown = false, autoBot = false;
let camY = -170, shake = 0, hint = 1, banner = null, fx = [], texts = [], flyers = [], coinPulse = 0, digTick = 0;
const install = pwa(GAME, $('install'));
themeToggle($('theme'));

// ------------------------------------------------------------------ the helper drone digs while you're away (idle coins)
(() => {
  const seen = store('delvewren:seen');
  const got = seen ? idleCoins(Date.now() - seen, save.best) : 0;
  store('delvewren:seen', Date.now());
  if (got > 0) { save.coins += got; persist(); setTimeout(() => toast(`🤖 Your drone dug up 🪙 ${got} while you were away`, 4200), 700); }
  setInterval(() => store('delvewren:seen', Date.now()), 30e3);
  document.addEventListener('visibilitychange', () => store('delvewren:seen', Date.now()));
})();

// ------------------------------------------------------------------ sound (WebAudio, no files) + haptics
let ac, noiseBuf;
function audio() {
  if (muted) return null;
  try {
    ac = ac || new (window.AudioContext || window.webkitAudioContext)();
    if (!noiseBuf) { noiseBuf = ac.createBuffer(1, ac.sampleRate * 0.3, ac.sampleRate); const d = noiseBuf.getChannelData(0); for (let i = 0; i < d.length; i++) d[i] = Math.random() * 2 - 1; }
    return ac;
  } catch { return null; }
}
function tone(f, d = 0.08, type = 'sine', vol = 0.07, to = 1, delay = 0) {
  const a = audio(); if (!a) return;
  const t0 = a.currentTime + delay, o = a.createOscillator(), v = a.createGain();
  o.type = type; o.frequency.setValueAtTime(f, t0); o.frequency.exponentialRampToValueAtTime(Math.max(40, f * to), t0 + d);
  v.gain.setValueAtTime(0.0001, t0); v.gain.exponentialRampToValueAtTime(vol, t0 + 0.006); v.gain.exponentialRampToValueAtTime(0.0001, t0 + d);
  o.connect(v); v.connect(a.destination); o.start(t0); o.stop(t0 + d + 0.03);
}
function crunch(freq, vol = 0.12, d = 0.09) {
  const a = audio(); if (!a) return;
  const s = a.createBufferSource(), f = a.createBiquadFilter(), v = a.createGain();
  s.buffer = noiseBuf; f.type = 'bandpass'; f.frequency.value = freq; f.Q.value = 1.4;
  v.gain.setValueAtTime(vol, a.currentTime); v.gain.exponentialRampToValueAtTime(0.0001, a.currentTime + d);
  s.connect(f); f.connect(v); v.connect(a.destination); s.start(); s.stop(a.currentTime + d + 0.02);
}
const NOTES = [784, 880, 988, 1047, 1175, 1319, 1480, 1568];
const buzz = (ms) => { try { if (navigator.vibrate) navigator.vibrate(ms); } catch { /* */ } };
const setMuteLabel = () => { $('mute').textContent = muted ? '🔇' : '🔊'; };
setMuteLabel();
$('mute').onclick = () => { muted = !muted; store('delvewren:mute', muted); setMuteLabel(); };

// ------------------------------------------------------------------ crisp canvas (device pixels)
let scale = 1;
function fit() {
  const r = cv.getBoundingClientRect();
  const dpr = Math.min(3, window.devicePixelRatio || 1);
  const w = Math.max(1, Math.round(r.width * dpr)), h = Math.max(1, Math.round(r.height * dpr));
  if (cv.width !== w || cv.height !== h) { cv.width = w; cv.height = h; }
  scale = cv.width / W;
}
new ResizeObserver(fit).observe(cv);
fit();

// ------------------------------------------------------------------ modes, upgrades, stats
const seedOf = (m) => (m.kind === 'daily' ? `daily:${m.date}` : m.seed);
const dayKey = (m) => `delvewren:day:${m.date}`;
const dayStats = (m) => store(dayKey(m)) || { best: 0, tries: 0 };
function renderModes() {
  const el = $('modes'); el.innerHTML = '';
  const items = [
    { t: 'Dig', on: mode.kind === 'dig', go: () => setMode({ kind: 'dig' }) },
    { t: `Daily Dig #${todayNum}`, on: mode.kind === 'daily' && mode.date === todayIso, go: () => setMode({ kind: 'daily', date: todayIso }) },
    { t: 'Archive', on: mode.kind === 'daily' && mode.date !== todayIso, lock: !pass.isPro(), go: archive },
  ];
  for (const it of items) {
    const b = document.createElement('button');
    b.className = 'chip'; b.type = 'button'; b.setAttribute('aria-pressed', String(it.on));
    b.innerHTML = `${it.t}${it.lock ? ' <span class="lock">🔒</span>' : ''}`;
    b.onclick = it.go; el.appendChild(b);
  }
}
function archive() {
  if (!pass.isPro()) { pass.open('archive'); return; }
  const n = todayNum - 1;
  const k = Number(prompt(`Play a past Daily Dig: enter a number from 1 to ${n}`, String(n)));
  if (k >= 1 && k <= n) setMode({ kind: 'daily', date: dateOf(k) });
}
function setMode(m) { mode = m; $('menu').open = false; renderModes(); start(); }
function hud() {
  $('num').textContent = mode.kind === 'daily' ? `Daily #${dayNumber(mode.date)}` : '';
  const best = mode.kind === 'daily' ? dayStats(mode).best : save.best;
  $('best').textContent = `${best} m`; $('coins').textContent = save.coins.toLocaleString('en-US');
  const ready = Object.keys(UPGRADES).filter((k) => upgradeCost(k, save.lv[k]) <= save.coins).length;
  $('up-btn').textContent = ready ? `🛠 Upgrades · ${ready} ready` : '🛠 Upgrades';
  $('up-btn').classList.toggle('glow', ready > 0);
}
const shopVis = (on) => { const b = $('shop-btn'); if (b) b.hidden = !on || pass.noShop(); };
function renderShop() {
  const el = $('up-list'); el.innerHTML = '';
  $('up-coins').textContent = save.coins.toLocaleString('en-US');
  for (const [k, u] of Object.entries(UPGRADES)) {
    const lv = save.lv[k] || 0, cost = upgradeCost(k, lv), max = cost === Infinity;
    const row = document.createElement('div'); row.className = 'up';
    row.innerHTML = `<span class="up-i" aria-hidden="true">${u.icon}</span><span class="up-t"><b>${u.name} <small>lv ${lv}</small></b><small>${u.what}</small></span>`;
    const b = document.createElement('button'); b.type = 'button'; b.className = 'btn sm'; b.dataset.up = k;
    b.textContent = max ? 'MAX' : `🪙 ${cost.toLocaleString('en-US')}`; b.disabled = max || cost > save.coins;
    b.onclick = () => {
      if (upgradeCost(k, save.lv[k]) > save.coins) return;
      save.coins -= upgradeCost(k, save.lv[k]); save.lv[k] = (save.lv[k] || 0) + 1; persist();
      tone(880, 0.08, 'triangle', 0.07); tone(1320, 0.12, 'triangle', 0.07, 1, 0.07); buzz(12);
      count(GAME, 'win', `up-${k}`);
      renderShop(); hud();
    };
    row.appendChild(b); el.appendChild(row);
  }
  $('up-note').textContent = mode.kind === 'daily' ? 'The Daily Dig uses the same rig for everyone; upgrades count in Dig mode.' : '';
}
$('up-btn').onclick = () => { renderShop(); $('upgrades').hidden = false; $('over').hidden = true; };
$('up-close').onclick = () => { $('upgrades').hidden = true; if (endShown) $('over').hidden = false; };
$('up-go').onclick = () => { $('upgrades').hidden = true; start(); };

// ------------------------------------------------------------------ run
function start() {
  if (mode.kind === 'dig') mode.seed = `d${Date.now()}`;
  run = makeRun(seedOf(mode), mode.kind === 'daily' ? DAILY_RIG : save.lv);
  camY = -170; shake = 0; banner = null; fx = []; texts = []; flyers = []; endShown = false; started = false; acc = 0; last = performance.now();
  $('over').hidden = true; $('upgrades').hidden = true; shopVis(false); hud();
}
function finish() {
  endShown = true; save.runs++;
  save.coins += run.coins;
  let newBest = false;
  if (mode.kind === 'daily') {
    const s = dayStats(mode); s.tries = (s.tries || 0) + 1;
    if (run.depth > (s.best || 0)) { s.best = run.depth; s.layers = run.layers; s.ores = run.ores; s.coins = run.coins; newBest = run.depth > 0; }
    store(dayKey(mode), s);
  } else if (run.depth > save.best) { save.best = run.depth; newBest = true; }
  persist(); hud();
  tone(523, 0.12, 'triangle', 0.07); tone(392, 0.25, 'triangle', 0.07, 1, 0.12);
  setTimeout(() => showOver(newBest), 450);
  if (run.depth >= 40) install.offer();
}

// ------------------------------------------------------------------ loop
function frame(now) {
  requestAnimationFrame(frame);
  const dt = Math.min(0.1, (now - last) / 1000); last = now;
  const holding = hold || keyHold || autoBot;
  if (holding && run && run.state === 'run' && !started) {
    started = true;
    count(GAME, 'play', mode.kind === 'daily' ? (mode.date === todayIso ? 'daily' : 'archive') : 'dig');
  }
  if (run && run.state === 'run' && started) {
    acc += dt;
    let n = 0;
    while (acc >= 1 / HZ && n++ < 6) {
      acc -= 1 / HZ;
      const col = autoBot ? botCol(run) : keyDir ? run.x + keyDir : holdCol;
      run.tick({ hold: holding, col });
      for (const e of run.events) onEvent(e);
      run.events.length = 0;
    }
    if (acc > 1 / HZ) acc = 0;
    if (run.digging && ++digTick % 7 === 0) {
      const d = run.digging; const b = BIOMES[biomeOf(d.r)];
      dust((d.c + 0.5) * TS, (d.r + (d.r > run.cell() ? 0 : 0.5)) * TS, d.type === T.ROCK || d.type === T.BOULDER ? b.rock : b.soil, 3);
      crunch(d.type === T.BOULDER ? 1300 : d.type === T.ROCK ? 900 : 420, 0.035, 0.05);
    }
  }
  if (run && run.state === 'done' && !endShown) { for (const e of run.events) onEvent(e); run.events.length = 0; finish(); }
  step(dt);
  draw(now);
}
function onEvent(e) {
  if (e.type === 'break') {
    const b = BIOMES[e.biome];
    const col = e.tile === T.BOULDER ? b.deep : e.tile === T.ROCK ? b.rock : b.soil;
    dust((e.c + 0.5) * TS, (e.r + 0.5) * TS, col, e.tile === T.BOULDER ? 18 : e.tile === T.ROCK ? 10 : 6, 1.6);
    if (e.tile === T.BOULDER) { shake = Math.max(shake, 6); crunch(1500, 0.14, 0.16); tone(110, 0.18, 'sine', 0.1, 0.6); buzz(15); }
    else if (e.tile === T.ROCK) { shake = Math.max(shake, 2); crunch(950, 0.1, 0.1); }
    else crunch(480, 0.08, 0.07);
  } else if (e.type === 'ore') {
    const c = { 4: '#E07B39', 5: '#DCE6F2', 6: '#FFD23F', 7: '#FF5FD2' }[e.ore];
    dust((e.c + 0.5) * TS, (e.r + 0.5) * TS, c, 12, 2);
    flyers.push({ x: (e.c + 0.5) * TS, y: (e.r + 0.5) * TS - camY, t: 0, c });
    texts.push({ x: (e.c + 0.5) * TS, y: (e.r + 0.2) * TS, t: `+${e.v}`, life: 1, c: e.ore === 7 ? '#E2399B' : '#2B2340' });
    tone(NOTES[Math.min(NOTES.length - 1, e.streak - 1)] * (e.ore === 7 ? 1.5 : 1), 0.12, 'triangle', 0.08);
    if (e.ore >= 6) tone(NOTES[Math.min(NOTES.length - 1, e.streak)] * 1.5, 0.16, 'sine', 0.06, 1, 0.06);
    buzz(e.ore >= 6 ? 14 : 6);
  } else if (e.type === 'fuel') {
    texts.push({ x: (e.c + 0.5) * TS, y: (e.r + 0.2) * TS, t: '+fuel', life: 1, c: '#E5484D' });
    tone(520, 0.08, 'square', 0.04); tone(780, 0.1, 'square', 0.04, 1, 0.07); buzz(10);
  } else if (e.type === 'biome') {
    banner = { t: `${BIOMES[e.biome].name} · ${e.row} m`, life: 2.2 };
    [0, 0.08, 0.16].forEach((d, i) => tone([659, 880, 1175][i], 0.18, 'triangle', 0.07, 1, d));
  } else if (e.type === 'thud') { shake = Math.max(shake, 3); tone(90, 0.12, 'sine', 0.1, 0.7); }
}
function dust(x, y, c, n, sp = 1) {
  for (let i = 0; i < n; i++) {
    const a = Math.random() * TAU, v = (40 + Math.random() * 120) * sp;
    fx.push({ x, y, vx: Math.cos(a) * v, vy: Math.sin(a) * v - 60, life: 0.6 + Math.random() * 0.5, r: 1.5 + Math.random() * 3, c });
  }
}
function step(dt) {
  for (const p of fx) { p.x += p.vx * dt; p.y += p.vy * dt; p.vy += 500 * dt; p.life -= dt * 1.5; }
  fx = fx.filter((p) => p.life > 0); if (fx.length > 300) fx.splice(0, fx.length - 300);
  for (const t of texts) { t.y -= 34 * dt; t.life -= dt; }
  texts = texts.filter((t) => t.life > 0);
  for (const f of flyers) f.t += dt * 2.2;
  const arrived = flyers.filter((f) => f.t >= 1).length;
  if (arrived) coinPulse = 1;
  flyers = flyers.filter((f) => f.t < 1);
  coinPulse = Math.max(0, coinPulse - dt * 3);
  if (banner) { banner.life -= dt; if (banner.life <= 0) banner = null; }
  if (run) {
    const target = (run.y + 0.5) * TS - H * 0.36;
    camY += (Math.max(-170, target) - camY) * Math.min(1, dt * 6);
    if (started && run.t > 50) hint = Math.max(0, hint - dt * 0.9);
  }
  shake *= Math.pow(0.02, dt); if (shake < 0.2) shake = 0;
}

// ------------------------------------------------------------------ drawing
const mix = (a, b, k) => { // hex a -> hex b by k
  const p = (h) => [parseInt(h.slice(1, 3), 16), parseInt(h.slice(3, 5), 16), parseInt(h.slice(5, 7), 16)];
  const x = p(a), y = p(b);
  return `rgb(${x.map((v, i) => Math.round(v + (y[i] - v) * k)).join(',')})`;
};
const pal = BIOMES.map((b) => ({ ...b, air: mix(b.soil, '#FFFFFF', 0.62), soilHi: mix(b.soil, '#FFFFFF', 0.22), rockHi: mix(b.rock, '#FFFFFF', 0.2), edge: mix(b.soil, '#FFFFFF', 0.45) }));
const h01 = (a, b) => { let h = (a * 374761393 + b * 668265263) | 0; h = (h ^ (h >>> 13)) * 1274126177; return ((h ^ (h >>> 16)) >>> 0) / 4294967296; };
function sky(c, top) {
  // the sky above the surface (world y < 0): bright blue, sun, soft clouds
  if (top >= 0) return;
  const gr = c.createLinearGradient(0, top, 0, 0); gr.addColorStop(0, '#7FD3FF'); gr.addColorStop(1, '#D8F3FF');
  c.fillStyle = gr; c.fillRect(-20, top - 20, W + 40, -top + 20);
  c.fillStyle = '#FFE27A'; c.beginPath(); c.arc(W - 66, -92, 24, 0, TAU); c.fill();
  c.fillStyle = 'rgba(255,255,255,.9)';
  const t = performance.now() / 1000;
  for (let i = 0; i < 3; i++) { const x = ((i * 140 + t * 8) % (W + 120)) - 60, y = -150 + i * 34; c.beginPath(); c.arc(x, y, 16, 0, TAU); c.arc(x + 18, y - 6, 20, 0, TAU); c.arc(x + 38, y, 15, 0, TAU); c.fill(); }
}
function tile(c, type, col, row, x, y, s) {
  const b = pal[biomeOf(row)];
  if (type === T.AIR) { c.fillStyle = b.air; c.fillRect(x, y, s, s); return; }
  const base = type === T.ROCK ? b.rock : type === T.BOULDER ? b.deep : b.soil;
  c.fillStyle = base; c.fillRect(x, y, s, s);
  const u = s / TS; // device px per world unit
  // speckles (fixed per tile, never flicker)
  c.fillStyle = type === T.ROCK || type === T.BOULDER ? b.rockHi : b.soilHi;
  for (let i = 0; i < 3; i++) { const px = h01(col * 7 + i, row), py = h01(row * 3 + i, col + 11); c.fillRect(x + (4 + px * 28) * u, y + (4 + py * 28) * u, 4 * u, 3 * u); }
  if (type === T.BOULDER) {
    c.fillStyle = b.rock; c.beginPath(); c.arc(x + s / 2, y + s / 2, s * 0.42, 0, TAU); c.fill();
    c.fillStyle = b.rockHi; c.beginPath(); c.arc(x + s * 0.38, y + s * 0.36, s * 0.13, 0, TAU); c.fill();
  } else if (ORE[type]) {
    const oc = { 4: ['#E07B39', '#FFB27A'], 5: ['#C9D6E6', '#FFFFFF'], 6: ['#FFC21A', '#FFF1A8'], 7: ['#FF4FCB', '#FFD1F2'] }[type];
    const pts = type === 7 ? [[0.5, 0.5]] : [[0.32, 0.36], [0.66, 0.42], [0.46, 0.7]];
    for (const [px, py] of pts) {
      const cx = x + px * s, cy = y + py * s, r = (type === 7 ? 11 : 6.5) * u;
      c.fillStyle = oc[0]; c.beginPath(); c.moveTo(cx, cy - r); c.lineTo(cx + r, cy); c.lineTo(cx, cy + r); c.lineTo(cx - r, cy); c.closePath(); c.fill();
      c.fillStyle = oc[1]; c.beginPath(); c.moveTo(cx, cy - r); c.lineTo(cx + r * 0.5, cy - r * 0.2); c.lineTo(cx, cy); c.closePath(); c.fill();
    }
    if (type >= 6) { const tw = (Math.sin(performance.now() / 260 + col * 2 + row) + 1) / 2; c.globalAlpha = tw; c.fillStyle = '#FFFFFF'; c.fillRect(x + s * 0.7, y + s * 0.18, 3 * u, 9 * u); c.fillRect(x + s * 0.7 - 3 * u, y + s * 0.18 + 3 * u, 9 * u, 3 * u); c.globalAlpha = 1; }
  } else if (type === T.FUEL) {
    c.fillStyle = '#E5484D'; rr(c, x + s * 0.24, y + s * 0.2, s * 0.52, s * 0.62, 5 * u); c.fill();
    c.fillStyle = '#FFD45C'; c.fillRect(x + s * 0.24, y + s * 0.46, s * 0.52, s * 0.1);
    c.fillStyle = '#B9282D'; c.fillRect(x + s * 0.42, y + s * 0.12, s * 0.16, s * 0.1);
  }
}
function wren(c, x, y, S, dir, spin, s) { // the digging bird-bot, in world units
  c.save(); c.translate(x, y); c.rotate(dir * -Math.PI / 2);
  // drill cone below
  c.fillStyle = S.drill; c.beginPath(); c.moveTo(-10, 8); c.lineTo(10, 8); c.lineTo(0, 30); c.closePath(); c.fill();
  c.strokeStyle = 'rgba(43,35,64,.35)'; c.lineWidth = 2;
  for (let i = 0; i < 3; i++) { const k = ((spin + i / 3) % 1); const yy = 10 + k * 18, hw = 10 * (1 - k * 0.9); c.beginPath(); c.moveTo(-hw, yy); c.lineTo(hw, yy + 3); c.stroke(); }
  c.restore();
  c.save(); c.translate(x, y);
  c.fillStyle = S.body; c.beginPath(); c.arc(0, 0, 15, 0, TAU); c.fill();
  c.lineWidth = 2.5; c.strokeStyle = 'rgba(43,35,64,.35)'; c.stroke();
  c.fillStyle = S.belly; c.beginPath(); c.ellipse(0, 6, 9, 7, 0, 0, TAU); c.fill();
  c.fillStyle = S.wing; c.beginPath(); c.ellipse(-11, 2, 6, 9, 0.5 + Math.sin(performance.now() / 90) * 0.15 * s, 0, TAU); c.fill();
  c.fillStyle = '#FFFFFF'; c.beginPath(); c.arc(5, -4, 5.2, 0, TAU); c.fill();
  c.fillStyle = '#2B2340'; c.beginPath(); c.arc(6, -4, 2.6, 0, TAU); c.fill();
  c.fillStyle = '#FFC21A'; c.beginPath(); c.moveTo(12, -1); c.lineTo(19, 1); c.lineTo(12, 3); c.closePath(); c.fill();
  c.fillStyle = 'rgba(255,255,255,.6)'; c.beginPath(); c.ellipse(-5, -9, 4, 2.4, -0.5, 0, TAU); c.fill();
  c.restore();
}
function draw(now) {
  const S = LOOKS[look];
  ctx.setTransform(1, 0, 0, 1, 0, 0);
  const sh = shake ? [(Math.random() - 0.5) * shake * scale, (Math.random() - 0.5) * shake * scale] : [0, 0];
  const cy = Math.round(camY * scale);
  // background behind the ground (only seen in the sky)
  ctx.fillStyle = '#D8F3FF'; ctx.fillRect(0, 0, cv.width, cv.height);
  ctx.setTransform(scale, 0, 0, scale, sh[0], sh[1] - camY * scale);
  sky(ctx, camY - 20);
  if (!run) return;
  // ground: drawn in device pixels with integer edges (no seams between tiles on any screen)
  ctx.setTransform(1, 0, 0, 1, Math.round(sh[0]), Math.round(sh[1]));
  const r0 = Math.max(0, Math.floor(camY / TS)), r1 = Math.ceil((camY + H) / TS);
  for (let r = r0; r <= r1; r++) {
    const y0 = Math.round(r * TS * scale) - cy, y1 = Math.round((r + 1) * TS * scale) - cy;
    for (let c = 0; c < COLS; c++) {
      const x0 = Math.round(c * TS * scale), x1 = Math.round((c + 1) * TS * scale);
      const type = run.tile(c, r);
      tile(ctx, type, c, r, x0, y0, Math.max(x1 - x0, y1 - y0));
      if (type !== T.AIR) {
        // a light edge where ground meets a tunnel or the sky: reads as depth, keeps the screen calm
        if (run.tile(c, r - 1) === T.AIR || r === 0) { ctx.fillStyle = r === 0 ? '#6FD36B' : pal[biomeOf(r)].edge; ctx.fillRect(x0, y0, x1 - x0, Math.max(2, Math.round((r === 0 ? 7 : 3) * scale))); }
        const k = run.crack(c, r);
        if (k > 0.05) { ctx.strokeStyle = `rgba(43,35,64,${0.25 + k * 0.4})`; ctx.lineWidth = Math.max(1, 2 * scale); const mx = (x0 + x1) / 2, my = (y0 + y1) / 2, q = (x1 - x0) * 0.38 * k;
          ctx.beginPath(); ctx.moveTo(mx, my); ctx.lineTo(mx - q, my - q * 0.6); ctx.moveTo(mx, my); ctx.lineTo(mx + q * 0.8, my - q * 0.3); ctx.moveTo(mx, my); ctx.lineTo(mx + q * 0.2, my + q); ctx.stroke(); }
      }
    }
  }
  // world things (wren, particles, texts) in world units
  ctx.setTransform(scale, 0, 0, scale, sh[0], sh[1] - camY * scale);
  const px = (run.x + (run.tx !== null ? Math.sign(run.tx - run.x) * Math.abs(run.sx || 0) : 0) + 0.5) * TS, py = (run.y + 0.5) * TS;
  const side = run.digging && run.digging.r === run.cell() ? Math.sign(run.digging.c - run.x) : run.tx !== null ? Math.sign(run.tx - run.x) : 0;
  const spin = run.digging ? (now / 120) % 1 : 0;
  const jx = run.digging ? (Math.random() - 0.5) * 1.6 : 0;
  wren(ctx, px + jx, py - 4, S, side, spin, run.digging ? 1 : 0.3);
  for (const p of fx) { ctx.globalAlpha = Math.max(0, Math.min(1, p.life * 1.6)); ctx.fillStyle = p.c; ctx.fillRect(p.x - p.r, p.y - p.r, p.r * 2, p.r * 2); }
  ctx.globalAlpha = 1; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
  for (const t of texts) { ctx.globalAlpha = Math.min(1, t.life * 1.6); ctx.font = '900 16px system-ui, -apple-system, sans-serif'; ctx.lineWidth = 4; ctx.strokeStyle = '#FFFFFF'; ctx.strokeText(t.t, t.x, t.y); ctx.fillStyle = t.c; ctx.fillText(t.t, t.x, t.y); }
  ctx.globalAlpha = 1;
  // HUD (screen units): one depth + fuel chip, one coin chip
  ctx.setTransform(scale, 0, 0, scale, 0, 0);
  for (const f of flyers) { const e = f.t * f.t; const x = f.x + (W - 50 - f.x) * e, y = f.y + (30 - f.y) * e; ctx.fillStyle = f.c; ctx.beginPath(); ctx.arc(x, y, 5, 0, TAU); ctx.fill(); }
  ctx.fillStyle = 'rgba(255,255,255,.88)'; rr(ctx, 12, 10, 132, 46, 20); ctx.fill();
  ctx.fillStyle = '#2B2340'; ctx.textAlign = 'left'; ctx.font = '900 22px system-ui, -apple-system, sans-serif'; ctx.fillText(`${run.depth} m`, 26, 28);
  const fk = run.fuel / run.maxFuel;
  ctx.fillStyle = 'rgba(43,35,64,.12)'; rr(ctx, 26, 42, 104, 7, 3.5); ctx.fill();
  ctx.fillStyle = fk > 0.35 ? "#2FBF71" : fk > 0.15 ? "#FFA41B" : "#E5484D"; if (fk > 0) { rr(ctx, 26, 42, Math.max(7, 104 * fk), 7, 3.5); ctx.fill(); }
  ctx.fillStyle = '#2B2340'; ctx.font = '700 11px system-ui, -apple-system, sans-serif'; ctx.globalAlpha = 0.55; ctx.textAlign = 'right'; ctx.fillText('fuel', 130, 28); ctx.globalAlpha = 1;
  const cw = 92 + coinPulse * 6;
  ctx.fillStyle = 'rgba(255,255,255,.88)'; rr(ctx, W - 12 - cw, 10, cw, 36, 18); ctx.fill();
  ctx.fillStyle = '#2B2340'; ctx.textAlign = 'center'; ctx.font = `900 ${17 + coinPulse * 3}px system-ui, -apple-system, sans-serif`; ctx.fillText(`🪙 ${run.coins}`, W - 12 - cw / 2, 29);
  if (banner) { ctx.globalAlpha = Math.min(1, banner.life * 1.5); ctx.fillStyle = 'rgba(255,255,255,.9)'; rr(ctx, 40, H * 0.2 - 22, W - 80, 44, 22); ctx.fill(); ctx.fillStyle = '#2B2340'; ctx.font = '900 18px system-ui, -apple-system, sans-serif'; ctx.fillText(banner.t, W / 2, H * 0.2); ctx.globalAlpha = 1; }
  if (hint > 0 && run.state === 'run') {
    ctx.globalAlpha = Math.min(1, hint * 1.5); ctx.fillStyle = 'rgba(255,255,255,.9)'; rr(ctx, 50, H * 0.62 - 26, W - 100, 56, 20); ctx.fill();
    ctx.fillStyle = '#2B2340'; ctx.font = '900 18px system-ui, -apple-system, sans-serif'; ctx.fillText(started ? 'Slide to steer to the gems' : 'Hold to dig', W / 2, H * 0.62 - 6);
    ctx.font = '600 13px system-ui, -apple-system, sans-serif'; ctx.globalAlpha *= 0.7; ctx.fillText(started ? 'let go to save fuel' : 'anywhere on the ground', W / 2, H * 0.62 + 14); ctx.globalAlpha = 1;
  }
}

// ------------------------------------------------------------------ results, share, card
const label = () => (mode.kind === 'daily' ? `#${dayNumber(mode.date)}` : 'dig');
const shareText = () => `${coreShare(run, label())}\nHow deep can your wren dig?`;
function showOver(newBest) {
  $('over-title').textContent = newBest ? 'New record!' : 'Out of fuel!';
  $('over-score').textContent = `${run.depth} m`;
  $('over-line').textContent = `+${run.coins} coins · ${BIOMES[biomeOf(Math.max(1, run.depth))].name}`;
  $('over-grid').textContent = coreShare(run, label());
  const it = intents(GAME, shareText(), PATH);
  $('sx').href = it.x; $('sb').href = it.bsky; $('sw').href = it.whatsapp;
  $('over').hidden = false; shopVis(true); hud();
  pass.afterWin($('over'), 'over');
}
function card() {
  const c = document.createElement('canvas'); c.width = 1080; c.height = 1350;
  const x = c.getContext('2d');
  const gr = x.createLinearGradient(0, 0, 0, 1350); gr.addColorStop(0, '#9FE0FF'); gr.addColorStop(0.28, '#D8F3FF'); gr.addColorStop(0.28, '#6FD36B'); gr.addColorStop(0.3, BIOMES[0].soil);
  run.layers.forEach((b, i) => gr.addColorStop(Math.min(0.99, 0.32 + (i + 1) * 0.09), BIOMES[b].soil));
  x.fillStyle = gr; x.fillRect(0, 0, 1080, 1350);
  x.save(); x.scale(3, 3); wren(x, 300, 140, LOOKS[look], 0, 0.3, 0); x.restore();
  x.fillStyle = '#2B2340'; x.textAlign = 'left';
  x.font = '900 72px system-ui, sans-serif'; x.fillText('DIG DRONE', 80, 130);
  x.globalAlpha = 0.75; x.font = '700 40px system-ui, sans-serif'; x.fillText(mode.kind === 'daily' ? `Daily Dig #${dayNumber(mode.date)} · ${mode.date}` : 'My deepest dig', 80, 190);
  x.globalAlpha = 1; x.fillStyle = '#FFFFFF'; x.font = '900 190px system-ui, sans-serif'; x.fillText(`${run.depth} m`, 80, 640);
  x.font = '800 48px system-ui, sans-serif'; x.fillText(run.layers.map((b) => LAYER_EMOJI[b]).join(' '), 80, 740);
  x.fillText(`🪙 ${run.coins}${run.ores[7] ? `   💎 ×${run.ores[7]}` : ''}`, 80, 830);
  x.font = '800 46px system-ui, sans-serif'; x.fillText('How deep can your wren dig?', 80, 1230);
  x.globalAlpha = 0.85; x.font = '600 32px system-ui, sans-serif'; x.fillText('Play free: cybermaxtools.com/games/dig-drone', 80, 1295);
  return c;
}
const fname = () => `delvewren-${mode.date || 'dig'}.png`;
$('share').onclick = async () => share(GAME, shareText(), PATH, await canvasBlob(card()), fname());
['sx', 'sb', 'sw'].forEach((id) => $(id).addEventListener('click', () => count(GAME, 'share', { sx: 'x', sb: 'bsky', sw: 'whatsapp' }[id])));
$('card').onclick = async () => { download(await canvasBlob(card()), fname()); count(GAME, 'share', 'png'); };

// ------------------------------------------------------------------ input: hold to dig, slide to steer
const colAt = (e) => { const r = cv.getBoundingClientRect(); return ((e.clientX - r.left) / r.width) * COLS - 0.5; };
cv.addEventListener('pointerdown', (e) => {
  e.preventDefault();
  if (run && run.state === 'done') { if (endShown) start(); return; }
  hold = true; holdCol = colAt(e);
  // a press right on the wren means "straight down"
  if (run && Math.abs(holdCol - run.x) < 0.6) holdCol = null;
  try { cv.setPointerCapture(e.pointerId); } catch { /* */ }
});
cv.addEventListener('pointermove', (e) => { if (hold) { const c = colAt(e); holdCol = run && Math.abs(c - run.x) < 0.6 ? null : c; } });
const up = () => { hold = false; holdCol = null; };
cv.addEventListener('pointerup', up); cv.addEventListener('pointercancel', up);
const KEYS = { ArrowLeft: -1, ArrowRight: 1, a: -1, d: 1 };
document.addEventListener('keydown', (e) => {
  if (/^(INPUT|TEXTAREA|SELECT|BUTTON)$/.test(document.activeElement && document.activeElement.tagName) && (e.key === ' ' || e.key === 'Enter')) return;
  if (e.key in KEYS) { keyDir = KEYS[e.key]; keyHold = true; e.preventDefault(); }
  else if (e.key === ' ' || e.key === 'ArrowDown' || e.key === 's') { e.preventDefault(); if (run && run.state === 'done') { if (endShown && !e.repeat) start(); } else keyHold = true; }
  else if (e.key === 'r' || e.key === 'R') { e.preventDefault(); start(); }
  else if (e.key === 'm' || e.key === 'M') $('mute').click();
});
document.addEventListener('keyup', (e) => {
  if (e.key in KEYS) { if (keyDir === KEYS[e.key]) keyDir = 0; keyHold = false; }
  else if (e.key === ' ' || e.key === 'ArrowDown' || e.key === 's') keyHold = false;
});
window.addEventListener('blur', () => { up(); keyHold = false; keyDir = 0; });
$('pass-btn').onclick = () => pass.open('header');
$('again').onclick = () => { start(); cv.focus(); };
document.addEventListener('visibilitychange', () => { last = performance.now(); acc = 0; up(); });
function renderLooks() {
  const el = $('looks'); el.innerHTML = '';
  for (const [id, s] of Object.entries(LOOKS)) {
    const b = document.createElement('button');
    const lock = !canUse(s);
    b.type = 'button'; b.title = `${s.name}${s.tier === 'pass' ? ' (Fun Pass)' : ''}`; b.setAttribute('aria-label', b.title);
    b.style.background = `linear-gradient(135deg, ${s.body} 50%, ${s.belly} 50%)`;
    b.setAttribute('aria-pressed', String(id === look));
    if (lock) b.classList.add('locked');
    b.onclick = () => { if (lock) { pass.open('theme'); return; } look = id; store('delvewren:look', id); renderLooks(); };
    el.appendChild(b);
  }
}
const refresh = () => { if (!canUse(LOOKS[look])) { look = 'ember'; store('delvewren:look', 'ember'); } renderLooks(); renderModes(); };
pass.onChange(refresh);

// test + screenshot hooks (no effect on normal play)
window.__delvewren = {
  state: () => ({ state: run.state, depth: run.depth, coins: run.coins, fuel: run.fuel, started, endShown, bank: save.coins, lv: { ...save.lv }, mode: mode.kind }),
  bot: (on = true) => { autoBot = on; },
  drain: () => { run.fuel = Math.min(run.fuel, 0.05); },
};
window.__cmxShot = async () => {
  start(); started = true; hint = 0;
  const r = run;
  for (let i = 0; i < 60 * 9 && r.state === 'run'; i++) { r.tick({ hold: true, col: botCol(r) }); r.events.length = 0; }
  camY = (r.y + 0.5) * TS - H * 0.36;
};

renderModes(); renderLooks();
start();
requestAnimationFrame(frame);