-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsnake.js
More file actions
440 lines (380 loc) · 24.3 KB
/
Copy pathsnake.js
File metadata and controls
440 lines (380 loc) · 24.3 KB
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
// Mini GTA-style procedural city demo (WebGL)
// Features: procedural grid city, walk/drive/shoot mechanics, pointer-lock mouselook
(function(){
const canvas = document.getElementById('gameCanvas');
const gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
if(!gl){ alert('WebGL required'); return; }
// Basic resize
function resize(){ const dpr = window.devicePixelRatio||1; canvas.width = Math.floor(canvas.clientWidth * dpr); canvas.height = Math.floor(canvas.clientHeight * dpr); gl.viewport(0,0,canvas.width,canvas.height); }
window.addEventListener('resize', resize);
resize();
// HUD
const modeName = document.getElementById('modeName');
const speedVal = document.getElementById('speedVal');
const ammoVal = document.getElementById('ammoVal');
// Controls
const startBtn = document.getElementById('startBtn');
const resetBtn = document.getElementById('resetBtn');
// Simple shader to draw flat colored geometry (2D positions in clip after projection)
const vsSrc = `attribute vec3 a_pos; attribute vec3 a_col; uniform mat4 u_proj; uniform mat4 u_view; varying vec3 v_col; void main(){ v_col=a_col; gl_Position = u_proj * u_view * vec4(a_pos,1.0); }`;
const fsSrc = `precision mediump float; varying vec3 v_col; void main(){ gl_FragColor = vec4(v_col,1.0); }`;
function compile(src,type){ const s=gl.createShader(type); gl.shaderSource(s,src); gl.compileShader(s); if(!gl.getShaderParameter(s,gl.COMPILE_STATUS)) console.error(gl.getShaderInfoLog(s)); return s; }
const prog = gl.createProgram(); gl.attachShader(prog,compile(vsSrc,gl.VERTEX_SHADER)); gl.attachShader(prog,compile(fsSrc,gl.FRAGMENT_SHADER)); gl.linkProgram(prog); gl.useProgram(prog);
const a_pos = gl.getAttribLocation(prog,'a_pos'); const a_col = gl.getAttribLocation(prog,'a_col');
const u_proj = gl.getUniformLocation(prog,'u_proj'); const u_view = gl.getUniformLocation(prog,'u_view');
// Simple geometry buffers (dynamic)
const vbo = gl.createBuffer();
// Camera / player state
const player = { x:0, y:1.6, z:0, yaw:0, pitch:0, speed:0.0, mode:'walk', vehicle:null };
const keys = {};
let pointerLocked = false;
// World: procedural grid city
const city = { blocks:[], seed: Math.floor(Math.random()*65536), size: 12, blockSize: 12 };
function rnd(){ city.seed = (city.seed * 1664525 + 1013904223) | 0; return ((city.seed >>> 0) / 4294967296); }
function genCity(){ city.blocks.length = 0; const s = city.size; const bs = city.blockSize; for(let gx=-s; gx<=s; gx++){ for(let gz=-s; gz<=s; gz++){ const centerX = gx * bs; const centerZ = gz * bs; const type = rnd() < 0.12 ? 'park' : (rnd() < 0.6 ? 'res' : 'commercial'); const height = type==='park' ? 0 : Math.floor(1 + rnd()*6); city.blocks.push({ gx, gz, x:centerX, z:centerZ, type, height }); } } }
genCity();
// Simple box builder for buildings and road planes
function pushBox(verts, x,y,z, w,h,d, col){ const hw = w/2, hd = d/2; const y0 = y; const y1 = y + h;
// 12 triangles (two per face) but we'll do top + 4 sides (no bottom)
// top
pushTri(verts, x-hw, y1, z-hd, x+hw, y1, z-hd, x+hw, y1, z+hd, col);
pushTri(verts, x-hw, y1, z-hd, x+hw, y1, z+hd, x-hw, y1, z+hd, col);
// sides (front, right, back, left)
pushRect(verts, x-hw, y0, z-hd, x+hw, y1, z-hd, col);
pushRect(verts, x+hw, y0, z-hd, x+hw, y1, z+hd, col);
pushRect(verts, x-hw, y0, z+hd, x+hw, y1, z+hd, col);
pushRect(verts, x-hw, y0, z-hd, x-hw, y1, z+hd, col);
}
function pushRect(verts,x0,y0,z0,x1,y1,z1,col){ pushTri(verts,x0,y0,z0, x1,y0,z1, x1,y1,z1, col); pushTri(verts,x0,y0,z0, x1,y1,z1, x0,y1,z0, col); }
function pushTri(verts, x1,y1,z1, x2,y2,z2, x3,y3,z3, col){ verts.push(x1,y1,z1, col[0],col[1],col[2]); verts.push(x2,y2,z2, col[0],col[1],col[2]); verts.push(x3,y3,z3, col[0],col[1],col[2]); }
// Road grid (flat quads)
function buildScene(){ const verts = []; // each vertex: x,y,z,r,g,b
// roads: simple grid along blocks
const roadCol = [0.12,0.12,0.12];
for(const b of city.blocks){ // horizontal road along block's center
const roadW = city.blockSize * 0.18;
pushRect(verts, b.x - city.blockSize/2, 0.01, b.z - roadW/2, b.x + city.blockSize/2, 0.01, b.z + roadW/2, roadCol);
pushRect(verts, b.x - roadW/2, 0.01, b.z - city.blockSize/2, b.x + roadW/2, 0.01, b.z + city.blockSize/2, roadCol);
// buildings
if(b.type!=='park'){
const bw = city.blockSize * 0.6; const bd = city.blockSize * 0.6; const bh = 1.6 + b.height * 1.2;
const col = b.type==='res' ? [0.7 - rnd()*0.2,0.7 - rnd()*0.2,0.75 - rnd()*0.25] : [0.85 - rnd()*0.3,0.7 - rnd()*0.3,0.55 - rnd()*0.3];
pushBox(verts, b.x, 0.0, b.z, bw, bh, bd, col);
} else {
// park: scatter low trees as small boxes
for(let i=0;i<6;i++){ const ox = (rnd()-0.5)*city.blockSize*0.6; const oz = (rnd()-0.5)*city.blockSize*0.6; pushBox(verts, b.x+ox, 0.0, b.z+oz, 0.6, 1.2, 0.6, [0.18, 0.6 - rnd()*0.2, 0.18]); }
}
}
return new Float32Array(verts);
}
// Simple projection and view
function perspective(fov, aspect, near, far){ const f = 1/Math.tan(fov/2); const nf = 1/(near-far); const out = new Float32Array(16); out[0]=f/aspect; out[5]=f; out[10]=(far+near)*nf; out[11]=-1; out[14]=(2*far*near)*nf; out[15]=0; return out; }
function lookAt(px,py,pz, tx,ty,tz, ux,uy,uz){ // compute view matrix
const zx = px-tx, zy = py-ty, zz = pz-tz; let zl = Math.hypot(zx,zy,zz); if(zl===0) zl=1; const zx0=zx/zl, zy0=zy/zl, zz0=zz/zl;
const xx = uy*zz0 - uz*zy0, xy = uz*zx0 - ux*zz0, xz = ux*zy0 - uy*zx0; let xl = Math.hypot(xx,xy,xz); if(xl===0) xl=1; const xx0=xx/xl, xy0=xy/xl, xz0=xz/xl;
const yx = zy0*xz0 - zz0*xy0, yy = zz0*xx0 - zx0*xz0, yz = zx0*xy0 - zy0*xx0;
const out = new Float32Array(16);
out[0]=xx0; out[1]=yx; out[2]=zx0; out[3]=0;
out[4]=xy0; out[5]=yy; out[6]=zy0; out[7]=0;
out[8]=xz0; out[9]=yz; out[10]=zz0; out[11]=0;
out[12]=-(xx0*px + xy0*py + xz0*pz);
out[13]=-(yx*px + yy*py + yz*pz);
out[14]=-(zx0*px + zy0*py + zz0*pz);
out[15]=1;
return out;
}
// Build initial scene VBO
let sceneBuf = buildScene();
// Simple render function
function render(){ gl.clearColor(0.53,0.78,0.92,1.0); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); gl.enable(gl.DEPTH_TEST);
// update projection & view
const aspect = canvas.width / canvas.height; const proj = perspective(Math.PI/3, aspect, 0.1, 200.0);
// compute camera forward vector from yaw/pitch
const cy = Math.cos(player.yaw), sy = Math.sin(player.yaw); const cp = Math.cos(player.pitch); const sp = Math.sin(player.pitch);
const fx = sy * cp, fz = cy * cp, fy = sp;
const view = lookAt(player.x, player.y, player.z, player.x+fx, player.y+fy, player.z+fz, 0,1,0);
gl.uniformMatrix4fv(u_proj,false,proj); gl.uniformMatrix4fv(u_view,false,view);
// bind buffer & attributes
gl.bindBuffer(gl.ARRAY_BUFFER, vbo);
gl.bufferData(gl.ARRAY_BUFFER, sceneBuf, gl.STATIC_DRAW);
const stride = 6 * 4; // floats per vertex
gl.enableVertexAttribArray(a_pos); gl.vertexAttribPointer(a_pos,3,gl.FLOAT,false,stride,0);
gl.enableVertexAttribArray(a_col); gl.vertexAttribPointer(a_col,3,gl.FLOAT,false,stride,3*4);
gl.drawArrays(gl.TRIANGLES, 0, sceneBuf.length / 6);
}
// Movement / physics basic
let last = performance.now();
let ammo = 24;
function update(){ const now = performance.now(); const dt = Math.min(0.05, (now-last)/1000); last = now;
// speed target
let targetSpeed = 0;
if(player.mode==='walk'){ targetSpeed = (keys['Shift']||keys['ShiftLeft']) ? 6.0 : 3.0; }
else if(player.mode==='drive'){ targetSpeed = (keys['Shift']||keys['ShiftLeft']) ? 12.0 : 8.0; }
// calculate forward/right from yaw
const fwd = { x: Math.sin(player.yaw), z: Math.cos(player.yaw) };
const right = { x: Math.cos(player.yaw), z: -Math.sin(player.yaw) };
let mvx=0, mvz=0;
if(keys['w']||keys['W']) mvz += 1; if(keys['s']||keys['S']) mvz -= 1; if(keys['a']||keys['A']) mvx -= 1; if(keys['d']||keys['D']) mvx += 1;
const ml = Math.hypot(mvx,mvz) || 1;
const move = (targetSpeed * dt);
player.x += (fwd.x*(mvz/ml) + right.x*(mvx/ml)) * move;
player.z += (fwd.z*(mvz/ml) + right.z*(mvx/ml)) * move;
// simple camera yaw/pitch are updated by mouse handlers
// update HUD
modeName.textContent = player.mode.charAt(0).toUpperCase() + player.mode.slice(1);
speedVal.textContent = (Math.round(targetSpeed*10)/10).toString();
ammoVal.textContent = String(ammo);
}
// Shooting (raycast simple against building bounding boxes)
function shoot(){ if(ammo<=0) return; ammo--; // ray origin at eye
const ox = player.x, oy = player.y, oz = player.z;
const cy = Math.cos(player.yaw), sy = Math.sin(player.yaw); const cp = Math.cos(player.pitch), sp = Math.sin(player.pitch);
const dx = Math.sin(player.yaw)*Math.cos(player.pitch), dy = Math.sin(player.pitch), dz = Math.cos(player.yaw)*Math.cos(player.pitch);
// check collision with nearest building center points (approx)
let hit = false;
for(const b of city.blocks){ if(b.type==='park') continue; const bx = b.x, bz = b.z; const dist = Math.hypot(bx-ox, bz-oz); if(dist < 18){ // hit chance based on angle
const ang = Math.atan2(bx-ox, bz-oz); const da = Math.abs(normalizeAngle(ang - player.yaw)); if(da < 0.25){ hit=true; break; } } }
if(hit) { // small feedback: brighten sky color briefly
gl.clearColor(0.8,0.9,0.6,1.0); setTimeout(()=>gl.clearColor(0.53,0.78,0.92,1.0),120);
}
}
function normalizeAngle(a){ while(a > Math.PI) a -= Math.PI*2; while(a < -Math.PI) a += Math.PI*2; return a; }
// Input: pointer lock & mouse
canvas.addEventListener('click', ()=>{ if(!pointerLocked && document.pointerLockElement !== canvas) canvas.requestPointerLock(); });
document.addEventListener('pointerlockchange', ()=>{ pointerLocked = (document.pointerLockElement === canvas); });
window.addEventListener('mousemove', e=>{ if(!pointerLocked) return; player.yaw += e.movementX * 0.0025; player.pitch -= e.movementY * 0.0025; player.pitch = Math.max(-1.2, Math.min(1.2, player.pitch)); });
window.addEventListener('keydown', e=>{ keys[e.key]=true; if(e.key==='e' || e.key==='E'){ // toggle vehicle
if(player.mode==='walk') player.mode='drive'; else player.mode='walk'; }
if(e.key===' '){ /* space: reserved */ }
if(e.key==='1'){ /* future */ }
// prevent default for space and arrow keys when controlling
});
window.addEventListener('keyup', e=>{ keys[e.key]=false; });
window.addEventListener('mousedown', e=>{ if(e.button===0) shoot(); });
// reset / start
startBtn.addEventListener('click', ()=>{ canvas.requestPointerLock(); last = performance.now(); loop(); });
resetBtn.addEventListener('click', ()=>{ city.seed = Math.floor(Math.random()*65536); genCity(); sceneBuf = buildScene(); });
// main loop
let running = false;
function loop(){ if(running) return; running = true; function tick(){ update(); render(); requestAnimationFrame(tick); } tick(); }
// initial buffer upload
gl.enable(gl.CULL_FACE); gl.cullFace(gl.BACK);
gl.bindBuffer(gl.ARRAY_BUFFER, vbo);
sceneBuf = buildScene(); gl.bufferData(gl.ARRAY_BUFFER, sceneBuf, gl.STATIC_DRAW);
// expose simple global for debug
window._miniCity = { city, player };
})();
// WebGL-first-person-lite + multiple weapons
// Simple 3D-looking first-person view implemented with WebGL billboards.
// Controls: WASD to move, mouse to turn, left-click to shoot, 1/2/3 switch weapons.
const canvas = document.getElementById('snakeCanvas');
const gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
if(!gl) {
alert('WebGL not supported in this browser.');
}
// UI
const startBtn = document.getElementById('startBtn');
const pauseBtn = document.getElementById('pauseBtn');
const restartBtn = document.getElementById('restartBtn');
const scoreBtn = document.getElementById('scoreBtn');
const statsOverlay = document.getElementById('statsOverlay');
const statsContent = document.getElementById('statsContent');
const resetHighBtn = document.getElementById('resetHighBtn');
const closeStatsBtn = document.getElementById('closeStatsBtn');
let running = false;
let score = 0, highScore = 0, plays = 0;
// world objects (2D positions on ground plane)
let enemies = [];
let apples = [];
// player in world coords
const player = { x: 0, y: 0, dir: 0, speed: 3.0 };
// weapons (ammo, mags, reload)
const weapons = {
pistol: { name:'Pistol', cooldown:0.35, auto:false, last:0, mag:12, magMax:12, reserve:48, reloadTime:1.2, reloading:false, reloadStart:0 },
shotgun: { name:'Shotgun', cooldown:0.9, auto:false, last:0, mag:6, magMax:6, reserve:24, reloadTime:1.6, reloading:false, reloadStart:0 },
smg: { name:'SMG', cooldown:0.08, auto:true, last:0, mag:30, magMax:30, reserve:120, reloadTime:2.0, reloading:false, reloadStart:0 }
};
let currentWeapon = 'pistol';
// HUD elements
const weaponNameEl = document.getElementById('weaponName');
const ammoDisplayEl = document.getElementById('ammoDisplay');
const reloadFillEl = document.getElementById('reloadFill');
function updateHUD(){
const w = weapons[currentWeapon];
if(weaponNameEl) weaponNameEl.textContent = `Weapon: ${w.name}`;
if(ammoDisplayEl) ammoDisplayEl.textContent = `Ammo: ${w.mag} / ${w.reserve}`;
if(reloadFillEl){
if(w.reloading){ const now = performance.now()/1000; const p = Math.min(1, (now - w.reloadStart)/w.reloadTime); reloadFillEl.style.width = `${Math.round(p*100)}%`; }
else reloadFillEl.style.width = '0%';
}
}
function startReload(key){ const w = weapons[key]; if(!w) return; if(w.reloading) return; if(w.mag>=w.magMax) return; if(w.reserve<=0) return; w.reloading = true; w.reloadStart = performance.now()/1000; updateHUD(); }
function tryCompleteReload(key){ const w = weapons[key]; if(!w || !w.reloading) return; const now = performance.now()/1000; if(now - w.reloadStart >= w.reloadTime){ const need = w.magMax - w.mag; const take = Math.min(need, w.reserve); w.mag += take; w.reserve -= take; w.reloading = false; w.reloadStart = 0; updateHUD(); } }
// input
let keys = {};
let mouse = { dx:0, dy:0, down:false };
// timing
let lastTime = 0;
// simple audio
let audioCtx = null;
function beep(freq,dur=0.06){ try{ if(!audioCtx) audioCtx = new (window.AudioContext||window.webkitAudioContext)(); const o=audioCtx.createOscillator(), g=audioCtx.createGain(); o.frequency.value=freq; o.type='sine'; o.connect(g); g.connect(audioCtx.destination); g.gain.setValueAtTime(0.0001,audioCtx.currentTime); g.gain.exponentialRampToValueAtTime(0.08,audioCtx.currentTime+0.01); o.start(); g.gain.exponentialRampToValueAtTime(0.0001,audioCtx.currentTime+dur); o.stop(audioCtx.currentTime+dur+0.02);}catch(e){} }
// helper: create shader program
function compileShader(src, type){ const s = gl.createShader(type); gl.shaderSource(s, src); gl.compileShader(s); if(!gl.getShaderParameter(s, gl.COMPILE_STATUS)) console.error(gl.getShaderInfoLog(s)); return s; }
const vs = "attribute vec2 a_pos; attribute vec3 a_color; varying vec3 v_color; void main(){ v_color=a_color; gl_Position = vec4(a_pos,0.0,1.0); }";
const fs = "precision mediump float; varying vec3 v_color; void main(){ gl_FragColor = vec4(v_color,1.0); }";
const prog = gl.createProgram(); gl.attachShader(prog, compileShader(vs, gl.VERTEX_SHADER)); gl.attachShader(prog, compileShader(fs, gl.FRAGMENT_SHADER)); gl.linkProgram(prog);
gl.useProgram(prog);
const posLoc = gl.getAttribLocation(prog, 'a_pos');
const colorLoc = gl.getAttribLocation(prog, 'a_color');
const vbo = gl.createBuffer();
function worldToClip(x, y){
// camera transform: player at origin looking along +Y
const dx = x - player.x;
const dy = y - player.y;
const cos = Math.cos(-player.dir);
const sin = Math.sin(-player.dir);
const camX = dx * cos - dy * sin;
const camZ = dx * sin + dy * cos;
// simple frustum: project with focal length
if(camZ <= 0.1) return null; // behind camera
const f = 1.2; // focal
const sx = (camX / camZ) * f; // -inf..inf
const sy = (1.0 / camZ) * f; // use for vertical size
// map to clip space (-1..1)
const clipX = sx; // we'll scale by aspect later when building quad
const clipY = 0.0; // we'll compute vertex y separately
return { camZ, sx, sy };
}
function buildSceneVertices(){
// build triangles for all billboards (enemies and apples)
const verts = [];
const aspect = canvas.width / canvas.height;
function addBill(x,y,size,color){
const p = worldToClip(x,y);
if(!p) return;
const screenW = size * p.sy * -1; // negative so closer = bigger
const w = screenW * aspect;
const h = screenW;
// center in clip: cx = p.sx, cy = 0.0
const cx = p.sx;
// build two triangles (CCW)
const x1 = cx - w; const x2 = cx + w;
const y1 = -h; const y2 = h;
// convert normalized clip coords (we use full clip directly)
verts.push(x1, y1, color[0], color[1], color[2]);
verts.push(x2, y1, color[0], color[1], color[2]);
verts.push(x2, y2, color[0], color[1], color[2]);
verts.push(x1, y1, color[0], color[1], color[2]);
verts.push(x2, y2, color[0], color[1], color[2]);
verts.push(x1, y2, color[0], color[1], color[2]);
}
for(const e of enemies) addBill(e.x, e.y, 0.6, [0.96,0.62,0.04]);
for(const a of apples) addBill(a.x, a.y, 0.35, [1.0,0.42,0.42]);
return new Float32Array(verts);
}
function renderWebGL(){
gl.viewport(0,0,canvas.width,canvas.height);
gl.clearColor(0.03,0.05,0.08,1.0);
gl.clear(gl.COLOR_BUFFER_BIT);
const verts = buildSceneVertices();
if(verts.length===0) return;
gl.bindBuffer(gl.ARRAY_BUFFER, vbo);
gl.bufferData(gl.ARRAY_BUFFER, verts, gl.STATIC_DRAW);
const stride = 5 * 4; // float size
gl.enableVertexAttribArray(posLoc);
gl.vertexAttribPointer(posLoc, 2, gl.FLOAT, false, stride, 0);
gl.enableVertexAttribArray(colorLoc);
gl.vertexAttribPointer(colorLoc, 3, gl.FLOAT, false, stride, 2*4);
gl.drawArrays(gl.TRIANGLES, 0, verts.length / 5);
}
// simple world logic (enemies approach player on ground plane)
function spawnEnemy(){ const ang = Math.random()*Math.PI*2; const dist=6+Math.random()*6; enemies.push({ x: player.x + Math.cos(ang)*dist, y: player.y + Math.sin(ang)*dist, speed: 1.0 + Math.random()*0.8, hp:1 }); }
function spawnApple(){ const ang = Math.random()*Math.PI*2; const dist = 2+Math.random()*6; apples.push({ x: player.x + Math.cos(ang)*dist, y: player.y + Math.sin(ang)*dist }); }
let spawnTimer=0, appleTimer=0;
function update(dt){
// movement
let mvx=0,mvy=0;
if(keys['w']||keys['W']) mvy += 1;
if(keys['s']||keys['S']) mvy -= 1;
if(keys['a']||keys['A']) mvx -= 1;
if(keys['d']||keys['D']) mvx += 1;
const len = Math.hypot(mvx,mvy) || 1;
// translate local movement to world
const forward = { x: Math.sin(player.dir), y: Math.cos(player.dir) };
const right = { x: Math.cos(player.dir), y: -Math.sin(player.dir) };
player.x += (forward.x*(mvy/len) + right.x*(mvx/len)) * player.speed * dt;
player.y += (forward.y*(mvy/len) + right.y*(mvx/len)) * player.speed * dt;
// turn with mouse dx
player.dir += mouse.dx * 0.002;
mouse.dx = 0;
// enemies move toward player
for(let i=enemies.length-1;i>=0;i--){ const e = enemies[i]; const dx = player.x - e.x; const dy = player.y - e.y; const d = Math.hypot(dx,dy)||0.001; e.x += (dx/d)*e.speed*dt; e.y += (dy/d)*e.speed*dt; if(d < 0.6){ // hit
running=false; plays++; try{ localStorage.setItem('snakePlays', String(plays)); }catch(e){}; beep(120,0.2); startBtn.disabled=false; }
}
// apples collect
for(let i=apples.length-1;i>=0;i--){ const a=apples[i]; if(Math.hypot(a.x-player.x,a.y-player.y)<0.9){ apples.splice(i,1); score++; if(score>highScore){ highScore=score; try{ localStorage.setItem('snakeHighScore',String(highScore)); }catch(e){} } if(scoreBtn) scoreBtn.textContent = `Score: ${score} (HS: ${highScore})`; beep(660,0.08); } }
// spawn
spawnTimer += dt; if(spawnTimer>1.2){ spawnTimer=0; spawnEnemy(); }
appleTimer += dt; if(appleTimer>5.5){ appleTimer=0; spawnApple(); }
// per-frame reload progress & completion for current weapon
const cw = weapons[currentWeapon];
if(cw && cw.reloading){
tryCompleteReload(currentWeapon);
updateHUD();
}
}
function rayHitEnemy(angle){
// ray from player at given angle, check line-circle intersection in world plane
let hitIndex = -1; let hitDist = Infinity;
const rx = Math.sin(angle), ry = Math.cos(angle);
for(let i=0;i<enemies.length;i++){ const e=enemies[i]; const dx=e.x-player.x; const dy=e.y-player.y; const t = dx*rx + dy*ry; if(t<=0) continue; const cx = player.x + rx*t; const cy = player.y + ry*t; const dist2 = (e.x-cx)*(e.x-cx)+(e.y-cy)*(e.y-cy); if(dist2 < (0.6*0.6)){ if(t < hitDist){ hitDist = t; hitIndex = i; } } }
return hitIndex;
}
function killEnemy(index){ if(index>=0 && index<enemies.length){ enemies.splice(index,1); score++; if(score>highScore){ highScore=score; try{ localStorage.setItem('snakeHighScore',String(highScore)); }catch(e){} } if(scoreBtn) scoreBtn.textContent = `Score: ${score} (HS: ${highScore})`; } }
function shoot(){
const w = weapons[currentWeapon]; const now = performance.now()/1000;
// check reload completion
if(w.reloading) { tryCompleteReload(currentWeapon); return; }
if(now - w.last < w.cooldown) return;
if(w.mag <= 0){ startReload(currentWeapon); return; }
w.last = now;
w.mag -= 1;
updateHUD();
if(currentWeapon==='pistol'){
const ang = player.dir; const hit = rayHitEnemy(ang); if(hit>=0) killEnemy(hit); beep(880,0.08);
} else if(currentWeapon==='shotgun'){
const base = player.dir; for(let i=0;i<7;i++){ const spread = (i-3)*0.06; const hit = rayHitEnemy(base + spread); if(hit>=0) killEnemy(hit); } beep(900,0.04);
} else if(currentWeapon==='smg'){
const ang = player.dir; const hit = rayHitEnemy(ang); if(hit>=0) killEnemy(hit); beep(780,0.02);
}
}
// render loop
function frame(t){ const now = t/1000; const dt = Math.min(0.05, (now - lastTime)||0.016); lastTime = now; if(running){ update(dt); renderWebGL(); } requestAnimationFrame(frame); }
// input handling
window.addEventListener('mousemove', e=>{ mouse.dx += e.movementX || 0; });
window.addEventListener('mousedown', e=>{ if(e.button===0){ mouse.down=true; shoot(); } });
window.addEventListener('mouseup', e=>{ if(e.button===0) mouse.down=false; });
window.addEventListener('keydown', e=>{ keys[e.key]=true; if(e.key==='1') currentWeapon='pistol'; if(e.key==='2') currentWeapon='shotgun'; if(e.key==='3') currentWeapon='smg'; if(e.key==='Escape'){ running=false; startBtn.disabled=false; } });
window.addEventListener('keyup', e=>{ keys[e.key]=false; });
// listen for reload key and update HUD when weapon switches
window.addEventListener('keydown', e=>{
if(e.key.toLowerCase() === 'r'){
startReload(currentWeapon);
}
// update HUD on weapon switch keys
if(e.key === '1' || e.key === '2' || e.key === '3'){
// small timeout to ensure currentWeapon was changed above
setTimeout(()=>updateHUD(), 0);
}
});
// UI wiring
startBtn.addEventListener('click', ()=>{ if(!running){ running=true; startBtn.disabled=true; lastTime = performance.now()/1000; requestAnimationFrame(frame); } });
pauseBtn.addEventListener('click', ()=>{ running = !running; pauseBtn.textContent = running? 'Pause':'Resume'; if(!running){ startBtn.disabled=false; } else { startBtn.disabled=true; lastTime = performance.now()/1000; } });
restartBtn.addEventListener('click', ()=>{ enemies=[]; apples=[]; score=0; running=false; startBtn.disabled=false; });
scoreBtn.addEventListener('click', ()=>{ statsContent.innerHTML = `<div>High score: <strong>${highScore}</strong></div><div>Plays: <strong>${plays}</strong></div>`; statsOverlay.style.display='flex'; });
closeStatsBtn.addEventListener('click', ()=>{ statsOverlay.style.display='none'; });
resetHighBtn.addEventListener('click', ()=>{ highScore=0; try{ localStorage.removeItem('snakeHighScore'); }catch(e){}; if(scoreBtn) scoreBtn.textContent = `Score: ${score} (HS: ${highScore})`; statsContent.innerHTML = `<div>High score reset</div>`; });
// init
try{ highScore = parseInt(localStorage.getItem('snakeHighScore')||'0',10)||0; plays = parseInt(localStorage.getItem('snakePlays')||'0',10)||0; if(scoreBtn) scoreBtn.textContent = `Score: ${score} (HS: ${highScore})`; }catch(e){}
spawnApple(); spawnEnemy();
updateHUD();