File size: 23,919 Bytes
9d1d0d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Blob Gulp: game screen (fixed 60 Hz sim, crisp canvas, follow camera that zooms out as you grow, one-finger steer,
// sound, haptics, daily/quick/archive, share line + card, Fun Pass). Rules: core.js. (c) 2026 CyberMax. All rights reserved.
import { makeArena, autoInput, shareText as coreShare, radius, HZ, WORLD, ROUND, COLORS, MEDALS, place } from './core.js';
import { dayNumber, dateOf, count, store, share, intents, download, canvasBlob, pwa, themeToggle, rr } from './cmx.js';
import * as pass from './funpass.js';

const GAME = 'blobgulp', PATH = '/games/blobgulp/';
const $ = (id) => document.getElementById(id);
const cv = $('c'), ctx = cv.getContext('2d'), TAU = Math.PI * 2;
const W = 360, H = 540;
const LOOKS = {
  meadow: { name: 'Meadow', tier: 'free', g1: '#E4FBEA', g2: '#D3F5FF', dot: 'rgba(60,140,100,.13)', edge: '#9FDDBB', ink: '#1E3A2E', acc: '#FF6FAE' },
  sorbet: { name: 'Sorbet', tier: 'pass', g1: '#FFE9F2', g2: '#FFF6D6', dot: 'rgba(200,90,130,.13)', edge: '#F5B6CF', ink: '#3E1E2E', acc: '#4DA3FF' },
  lagoon: { name: 'Lagoon', tier: 'pass', g1: '#DDF4FF', g2: '#E9E4FF', dot: 'rgba(60,100,180,.13)', edge: '#A9CFF5', ink: '#1E2A44', acc: '#FF9F1C' },
};
const todayIso = new Date().toISOString().slice(0, 10), todayNum = dayNumber(todayIso);
pass.init({ game: GAME, name: 'Blob Gulp', perks: ['Every past Daily Arena in the archive', 'Sorbet and Lagoon arena themes'],
  free: 'The Daily Arena and quick matches stay free for everyone.', extra: 'The Fun Pass adds every past Daily Arena and 2 arena themes.', preview: ['past daily arenas', '2 themes'] });
const canUse = (s) => s.tier === 'free' || pass.isPro();
let look = LOOKS[store('blobgulp:look')] && canUse(LOOKS[store('blobgulp:look')]) ? store('blobgulp:look') : 'meadow';
let muted = !!store('blobgulp:mute');
let mode = { kind: 'daily', date: todayIso };
let A, acc = 0, last = performance.now(), endShown = false, state = 'ready', steer = null, lastDir = null, autoBot = false, shake = 0;
let fx = [], texts = [], cam = { x: WORLD / 2, y: WORLD / 2, z: 1 };
const install = pwa(GAME, $('install'));
themeToggle($('theme'));

// ------------------------------------------------------------------ sound + haptics
let ac;
function tone(f, d = 0.08, type = 'sine', vol = 0.07, to = 1, delay = 0) {
  if (muted) return;
  try {
    ac = ac || new (window.AudioContext || window.webkitAudioContext)();
    const s = ac.currentTime + delay, o = ac.createOscillator(), v = ac.createGain();
    o.type = type; o.frequency.setValueAtTime(f, s); o.frequency.exponentialRampToValueAtTime(Math.max(40, f * to), s + d);
    v.gain.setValueAtTime(0.0001, s); v.gain.exponentialRampToValueAtTime(vol, s + 0.008); v.gain.exponentialRampToValueAtTime(0.0001, s + d);
    o.connect(v); v.connect(ac.destination); o.start(s); o.stop(s + d + 0.03);
  } catch { /* no audio */ }
}
const buzz = (ms) => { try { if (navigator.vibrate) navigator.vibrate(ms); } catch { /* */ } };
const setMute = () => { $('mute').textContent = muted ? '🔇' : '🔊'; };
setMute(); $('mute').onclick = () => { muted = !muted; store('blobgulp:mute', muted); setMute(); };

// ------------------------------------------------------------------ crisp canvas
let scale = 1;
function fit() {
  const r = cv.getBoundingClientRect(), 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
const RULE = { daily: 'timed', quick: 'timed', last: 'last', endless: 'endless' };
const ruleOf = (m) => RULE[m.kind] || 'timed';
const seedOf = (m) => (m.kind === 'daily' ? `daily:${m.date}` : m.seed);
const dayKey = (m) => `blobgulp:day:${m.date}`;
const dayStats = (m) => store(dayKey(m)) || { best: 0, tries: 0, rank: 0 };
function renderModes() {
  const el = $('modes'); el.innerHTML = '';
  const items = [
    { t: `Daily Arena #${todayNum}`, on: mode.kind === 'daily' && mode.date === todayIso, go: () => setMode({ kind: 'daily', date: todayIso }) },
    { t: 'Quick match', on: mode.kind === 'quick', go: () => setMode({ kind: 'quick', seed: `q${Date.now()}` }) },
    { t: 'Last Blob Standing', on: mode.kind === 'last', go: () => setMode({ kind: 'last', seed: `l${Date.now()}` }) },
    { t: 'Endless', on: mode.kind === 'endless', go: () => setMode({ kind: 'endless', seed: `e${Date.now()}` }) },
    { 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, k = Number(prompt(`Play a past Daily Arena: 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(); }
const NAMES = { quick: 'quick match', last: 'last blob standing', endless: 'endless' };
const label = () => (mode.kind === 'daily' ? `#${dayNumber(mode.date)}` : NAMES[mode.kind]);
const bestKey = () => `blobgulp:${mode.kind}-best`;
function hud() {
  $('num').textContent = mode.kind === 'daily' ? `#${dayNumber(mode.date)}` : { quick: 'quick', last: 'last one', endless: 'endless' }[mode.kind];
  const s = mode.kind === 'daily' ? dayStats(mode) : { best: store(bestKey()) || 0 };
  $('best').textContent = Math.round(s.best || 0); $('wins').textContent = store('blobgulp:wins') || 0;
}
const shopVis = (on) => { const b = $('shop-btn'); if (b) b.hidden = !on || pass.noShop(); };

// ------------------------------------------------------------------ run
function start(ready = false) {
  if (mode.kind !== 'daily') mode.seed = `${mode.kind[0]}${Date.now()}`;
  A = makeArena(seedOf(mode), { rule: ruleOf(mode) });
  fx = []; texts = []; endShown = false; acc = 0; last = performance.now(); steer = null; lastDir = null; shake = 0;
  cam = { x: A.me().x, y: A.me().y, z: 1 };
  state = ready ? 'ready' : 'run';
  $('over').hidden = true; shopVis(false); hud();
  if (!ready) count(GAME, 'play', mode.kind === 'daily' ? (mode.date === todayIso ? 'daily' : 'archive') : mode.kind);
}
function finish() {
  endShown = true; state = 'over';
  const rk = A.rank(), me = A.me();
  if (rk === 1) { tone(784, 0.15, 'triangle', 0.08); tone(1047, 0.2, 'triangle', 0.08, 1, 0.12); tone(1568, 0.3, 'triangle', 0.07, 1, 0.24); store('blobgulp:wins', (store('blobgulp:wins') || 0) + 1); }
  else tone(520, 0.2, 'triangle', 0.06, 0.8);
  let newBest = false;
  if (mode.kind === 'daily') { const s = dayStats(mode); s.tries++; if (me.m > s.best) { s.best = Math.round(me.m); s.rank = rk; newBest = true; } store(dayKey(mode), s); }
  else { const v = Math.round(A.rule === 'endless' ? me.best : me.m); if (v > (store(bestKey()) || 0)) { store(bestKey(), v); newBest = true; } }
  hud();
  setTimeout(() => showOver(newBest), 700);
  if (rk <= 3) install.offer();
}

// ------------------------------------------------------------------ loop
function frame(now) {
  requestAnimationFrame(frame);
  const dt = Math.min(0.1, (now - last) / 1000); last = now;
  if (A && state === 'run') {
    acc += dt; let n = 0;
    while (acc >= 1 / HZ && n++ < 6) {
      acc -= 1 / HZ;
      A.input = autoBot ? autoInput(A) : steer || lastDir;
      A.step();
      for (const e of A.events) onEvent(e);
      A.events.length = 0;
      if (A.state === 'over') { finish(); break; }
    }
    if (acc > 1 / HZ) acc = 0;
  }
  step(dt);
  draw(now);
}
function onEvent(e) {
  const me = A.me();
  if (e.type === 'snack') { if (Math.random() < 0.5) tone(900 + e.m * 120, 0.04, 'sine', 0.025, 1.3); }
  else if (e.type === 'gulp') {
    const o = A.blobs[e.of], c = o.color;
    burst(e.x, e.y, c, 18, 220);
    if (e.by === 0) { texts.push({ x: e.x, y: e.y, t: `Gulp! +${Math.round(e.m * 0.8)}`, life: 1 }); tone(300, 0.18, 'sine', 0.1, 0.5); tone(880, 0.12, 'triangle', 0.06, 1.2, 0.08); buzz(20); shake = 4; }
    else if (e.of === 0) { texts.push({ x: me.x, y: me.y, t: A.rule === 'timed' ? 'Gulped! back soon…' : 'Gulped!', life: 1.4 }); tone(200, 0.3, 'sawtooth', 0.05, 0.5); buzz([30, 30, 30]); shake = 7; }
  } else if (e.type === 'spawn' && e.id === 0) { tone(660, 0.1, 'triangle', 0.05, 1.3); }
}
function burst(x, y, c, n, sp) { for (let i = 0; i < n; i++) { const a = Math.random() * TAU, v = sp * (0.3 + Math.random() * 0.7); fx.push({ x, y, vx: Math.cos(a) * v, vy: Math.sin(a) * v, life: 1, r: 3 + Math.random() * 4, c: i % 4 === 0 ? '#FFFFFF' : c }); } }
function step(dt) {
  for (const p of fx) { p.x += p.vx * dt; p.y += p.vy * dt; p.vx *= 0.94; p.vy *= 0.94; p.life -= dt * 1.4; }
  fx = fx.filter((p) => p.life > 0);
  for (const t of texts) { t.y -= 40 * dt; t.life -= dt * 0.8; }
  texts = texts.filter((t) => t.life > 0);
  if (A) {
    const me = A.me(), R = radius(me.m), z = Math.min(1, 1.15 / (1 + (R - 16) / 70));
    const k = 1 - Math.exp(-dt * 5); cam.x += (me.x - cam.x) * k; cam.y += (me.y - cam.y) * k; cam.z += (z - cam.z) * (1 - Math.exp(-dt * 2));
  }
  shake *= Math.pow(0.02, dt); if (shake < 0.2) shake = 0;
}
function blob(c, b, now, S, R) {
  const t = now / 1000 + b.id, sp = Math.hypot(b.vx, b.vy), ang = Math.atan2(b.vy, b.vx);
  c.save(); c.translate(b.x, b.y);
  // jelly wobble: stretch a little along the motion
  const st = Math.min(0.1, sp / 2200);
  c.rotate(ang); c.scale(1 + st + Math.sin(t * 6) * 0.015, 1 - st + Math.cos(t * 6) * 0.015); c.rotate(-ang);
  const g = c.createRadialGradient(-R * 0.35, -R * 0.4, R * 0.1, 0, 0, R);
  g.addColorStop(0, '#FFFFFF'); g.addColorStop(0.25, b.color); g.addColorStop(1, b.color);
  c.globalAlpha = 0.18; c.fillStyle = '#000'; c.beginPath(); c.ellipse(R * 0.08, R * 0.12, R, R * 0.96, 0, 0, TAU); c.fill(); c.globalAlpha = 1;
  c.fillStyle = g; c.beginPath(); c.arc(0, 0, R, 0, TAU); c.fill();
  c.lineWidth = Math.max(2, R * 0.07); c.strokeStyle = 'rgba(30,40,60,.25)'; c.stroke();
  if (b.me) { c.lineWidth = Math.max(3, R * 0.08); c.strokeStyle = '#FFFFFF'; c.beginPath(); c.arc(0, 0, R + c.lineWidth * 0.6, 0, TAU); c.stroke(); }
  // face looks where it goes; scared of bigger blobs nearby
  const lx = Math.cos(ang) * R * 0.12 * Math.min(1, sp / 80), ly = Math.sin(ang) * R * 0.12 * Math.min(1, sp / 80), er = Math.max(2, R * 0.16);
  for (const s of [-1, 1]) { c.fillStyle = '#FFFFFF'; c.beginPath(); c.arc(s * R * 0.32 + lx * 0.5, -R * 0.12 + ly * 0.5, er, 0, TAU); c.fill(); c.fillStyle = '#1E2433'; c.beginPath(); c.arc(s * R * 0.32 + lx, -R * 0.12 + ly, er * 0.55, 0, TAU); c.fill(); }
  c.strokeStyle = '#1E2433'; c.lineWidth = Math.max(1.5, R * 0.06); c.lineCap = 'round'; c.beginPath();
  if (b.mood === 'flee') c.arc(lx * 0.5, R * 0.3 + ly * 0.5, R * 0.12, 0, TAU); else c.arc(lx * 0.5, R * 0.16 + ly * 0.5, R * 0.2, 0.15 * Math.PI, 0.85 * Math.PI);
  c.stroke();
  c.restore();
}
function draw(now) {
  const S = LOOKS[look];
  ctx.setTransform(1, 0, 0, 1, 0, 0);
  const gr = ctx.createLinearGradient(0, 0, 0, cv.height); gr.addColorStop(0, S.g1); gr.addColorStop(1, S.g2); ctx.fillStyle = gr; ctx.fillRect(0, 0, cv.width, cv.height);
  if (!A) return;
  const z = cam.z * scale, ox = cv.width / 2 - cam.x * z + (shake ? (Math.random() - 0.5) * shake * scale : 0), oy = cv.height / 2 - cam.y * z + (shake ? (Math.random() - 0.5) * shake * scale : 0);
  ctx.setTransform(z, 0, 0, z, ox, oy);
  const vw = W / cam.z / 2 + 60, vh = H / cam.z / 2 + 60;
  // ground: soft dots, then the arena edge
  ctx.fillStyle = S.dot; const step = 60, x0 = Math.max(0, Math.floor((cam.x - vw) / step) * step), y0 = Math.max(0, Math.floor((cam.y - vh) / step) * step);
  for (let x = x0; x <= Math.min(WORLD, cam.x + vw); x += step) for (let y = y0; y <= Math.min(WORLD, cam.y + vh); y += step) { ctx.beginPath(); ctx.arc(x, y, 3, 0, TAU); ctx.fill(); }
  ctx.strokeStyle = S.edge; ctx.lineWidth = 10; rr(ctx, -5, -5, WORLD + 10, WORLD + 10, 40); ctx.stroke();
  if (A.hi - A.lo < WORLD - 1) { // Last Blob Standing: the closing wall
    ctx.fillStyle = 'rgba(40,30,70,.16)'; ctx.fillRect(-5, -5, WORLD + 10, A.lo + 5); ctx.fillRect(-5, A.hi, WORLD + 10, WORLD - A.hi + 5); ctx.fillRect(-5, A.lo, A.lo + 5, A.hi - A.lo); ctx.fillRect(A.hi, A.lo, WORLD - A.hi + 5, A.hi - A.lo);
    ctx.strokeStyle = S.acc; ctx.lineWidth = 6; ctx.setLineDash([18, 12]); rr(ctx, A.lo, A.lo, A.hi - A.lo, A.hi - A.lo, 30); ctx.stroke(); ctx.setLineDash([]);
  }
  // snacks
  for (const f of A.food) {
    if (Math.abs(f.x - cam.x) > vw || Math.abs(f.y - cam.y) > vh) continue;
    const r = f.m >= 6 ? 9 : 4 + f.m * 1.5;
    ctx.fillStyle = f.m >= 6 ? '#FFD23F' : COLORS[f.c]; ctx.beginPath(); ctx.arc(f.x, f.y, r, 0, TAU); ctx.fill();
    ctx.fillStyle = 'rgba(255,255,255,.75)'; ctx.beginPath(); ctx.arc(f.x - r * 0.3, f.y - r * 0.3, r * 0.35, 0, TAU); ctx.fill();
    if (f.m >= 6) { ctx.strokeStyle = 'rgba(255,180,0,.6)'; ctx.lineWidth = 2; ctx.beginPath(); ctx.arc(f.x, f.y, r + 3 + Math.sin(now / 200) * 1.5, 0, TAU); ctx.stroke(); }
  }
  // blobs, small under big
  const lead = A.ranking()[0];
  const order = A.blobs.filter((b) => b.alive).sort((a, b) => a.m - b.m);
  for (const b of order) {
    const R = radius(b.m);
    if (Math.abs(b.x - cam.x) > vw + R || Math.abs(b.y - cam.y) > vh + R) continue;
    blob(ctx, b, now, S, R);
    if (b === lead) { ctx.font = `${Math.max(16, R * 0.7)}px system-ui,sans-serif`; ctx.textAlign = 'center'; ctx.fillText('👑', b.x, b.y - R - Math.max(8, R * 0.2)); }
  }
  for (const p of fx) { ctx.globalAlpha = Math.max(0, p.life); ctx.fillStyle = p.c; ctx.beginPath(); ctx.arc(p.x, p.y, p.r, 0, TAU); ctx.fill(); }
  ctx.globalAlpha = 1; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
  for (const t of texts) { ctx.globalAlpha = Math.min(1, t.life * 1.5); ctx.font = `900 ${20 / cam.z}px system-ui,sans-serif`; ctx.lineWidth = 5 / cam.z; ctx.strokeStyle = '#FFF'; ctx.fillStyle = S.ink; ctx.strokeText(t.t, t.x, t.y - 30); ctx.fillText(t.t, t.x, t.y - 30); }
  ctx.globalAlpha = 1;
  // HUD (screen space): size + place (left), clock (right)
  ctx.setTransform(scale, 0, 0, scale, 0, 0);
  const me = A.me(), rk = A.rank();
  ctx.fillStyle = 'rgba(255,255,255,.9)'; rr(ctx, 10, 10, 132, 40, 20); ctx.fill();
  ctx.fillStyle = S.ink; ctx.textAlign = 'left'; ctx.font = '900 21px system-ui,-apple-system,sans-serif'; ctx.fillText(String(Math.round(me.m)), 24, 31);
  ctx.textAlign = 'right'; ctx.font = '800 15px system-ui,sans-serif'; ctx.fillStyle = rk === 1 ? '#E2A100' : S.ink; ctx.fillText(`${MEDALS[rk - 1] || ''} ${place(rk)}`, 134, 31);
  const left = A.left();
  ctx.fillStyle = 'rgba(255,255,255,.9)'; rr(ctx, W - 76, 10, 66, 40, 20); ctx.fill();
  const clock = A.rule === 'last' ? `👥${A.alive()}` : A.rule === 'endless' ? `${Math.floor(left)}s` : `${Math.ceil(left)}s`;
  ctx.fillStyle = A.rule === 'timed' && left <= 10 && state === 'run' ? '#E2477A' : S.ink; ctx.textAlign = 'center'; ctx.font = '900 20px system-ui,sans-serif'; ctx.fillText(clock, W - 43, 31);
  if (state === 'ready') {
    ctx.fillStyle = 'rgba(255,255,255,.92)'; rr(ctx, 36, H * 0.62, W - 72, 74, 20); ctx.fill();
    ctx.fillStyle = S.ink; ctx.font = '900 20px system-ui,sans-serif'; ctx.fillText('Hold and drag to steer', W / 2, H * 0.62 + 26);
    ctx.font = '600 14px system-ui,sans-serif'; ctx.globalAlpha = 0.75; ctx.fillText({ timed: 'Gulp snacks and smaller blobs. 60 seconds.', last: 'One life each. The arena shrinks. Be the last one.', endless: 'One life. Grow as big as you can. Bots keep coming.' }[A.rule], W / 2, H * 0.62 + 52); ctx.globalAlpha = 1;
  }
  if (steer && state === 'run') { // a small ring where the thumb is: you always see your input
    ctx.strokeStyle = 'rgba(30,40,60,.25)'; ctx.lineWidth = 3; ctx.beginPath(); ctx.arc(steer.px, steer.py, 22, 0, TAU); ctx.stroke();
  }
}

// ------------------------------------------------------------------ input: hold and drag anywhere, the blob swims toward your finger
const toScreen = (e) => { const r = cv.getBoundingClientRect(); return [((e.clientX - r.left) / r.width) * W, ((e.clientY - r.top) / r.height) * H]; };
function aim(px, py) {
  const me = A.me(), sx = W / 2 + (me.x - cam.x) * cam.z, sy = H / 2 + (me.y - cam.y) * cam.z;
  const dx = px - sx, dy = py - sy, d = Math.hypot(dx, dy);
  if (d < 6) return { dx: 0, dy: 0, px, py };
  const k = Math.min(1, d / 70); return { dx: (dx / d) * k, dy: (dy / d) * k, px, py };
}
let down = false;
cv.addEventListener('pointerdown', (e) => {
  e.preventDefault();
  if (state === 'over') { if (endShown) start(); return; }
  if (state === 'ready') { state = 'run'; count(GAME, 'play', mode.kind === 'daily' ? 'daily' : 'quick'); }
  down = true; steer = aim(...toScreen(e));
  try { cv.setPointerCapture(e.pointerId); } catch { /* */ }
});
cv.addEventListener('pointermove', (e) => { if (down || (e.pointerType === 'mouse' && state === 'run')) { steer = aim(...toScreen(e)); } });
const up = () => { if (!down) return; down = false; if (steer) lastDir = { dx: steer.dx * 0.55, dy: steer.dy * 0.55 }; steer = null; };
cv.addEventListener('pointerup', up); cv.addEventListener('pointercancel', up);
cv.addEventListener('pointerleave', (e) => { if (e.pointerType === 'mouse' && steer) { lastDir = { dx: steer.dx, dy: steer.dy }; steer = null; } });
const keys = new Set();
document.addEventListener('keydown', (e) => {
  if (/^(INPUT|TEXTAREA|SELECT)$/.test(document.activeElement && document.activeElement.tagName)) return;
  if (['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'a', 'd', 'w', 's'].includes(e.key)) { keys.add(e.key); e.preventDefault(); if (state === 'ready') state = 'run'; keyDir(); }
  else if (e.key === 'r' || e.key === 'R') { e.preventDefault(); start(); }
  else if (e.key === 'm' || e.key === 'M') $('mute').click();
  else if ((e.key === ' ' || e.key === 'Enter') && state !== 'run' && document.activeElement && document.activeElement.tagName !== 'BUTTON') { e.preventDefault(); if (state === 'ready') state = 'run'; else start(); }
});
document.addEventListener('keyup', (e) => { keys.delete(e.key); keyDir(); });
function keyDir() {
  const dx = (keys.has('ArrowRight') || keys.has('d') ? 1 : 0) - (keys.has('ArrowLeft') || keys.has('a') ? 1 : 0), dy = (keys.has('ArrowDown') || keys.has('s') ? 1 : 0) - (keys.has('ArrowUp') || keys.has('w') ? 1 : 0);
  const l = Math.hypot(dx, dy); if (l) lastDir = { dx: dx / l, dy: dy / l };
}

// ------------------------------------------------------------------ results, share, card
function shareText() { return `${coreShare(A, label())}\nCan you be the biggest blob?`; }
function showOver(newBest) {
  const rk = A.rank(), me = A.me();
  const pl = `gulped ${me.gulps} blob${me.gulps === 1 ? '' : 's'}${newBest ? ' · new best' : ''}`;
  if (A.rule === 'endless') {
    $('over-title').textContent = `Gulped after ${Math.floor(A.t)}s`;
    $('over-score').textContent = Math.round(me.best).toLocaleString('en-US');
    $('over-line').textContent = `biggest size · ${pl}`;
  } else {
    $('over-title').textContent = rk === 1 ? (A.rule === 'last' ? 'Last blob standing! 👑' : 'You won! 👑') : `${MEDALS[rk - 1] || '🫧'} ${place(rk)} of ${A.blobs.length}`;
    $('over-score').textContent = Math.round(A.rule === 'last' ? me.best : me.m).toLocaleString('en-US');
    $('over-line').textContent = `${A.rule === 'last' ? (me.alive ? 'last one alive' : `lasted ${Math.floor(A.t)}s`) + ' · biggest size' : 'size at the bell'} · ${pl}`;
  }
  $('over-grid').textContent = A.ranking().slice(0, 5).map((b, i) => `${MEDALS[i] || `${i + 1}.`} ${b.me ? 'You' : b.name} ${Math.round(b.m)}`).join('\n') + `\n\n${coreShare(A, label())}`;
  const it = intents(GAME, shareText(), PATH); $('sx').href = it.x; $('sb').href = it.bsky; $('sw').href = it.whatsapp;
  $('over').hidden = false; shopVis(true);
  pass.afterWin($('over'), 'over');
}
function card() {
  const S = LOOKS[look], 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, S.g1); gr.addColorStop(1, S.g2); x.fillStyle = gr; x.fillRect(0, 0, 1080, 1350);
  const top = A.ranking().slice(0, 5);
  top.forEach((b, i) => { const R = 60 + (5 - i) * 18; blob(x, { ...b, x: 160 + i * 190, y: 640 - (i % 2) * 70, vx: 0, vy: 0, mood: 'eat' }, 0, S, R); });
  x.fillStyle = S.ink; x.textAlign = 'left'; x.font = '900 84px system-ui,sans-serif'; x.fillText('BLOB GULP', 80, 150);
  x.globalAlpha = 0.75; x.font = '700 40px system-ui,sans-serif'; x.fillText(mode.kind === 'daily' ? `Daily Arena #${dayNumber(mode.date)} · ${mode.date}` : { quick: 'Quick match', last: 'Last Blob Standing', endless: 'Endless' }[mode.kind], 80, 210); x.globalAlpha = 1;
  const rk = A.rank(); x.font = '900 120px system-ui,sans-serif'; x.fillText(A.rule === 'endless' ? `${Math.floor(A.t)}s alive` : `${MEDALS[rk - 1] || ''} ${place(rk)} of ${A.blobs.length}`, 80, 960);
  x.font = '700 48px system-ui,sans-serif'; x.fillText(`${A.rule === 'timed' ? 'size' : 'biggest'} ${Math.round(A.rule === 'timed' ? A.me().m : A.me().best)} · gulped ${A.me().gulps}`, 80, 1040);
  x.font = '800 44px system-ui,sans-serif'; x.fillText('Can you be the biggest blob?', 80, 1200);
  x.globalAlpha = 0.7; x.font = '600 32px system-ui,sans-serif'; x.fillText('Play free: cybermaxtools.com/games/blobgulp', 80, 1270);
  return c;
}
const fname = () => `blobgulp-${mode.kind === 'daily' ? mode.date : mode.kind}.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'); };
$('pass-btn').onclick = () => pass.open('header');
$('again').onclick = () => { start(); cv.focus(); };
document.addEventListener('visibilitychange', () => { last = performance.now(); acc = 0; });
function renderLooks() {
  const el = $('looks'); el.innerHTML = '';
  for (const [id, s] of Object.entries(LOOKS)) {
    const b = document.createElement('button'), 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.g1} 50%, ${s.acc} 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('blobgulp:look', id); renderLooks(); };
    el.appendChild(b);
  }
}
pass.onChange(() => { if (!canUse(LOOKS[look])) { look = 'meadow'; store('blobgulp:look', 'meadow'); } renderLooks(); renderModes(); });

// test + screenshot hooks (no effect on normal play)
window.__blobgulp = {
  state: () => ({ state, t: A.t, size: Math.round(A.me().m), rank: A.rank(), gulps: A.me().gulps, alive: A.me().alive, x: A.me().x, y: A.me().y, mode: mode.kind, rule: A.rule, left: A.alive(), endShown, blobs: A.blobs.length }),
  setMode,
  bot: (on = true) => { autoBot = on; if (on && state === 'ready') state = 'run'; },
  bell: () => { A.t = ROUND - 0.02; },
  shareText,
};
window.__cmxShot = async () => { start(); autoBot = true; for (let i = 0; i < 60 * 14; i++) { A.input = autoInput(A); A.step(); A.events.length = 0; } autoBot = false; cam = { x: A.me().x, y: A.me().y, z: 0.9 }; };

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