🎮ArcadeLab

Pixel Quest - The Lost Crystal

by PixelFlame92
1805 lines48.2 KB
▶ Play
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no,viewport-fit=cover">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="mobile-web-app-capable" content="yes">
<meta name="theme-color" content="#0d1b0d">
<title>Pixel Quest - The Lost Crystal</title>
<style>
  *{
    margin:0;padding:0;box-sizing:border-box;
    -webkit-tap-highlight-color:transparent;
    -webkit-user-select:none;user-select:none;
    -webkit-touch-callout:none;
  }
  html,body{
    width:100%;height:100%;overflow:hidden;
    background:#0d1b0d;
    touch-action:none;
    overscroll-behavior:none;
    font-family:"Courier New",Courier,monospace;
  }
  canvas#game{
    display:block;position:fixed;left:0;top:0;
    width:100%;height:100%;
    image-rendering:pixelated;
    image-rendering:-moz-crisp-edges;
    image-rendering:crisp-edges;
    touch-action:none;
  }

  /* ---------- MUTE ---------- */
  #mute{
    position:fixed;top:8px;right:8px;
    width:44px;height:44px;
    display:none;align-items:center;justify-content:center;
    border-radius:10px;
    background:rgba(0,0,0,0.5);
    border:2px solid rgba(255,255,255,0.35);
    color:#fff;font-size:20px;line-height:1;
    z-index:30;cursor:pointer;touch-action:none;
  }
  #mute:active{background:rgba(255,255,255,0.25);}
  body.playing #mute{display:flex;}

  /* ---------- JOYSTICK ---------- */
  #joy{
    position:fixed;left:18px;bottom:18px;
    width:128px;height:128px;border-radius:50%;
    background:rgba(255,255,255,0.10);
    border:2px solid rgba(255,255,255,0.30);
    display:none;z-index:25;touch-action:none;
  }
  #knob{
    position:absolute;left:50%;top:50%;
    width:54px;height:54px;margin:-27px 0 0 -27px;
    border-radius:50%;
    background:rgba(255,255,255,0.35);
    border:2px solid rgba(255,255,255,0.55);
    pointer-events:none;
    will-change:transform;
  }
  body.playing #joy{display:block;}

  /* ---------- BUTTONS ---------- */
  .btn{
    position:fixed;z-index:25;
    display:none;align-items:center;justify-content:center;
    border-radius:50%;
    background:rgba(255,255,255,0.14);
    border:2px solid rgba(255,255,255,0.42);
    color:#fff;font-weight:bold;
    text-shadow:0 2px 0 rgba(0,0,0,0.5);
    touch-action:none;cursor:pointer;
    letter-spacing:0.5px;
  }
  .btn:active,.btn.active{background:rgba(255,255,255,0.42);transform:scale(0.95);}
  body.playing .btn{display:flex;}

  #bA{right:18px;bottom:18px;width:82px;height:82px;font-size:30px;}
  #bB{right:112px;bottom:34px;width:72px;height:72px;font-size:26px;}
  #bRun{right:26px;bottom:112px;width:70px;height:48px;border-radius:24px;font-size:14px;}

  @media (max-width:360px){
    #joy{width:104px;height:104px;left:12px;bottom:12px;}
    #knob{width:44px;height:44px;margin:-22px 0 0 -22px;}
    #bA{width:70px;height:70px;right:12px;bottom:12px;font-size:26px;}
    #bB{width:62px;height:62px;right:92px;bottom:26px;font-size:22px;}
    #bRun{width:62px;height:42px;right:16px;bottom:94px;font-size:13px;}
  }

  /* ---------- MENU / OVERLAY ---------- */
  #menu{
    position:fixed;inset:0;z-index:60;
    display:flex;align-items:center;justify-content:center;
    background:rgba(5,10,20,0.82);
    padding:20px;
    touch-action:none;
  }
  #menuInner{
    max-width:520px;width:100%;
    text-align:center;color:#fff;
    background:rgba(15,25,40,0.92);
    border:3px solid #3a6ea5;
    border-radius:14px;
    padding:22px 18px 26px;
    box-shadow:0 0 0 4px rgba(0,0,0,0.5), 0 12px 40px rgba(0,0,0,0.7);
  }
  #menuInner h1{
    font-size:clamp(22px,6vw,36px);
    letter-spacing:2px;
    color:#ffd94a;
    text-shadow:0 3px 0 #8a5a00, 0 0 18px rgba(255,217,74,0.5);
    margin-bottom:4px;
  }
  #menuInner h2{
    font-size:clamp(12px,3.4vw,18px);
    color:#8fd3ff;letter-spacing:3px;
    margin-bottom:14px;font-weight:normal;
  }
  #menuInner p{
    font-size:clamp(11px,3vw,14px);
    line-height:1.65;color:#c8d8e8;
    margin-bottom:18px;white-space:pre-line;
  }
  #menuInner button{
    font-family:inherit;
    font-size:clamp(16px,4.5vw,22px);
    font-weight:bold;letter-spacing:2px;
    color:#0d1b0d;
    background:linear-gradient(#ffe066,#f0b400);
    border:none;border-radius:10px;
    padding:16px 44px;
    cursor:pointer;
    box-shadow:0 5px 0 #8a5a00, 0 8px 18px rgba(0,0,0,0.5);
    touch-action:none;
    min-width:200px;
  }
  #menuInner button:active{
    transform:translateY(4px);
    box-shadow:0 1px 0 #8a5a00;
  }
</style>
</head>
<body>

<canvas id="game"></canvas>
<div id="mute">🔊</div>
<div id="joy"><div id="knob"></div></div>
<div class="btn" id="bA">A</div>
<div class="btn" id="bB">B</div>
<div class="btn" id="bRun">RUN</div>
<div id="menu"><div id="menuInner"></div></div>

<script>
"use strict";

/* =========================================================
   PIXEL QUEST - THE LOST CRYSTAL
   Single file 16-bit style adventure game
   ========================================================= */

/* ---------------- UTILITIES ---------------- */
const clamp = (v,a,b)=> v<a?a:(v>b?b:v);
const rnd = (a,b)=> a + Math.random()*(b-a);
function hash2(x,y){
  let n = (x*374761393 + y*668265263) | 0;
  n = (n ^ (n >>> 13)) * 1274126177 | 0;
  return ((n ^ (n >>> 16)) >>> 0);
}

/* ---------------- AUDIO ---------------- */
let actx = null;
let muted = false;

function initAudio(){
  if(!actx){
    try{ actx = new (window.AudioContext || window.webkitAudioContext)(); }catch(e){ actx=null; }
  }
  if(actx && actx.state === 'suspended'){ actx.resume(); }
}

function beep(freq, dur, type, vol){
  if(muted) return;
  initAudio();
  if(!actx) return;
  try{
    const t = actx.currentTime;
    const o = actx.createOscillator();
    const g = actx.createGain();
    o.type = type || 'square';
    o.frequency.setValueAtTime(freq, t);
    g.gain.setValueAtTime(vol === undefined ? 0.05 : vol, t);
    g.gain.exponentialRampToValueAtTime(0.0001, t + dur);
    o.connect(g); g.connect(actx.destination);
    o.start(t); o.stop(t + dur + 0.02);
  }catch(e){}
}

function sfxHit(){ beep(220,0.09,'square',0.06); }
function sfxSwing(){ beep(700,0.05,'square',0.035); }
function sfxCoin(){ beep(1046,0.06,'square',0.05); setTimeout(()=>beep(1568,0.09,'square',0.05),55); }
function sfxCrystal(){
  beep(880,0.09,'sine',0.06);
  setTimeout(()=>beep(1174,0.09,'sine',0.06),90);
  setTimeout(()=>beep(1568,0.16,'sine',0.06),180);
}
function sfxHurt(){ beep(160,0.18,'sawtooth',0.07); }
function sfxTalk(){ beep(520,0.05,'square',0.04); }
function sfxWin(){
  const n=[523,659,784,1046];
  n.forEach((f,i)=>setTimeout(()=>beep(f,0.22,'square',0.06), i*130));
}
function sfxLose(){
  const n=[392,330,262,196];
  n.forEach((f,i)=>setTimeout(()=>beep(f,0.28,'sawtooth',0.07), i*160));
}

/* ---------------- CANVAS ---------------- */
const cvs = document.getElementById('game');
const ctx = cvs.getContext('2d', { alpha:false });

let W = 320, H = 240;
let SCALE = 3;
let VIEW_W = 100, VIEW_H = 100;

function resizeCanvas(){
  W = Math.max(200, Math.floor(window.innerWidth));
  H = Math.max(200, Math.floor(window.innerHeight));
  cvs.width = W;
  cvs.height = H;
  SCALE = Math.max(2, Math.floor(Math.min(W,H)/200));
  VIEW_W = W / SCALE;
  VIEW_H = H / SCALE;
  ctx.imageSmoothingEnabled = false;
}
window.addEventListener('resize', resizeCanvas);
window.addEventListener('orientationchange', ()=> setTimeout(resizeCanvas, 120));
resizeCanvas();

/* ---------------- WORLD CONSTANTS ---------------- */
const TILE = 16;
const MAPW = 64, MAPH = 64;
const WORLD_W = MAPW * TILE;   // 1024
const WORLD_H = MAPH * TILE;   // 1024

const T_GRASS=0, T_TREE=1, T_WATER=2, T_PATH=3, T_FLOWER=4, T_ROCK=5, T_SAND=6, T_BRIDGE=7;
const SOLID_TILE = { 1:1, 2:1, 5:1 };

let map = [];

/* ---------------- TILE RENDERING ---------------- */
function drawTile(g, px, py, t, tx, ty){
  const h = hash2(tx, ty);

  switch(t){
    case T_GRASS: {
      g.fillStyle = '#4e9a3d';
      g.fillRect(px,py,TILE,TILE);
      g.fillStyle = '#458a36';
      if(h%3===0) g.fillRect(px + (h>>4)%12, py + (h>>8)%12, 2, 2);
      if(h%7===0) g.fillRect(px + (h>>3)%12, py + (h>>6)%12, 2, 2);
      g.fillStyle = '#5aab48';
      if(h%4===0) g.fillRect(px + (h>>5)%12, py + (h>>9)%12, 2, 2);
      break;
    }
    case T_FLOWER: {
      g.fillStyle = '#4e9a3d'; g.fillRect(px,py,TILE,TILE);
      g.fillStyle = '#458a36';
      g.fillRect(px + (h>>4)%12, py + (h>>8)%12, 2, 2);
      const cols = ['#f4d35e','#ee6c8a','#ffffff','#c77dff'];
      const fx = px + 3 + (h>>6)%8;
      const fy = py + 3 + (h>>10)%8;
      g.fillStyle = cols[h%4];
      g.fillRect(fx, fy, 4, 4);
      g.fillStyle = '#ffe89a';
      g.fillRect(fx+1, fy+1, 2, 2);
      break;
    }
    case T_PATH: {
      g.fillStyle = '#c9a86a'; g.fillRect(px,py,TILE,TILE);
      g.fillStyle = '#b6945a';
      if(h%2) g.fillRect(px + (h>>4)%13, py + (h>>8)%13, 2, 2);
      g.fillStyle = '#d9bc84';
      if(h%3===0) g.fillRect(px + (h>>3)%13, py + (h>>7)%13, 2, 2);
      break;
    }
    case T_SAND: {
      g.fillStyle = '#e2cf98'; g.fillRect(px,py,TILE,TILE);
      g.fillStyle = '#d4bd82';
      if(h%2===0) g.fillRect(px + (h>>4)%13, py + (h>>8)%13, 2, 2);
      break;
    }
    case T_WATER: {
      g.fillStyle = '#2b6cb0'; g.fillRect(px,py,TILE,TILE);
      g.fillStyle = '#3b82d6';
      g.fillRect(px+2, py+3, 6, 2);
      g.fillRect(px+9, py+10, 5, 2);
      g.fillStyle = '#5b9fe8';
      g.fillRect(px+3, py+3, 3, 1);
      break;
    }
    case T_BRIDGE: {
      g.fillStyle = '#8b5a2b'; g.fillRect(px,py,TILE,TILE);
      g.fillStyle = '#6d4420';
      g.fillRect(px,py,TILE,2);
      g.fillRect(px,py+14,TILE,2);
      g.fillRect(px,py+7,TILE,1);
      g.fillStyle = '#a06a35';
      g.fillRect(px+1,py+3,14,2);
      g.fillRect(px+1,py+10,14,2);
      break;
    }
    case T_TREE: {
      g.fillStyle = '#4e9a3d'; g.fillRect(px,py,TILE,TILE);
      g.fillStyle = 'rgba(0,0,0,0.18)';
      g.fillRect(px+3,py+13,11,3);
      g.fillStyle = '#5d4037';
      g.fillRect(px+7,py+10,3,6);
      g.fillStyle = '#2e7d32';
      g.fillRect(px+3,py+1,10,9);
      g.fillRect(px+1,py+3,14,5);
      g.fillStyle = '#43a047';
      g.fillRect(px+4,py+2,4,3);
      g.fillRect(px+2,py+4,3,2);
      g.fillStyle = '#1b5e20';
      g.fillRect(px+10,py+7,3,2);
      break;
    }
    case T_ROCK: {
      g.fillStyle = '#4e9a3d'; g.fillRect(px,py,TILE,TILE);
      g.fillStyle = 'rgba(0,0,0,0.2)';
      g.fillRect(px+2,py+12,12,3);
      g.fillStyle = '#7d7d8a';
      g.fillRect(px+2,py+4,12,9);
      g.fillRect(px+4,py+2,8,3);
      g.fillStyle = '#9e9eae';
      g.fillRect(px+3,py+5,5,4);
      g.fillStyle = '#5c5c68';
      g.fillRect(px+9,py+9,4,3);
      break;
    }
  }
}

/* ---------------- MAP GENERATION ---------------- */
function clearAreaTiles(cx, cy, r){
  for(let y=cy-r; y<=cy+r; y++){
    for(let x=cx-r; x<=cx+r; x++){
      if(x<2 || y<2 || x>=MAPW-2 || y>=MAPH-2) continue;
      if(map[y][x] === T_TREE || map[y][x] === T_ROCK) map[y][x] = T_GRASS;
    }
  }
}

function generateMap(){
  map = [];
  for(let y=0;y<MAPH;y++){
    const row = new Array(MAPW).fill(T_GRASS);
    map.push(row);
  }

  // Border of trees
  for(let y=0;y<MAPH;y++){
    for(let x=0;x<MAPW;x++){
      if(x<2 || y<2 || x>=MAPW-2 || y>=MAPH-2) map[y][x] = T_TREE;
    }
  }

  // River (vertical)
  for(let y=0;y<MAPH;y++){
    for(let x=45;x<=47;x++) map[y][x] = T_WATER;
    map[y][44] = T_SAND;
    map[y][48] = T_SAND;
  }

  // Bridge
  for(let y=30;y<=32;y++){
    for(let x=44;x<=48;x++) map[y][x] = T_BRIDGE;
  }

  // Paths
  for(let x=14;x<=32;x++) map[16][x] = T_PATH;          // castle road
  for(let y=12;y<=16;y++) map[y][32] = T_PATH;          // castle entrance
  for(let y=16;y<=30;y++) map[y][14] = T_PATH;          // village road
  for(let x=14;x<=44;x++) map[26][x] = T_PATH;          // east road
  for(let y=26;y<=31;y++) map[y][44] = T_PATH;          // to bridge
  for(let x=48;x<=60;x++) map[31][x] = T_PATH;          // east of bridge

  // Scatter trees & rocks
  for(let i=0;i<520;i++){
    const x = 3 + Math.floor(Math.random()*(MAPW-6));
    const y = 3 + Math.floor(Math.random()*(MAPH-6));
    if(map[y][x] !== T_GRASS) continue;
    let nearPath = false;
    for(let dy=-1;dy<=1 && !nearPath;dy++){
      for(let dx=-1;dx<=1;dx++){
        if(map[y+dy] && map[y+dy][x+dx] === T_PATH){ nearPath = true; break; }
      }
    }
    if(nearPath) continue;
    map[y][x] = (Math.random() < 0.78) ? T_TREE : T_ROCK;
  }

  // Flowers
  for(let i=0;i<260;i++){
    const x = 3 + Math.floor(Math.random()*(MAPW-6));
    const y = 3 + Math.floor(Math.random()*(MAPH-6));
    if(map[y][x] === T_GRASS && Math.random()<0.6) map[y][x] = T_FLOWER;
  }

  // Clear important areas
  clearAreaTiles(14, 24, 9);     // village
  clearAreaTiles(32, 14, 9);     // castle front
  clearAreaTiles(12, 48, 4);     // crystal 1
  clearAreaTiles(56, 43, 4);     // crystal 2
  clearAreaTiles(55, 14, 4);     // crystal 3 / cave
  clearAreaTiles(44, 31, 3);
  clearAreaTiles(52, 31, 3);
  clearAreaTiles(14, 44, 3);
  clearAreaTiles(56, 26, 3);
}

/* ---------------- MAP PRERENDER ---------------- */
const mapCanvas = document.createElement('canvas');
mapCanvas.width = WORLD_W;
mapCanvas.height = WORLD_H;
const mctx = mapCanvas.getContext('2d');

function renderMapCanvas(){
  mctx.imageSmoothingEnabled = false;
  for(let y=0;y<MAPH;y++){
    for(let x=0;x<MAPW;x++){
      drawTile(mctx, x*TILE, y*TILE, map[y][x], x, y);
    }
  }
}

/* ---------------- WORLD OBJECTS ---------------- */
const houses = [
  { x:160, y:320, w:48, h:48 },
  { x:272, y:352, w:48, h:48 },
  { x:176, y:480, w:48, h:48 }
];

const castle = { x:432, y:48, w:176, h:144 };
const cave   = { x:856, y:140, w:64, h:56 };

const solids = [];

function buildSolids(){
  solids.length = 0;
  houses.forEach(h => solids.push({x:h.x, y:h.y, w:h.w, h:h.h}));
  solids.push({x:castle.x, y:castle.y, w:castle.w, h:castle.h});
  solids.push({x:cave.x, y:cave.y, w:cave.w, h:cave.h});
}

/* ---------------- COLLISION ---------------- */
const HB_W = 11;
const HB_H = 8;

function collidesAt(x, y){
  const x1 = x - HB_W/2, y1 = y - HB_H;
  const x2 = x + HB_W/2, y2 = y;
  const tx1 = Math.floor(x1/TILE), tx2 = Math.floor((x2-0.01)/TILE);
  const ty1 = Math.floor(y1/TILE), ty2 = Math.floor((y2-0.01)/TILE);
  for(let ty=ty1; ty<=ty2; ty++){
    for(let tx=tx1; tx<=tx2; tx++){
      if(tx<0 || ty<0 || tx>=MAPW || ty>=MAPH) return true;
      if(SOLID_TILE[map[ty][tx]]) return true;
    }
  }
  for(let i=0;i<solids.length;i++){
    const o = solids[i];
    if(x2 > o.x && x1 < o.x+o.w && y2 > o.y && y1 < o.y+o.h) return true;
  }
  return false;
}

function tryMove(e, dx, dy){
  if(dx !== 0){
    if(!collidesAt(e.x+dx, e.y)) e.x += dx;
    else if(Math.abs(dx) > 2 && !collidesAt(e.x+dx/2, e.y)) e.x += dx/2;
  }
  if(dy !== 0){
    if(!collidesAt(e.x, e.y+dy)) e.y += dy;
    else if(Math.abs(dy) > 2 && !collidesAt(e.x, e.y+dy/2)) e.y += dy/2;
  }
}

/* ---------------- GAME STATE ---------------- */
const G = {
  state: 'title',       // title | playing | win | lose
  t: 0,
  msg: '',
  msgTimer: 0,
  shake: 0
};

let player = null;
let enemies = [];
let npcs = [];
let crystals = [];
let coins = [];
let hearts = [];
let floats = [];
let dialogue = null;
let bossSpawned = false;
let boss = null;
let questStarted = false;

const cam = { x:0, y:0 };

/* ---------------- SPRITE PATTERNS ---------------- */
const HEART_PAT = [
  "01100110",
  "11111111",
  "11111111",
  "11111111",
  "01111110",
  "00111100",
  "00011000"
];
const CRYSTAL_PAT = [
  "00011000",
  "00111100",
  "01111110",
  "11111111",
  "01111110",
  "00111100",
  "00011000",
  "00000000"
];
const COIN_PAT = [
  "00111100",
  "01111110",
  "11111111",
  "11111111",
  "11111111",
  "11111111",
  "01111110",
  "00111100"
];

function drawPattern(pat, x, y, px, color){
  ctx.fillStyle = color;
  const w = pat[0].length;
  for(let r=0;r<pat.length;r++){
    const row = pat[r];
    for(let c=0;c<w;c++){
      if(row[c] === '1'){
        ctx.fillRect(Math.round(x + c*px), Math.round(y + r*px), Math.ceil(px), Math.ceil(px));
      }
    }
  }
}

/* ---------------- CHARACTER DRAWING ---------------- */
function drawHero(g, px, py, dir, walking, frame, attacking, flash){
  // shadow
  g.fillStyle = 'rgba(0,0,0,0.25)';
  g.fillRect(px+3, py+14, 10, 2);

  const skin  = flash ? '#ffffff' : '#f2c29a';
  const skinD = flash ? '#dddddd' : '#d9a077';
  const tunic = flash ? '#ffffff' : '#3f8f4f';
  const tunicD= flash ? '#dddddd' : '#2e6f3c';
  const hair  = flash ? '#ffffff' : '#5a3a1e';
  const boot  = flash ? '#dddddd' : '#4a3020';

  // legs
  g.fillStyle = boot;
  if(walking){
    const f = Math.floor(frame) % 2;
    if(f === 0){
      g.fillRect(px+3, py+13, 3, 3);
      g.fillRect(px+10, py+13, 3, 3);
    } else {
      g.fillRect(px+4, py+13, 3, 3);
      g.fillRect(px+9, py+13, 3, 3);
    }
  } else {
    g.fillRect(px+4, py+13, 3, 3);
    g.fillRect(px+9, py+13, 3, 3);
  }

  // body
  g.fillStyle = tunic;
  g.fillRect(px+4, py+8, 8, 6);
  g.fillStyle = tunicD;
  g.fillRect(px+4, py+12, 8, 2);
  // belt
  g.fillStyle = flash ? '#ffffff' : '#6b4a2a';
  g.fillRect(px+4, py+11, 8, 1);

  // arms
  g.fillStyle = skin;
  g.fillRect(px+2, py+9, 2, 4);
  g.fillRect(px+12, py+9, 2, 4);

  // head
  g.fillStyle = skin;
  g.fillRect(px+4, py+2, 8, 6);
  g.fillStyle = skinD;
  g.fillRect(px+4, py+7, 8, 1);

  // hair
  g.fillStyle = hair;
  g.fillRect(px+3, py+1, 10, 3);
  g.fillRect(px+3, py+1, 2, 5);
  g.fillRect(px+11, py+1, 2, 5);

  // eyes
  if(dir !== 'up'){
    g.fillStyle = '#1a1a2e';
    if(dir === 'down'){ g.fillRect(px+6,py+5,2,2); g.fillRect(px+9,py+5,2,2); }
    else if(dir === 'left'){ g.fillRect(px+5,py+5,2,2); }
    else { g.fillRect(px+10,py+5,2,2); }
  }

  // sword swing
  if(attacking){
    g.fillStyle = '#e8f4ff';
    if(dir === 'down'){
      g.fillRect(px+1, py+12, 14, 3);
      g.fillStyle = '#9fd0ff'; g.fillRect(px+1, py+14, 14, 1);
    } else if(dir === 'up'){
      g.fillRect(px+1, py+1, 14, 3);
      g.fillStyle = '#9fd0ff'; g.fillRect(px+1, py+1, 14, 1);
    } else if(dir === 'left'){
      g.fillRect(px-3, py+5, 3, 12);
      g.fillStyle = '#9fd0ff'; g.fillRect(px-3, py+5, 1, 12);
    } else {
      g.fillRect(px+16, py+5, 3, 12);
      g.fillStyle = '#9fd0ff'; g.fillRect(px+18, py+5, 1, 12);
    }
  }
}

function drawSlime(g, e){
  const big = e.boss;
  const baseR = big ? 24 : 9;
  const squish = 1 + Math.sin(G.t*7 + (e.seed||0)) * 0.09;
  const w = baseR*2*squish;
  const h = baseR*1.7/squish;

  // shadow
  g.fillStyle = 'rgba(0,0,0,0.25)';
  g.fillRect(e.x - w/2 + 2, e.y - 2, w-4, 3);

  const flashing = e.hitFlash > 0;
  const bodyCol = flashing ? '#ffffff' : (big ? '#8e44ad' : '#3fae5a');
  const darkCol = flashing ? '#dddddd' : (big ? '#6c3483' : '#2d8442');

  // body
  g.fillStyle = bodyCol;
  g.fillRect(e.x - w/2 + 3, e.y - h, w - 6, h);
  g.fillRect(e.x - w/2, e.y - h + 4, w, h - 4);
  g.fillStyle = darkCol;
  g.fillRect(e.x - w/2, e.y - 3, w, 3);

  // highlight
  g.fillStyle = 'rgba(255,255,255,0.35)';
  g.fillRect(e.x - w/2 + 4, e.y - h + 3, Math.max(3,w*0.2), Math.max(2,h*0.2));

  // eyes
  g.fillStyle = '#111';
  const ey = e.y - h + h*0.42;
  const ex = Math.max(2, w*0.16);
  g.fillRect(e.x - ex - 2, ey, 3, 4);
  g.fillRect(e.x + ex - 1, ey, 3, 4);
  g.fillStyle = '#fff';
  g.fillRect(e.x - ex - 1, ey, 1, 1);
  g.fillRect(e.x + ex, ey, 1, 1);

  // crown for boss
  if(big){
    g.fillStyle = '#ffd94a';
    g.fillRect(e.x - 10, e.y - h - 5, 20, 5);
    g.fillRect(e.x - 10, e.y - h - 10, 4, 6);
    g.fillRect(e.x - 2,  e.y - h - 10, 4, 6);
    g.fillRect(e.x + 6,  e.y - h - 10, 4, 6);
  }

  // boss health bar
  if(big){
    const bw = 70, bh = 7;
    const bx = e.x - bw/2, by = e.y - h - 22;
    g.fillStyle = 'rgba(0,0,0,0.65)';
    g.fillRect(bx-2, by-2, bw+4, bh+4);
    g.fillStyle = '#3a1010';
    g.fillRect(bx, by, bw, bh);
    g.fillStyle = '#e84545';
    g.fillRect(bx, by, bw * (e.hp/e.maxHp), bh);
    g.fillStyle = 'rgba(255,255,255,0.4)';
    g.fillRect(bx, by, bw * (e.hp/e.maxHp), 2);
  }
}

function drawNPC(g, n){
  const px = Math.round(n.x) - 8;
  const py = Math.round(n.y) - 16;

  g.fillStyle = 'rgba(0,0,0,0.25)';
  g.fillRect(px+3, py+14, 10, 2);

  // legs
  g.fillStyle = '#4a3020';
  g.fillRect(px+4, py+13, 3, 3);
  g.fillRect(px+9, py+13, 3, 3);

  // robe
  g.fillStyle = n.color2;
  g.fillRect(px+3, py+8, 10, 7);
  g.fillStyle = n.color;
  g.fillRect(px+4, py+8, 8, 6);

  // head
  g.fillStyle = '#f2c29a';
  g.fillRect(px+4, py+3, 8, 6);

  // hair / hat
  g.fillStyle = n.hair;
  g.fillRect(px+3, py+1, 10, 3);
  if(n.hat){
    g.fillStyle = n.hat;
    g.fillRect(px+1, py+1, 14, 3);
    g.fillRect(px+5, py-3, 6, 5);
  }

  // eyes
  g.fillStyle = '#1a1a2e';
  g.fillRect(px+6, py+6, 2, 2);
  g.fillRect(px+9, py+6, 2, 2);

  // quest marker
  if(n.marker){
    const bob = Math.sin(G.t*4)*2;
    g.fillStyle = '#ffd94a';
    g.fillRect(px+6, py-14+bob, 4, 8);
    g.fillRect(px+6, py-4+bob, 4, 3);
  }
}

/* ---------------- WORLD OBJECT DRAWING ---------------- */
function drawHouse(g, h){
  const x = h.x, y = h.y, w = h.w, hh = h.h;

  // shadow
  g.fillStyle = 'rgba(0,0,0,0.22)';
  g.fillRect(x+4, y+hh-4, w, 8);

  // walls
  g.fillStyle = '#e8d8b0';
  g.fillRect(x, y+18, w, hh-18);
  g.fillStyle = '#d6c49a';
  g.fillRect(x, y+hh-6, w, 6);

  // wood beams
  g.fillStyle = '#8b6b4a';
  g.fillRect(x, y+18, 2, hh-18);
  g.fillRect(x+w-2, y+18, 2, hh-18);
  g.fillRect(x, y+hh-3, w, 3);
  g.fillRect(x+2, y+18, w-4, 2);

  // windows
  g.fillStyle = '#7ec8e3';
  g.fillRect(x+7, y+24, 9, 9);
  g.fillRect(x+w-16, y+24, 9, 9);
  g.fillStyle = '#8b6b4a';
  g.fillRect(x+11, y+24, 1, 9);
  g.fillRect(x+7, y+28, 9, 1);
  g.fillRect(x+w-12, y+24, 1, 9);
  g.fillRect(x+w-16, y+28, 9, 1);

  // roof
  g.fillStyle = '#c0392b';
  g.fillRect(x-4, y+10, w+8, 11);
  g.fillRect(x+2, y+4, w-4, 7);
  g.fillRect(x+8, y-1, w-16, 6);
  g.fillStyle = '#e05a4a';
  g.fillRect(x-4, y+10, w+8, 2);
  g.fillRect(x+2, y+4, w-4, 2);
  g.fillStyle = '#8f2a1f';
  g.fillRect(x-4, y+20, w+8, 2);

  // door
  g.fillStyle = '#5a3a1e';
  g.fillRect(x+w/2-7, y+hh-17, 14, 17);
  g.fillStyle = '#3a2410';
  g.fillRect(x+w/2-7, y+hh-17, 14, 2);
  g.fillStyle = '#c9a227';
  g.fillRect(x+w/2+3, y+hh-9, 2, 2);
}

function drawCastle(g){
  const x = castle.x, y = castle.y, w = castle.w, hh = castle.h;

  g.fillStyle = 'rgba(0,0,0,0.25)';
  g.fillRect(x+8, y+hh-4, w, 10);

  // side towers
  g.fillStyle = '#6e6e80';
  g.fillRect(x-6, y+8, 30, hh-8);
  g.fillRect(x+w-24, y+8, 30, hh-8);

  // main wall
  g.fillStyle = '#8a8a9c';
  g.fillRect(x, y+34, w, hh-34);
  g.fillStyle = '#7a7a8c';
  g.fillRect(x, y+34, w, 5);

  // bricks
  g.fillStyle = '#767686';
  for(let yy=y+46; yy<y+hh-4; yy+=12){
    g.fillRect(x, yy, w, 2);
    for(let xx=x+((yy/12)%2?0:14); xx<x+w; xx+=28){
      g.fillRect(xx, yy, 2, 12);
    }
  }

  // battlements on main wall
  g.fillStyle = '#8a8a9c';
  for(let xx=x; xx<x+w; xx+=24){
    g.fillRect(xx, y+20, 14, 16);
  }

  // tower battlements
  g.fillStyle = '#6e6e80';
  for(let xx=x-6; xx<x+24; xx+=12) g.fillRect(xx, y, 8, 12);
  for(let xx=x+w-24; xx<x+w+6; xx+=12) g.fillRect(xx, y, 8, 12);

  // banners
  g.fillStyle = '#b03030';
  g.fillRect(x+24, y+54, 14, 32);
  g.fillRect(x+w-38, y+54, 14, 32);
  g.fillStyle = '#c9a227';
  g.fillRect(x+29, y+62, 4, 16);
  g.fillRect(x+w-33, y+62, 4, 16);

  // door
  const dx = x + w/2 - 18;
  const dy = y + hh - 46;
  g.fillStyle = '#3a2a18';
  g.fillRect(dx, dy, 36, 46);
  g.fillStyle = '#241608';
  g.fillRect(dx+4, dy+7, 28, 39);
  g.fillStyle = '#c9a227';
  g.fillRect(dx, dy, 36, 3);
  g.fillStyle = '#5a3a1a';
  g.fillRect(dx+15, dy+7, 6, 39);

  // door glow when unlocked
  if(player && player.crystals >= 3){
    const gl = 0.25 + Math.sin(G.t*4)*0.15;
    g.fillStyle = 'rgba(120,220,255,' + gl + ')';
    g.fillRect(dx+2, dy+4, 32, 42);
  }
}

function drawCave(g){
  const x = cave.x, y = cave.y, w = cave.w, hh = cave.h;

  g.fillStyle = 'rgba(0,0,0,0.25)';
  g.fillRect(x+4, y+hh-4, w, 8);

  g.fillStyle = '#5a5a68';
  g.fillRect(x, y+10, w, hh-10);
  g.fillRect(x+10, y, w-20, 14);
  g.fillStyle = '#6e6e80';
  g.fillRect(x+4, y+14, w-8, 5);

  // opening
  const ox = x + w/2 - 17;
  const oy = y + 22;
  g.fillStyle = '#0a0a12';
  g.fillRect(ox, oy, 34, hh-22);
  g.fillRect(ox+4, oy-10, 26, 12);

  // eerie glow
  g.fillStyle = 'rgba(130,90,230,0.28)';
  g.fillRect(ox+8, oy+10, 18, hh-30);
}

/* ---------------- INPUT ---------------- */
const keys = {};
const joy = { active:false, x:0, y:0, id:null };
let runHeld = false;

const joyEl  = document.getElementById('joy');
const knobEl = document.getElementById('knob');

function updateJoy(e){
  const r = joyEl.getBoundingClientRect();
  const cx = r.left + r.width/2;
  const cy = r.top + r.height/2;
  let dx = e.clientX - cx;
  let dy = e.clientY - cy;
  const max = r.width/2;
  const d = Math.hypot(dx,dy);
  if(d > max){ dx = dx/d*max; dy = dy/d*max; }
  knobEl.style.transform = 'translate(' + dx.toFixed(1) + 'px,' + dy.toFixed(1) + 'px)';

  const nx = dx/max, ny = dy/max;
  const mag = Math.hypot(nx,ny);
  if(mag < 0.22){ joy.x = 0; joy.y = 0; }
  else {
    const m = (mag - 0.22) / 0.78;
    joy.x = (nx/mag) * m;
    joy.y = (ny/mag) * m;
  }
}

joyEl.addEventListener('pointerdown', function(e){
  e.preventDefault(); e.stopPropagation();
  initAudio();
  if(joy.active) return;
  joy.active = true;
  joy.id = e.pointerId;
  try{ joyEl.setPointerCapture(e.pointerId); }catch(err){}
  updateJoy(e);
});
joyEl.addEventListener('pointermove', function(e){
  if(!joy.active || e.pointerId !== joy.id) return;
  e.preventDefault();
  updateJoy(e);
});
function endJoy(e){
  if(e.pointerId !== joy.id) return;
  joy.active = false;
  joy.id = null;
  joy.x = 0; joy.y = 0;
  knobEl.style.transform = 'translate(0,0)';
}
joyEl.addEventListener('pointerup', endJoy);
joyEl.addEventListener('pointercancel', endJoy);
joyEl.addEventListener('pointerleave', function(e){ if(joy.active && e.pointerId===joy.id) endJoy(e); });

/* ---- Buttons ---- */
function bindButton(el, onDown, onUp){
  el.addEventListener('pointerdown', function(e){
    e.preventDefault(); e.stopPropagation();
    initAudio();
    el.classList.add('active');
    try{ el.setPointerCapture(e.pointerId); }catch(err){}
    if(onDown) onDown();
  });
  function up(e){
    e.preventDefault();
    el.classList.remove('active');
    if(onUp) onUp();
  }
  el.addEventListener('pointerup', up);
  el.addEventListener('pointercancel', up);
  el.addEventListener('pointerleave', function(e){
    el.classList.remove('active');
    if(onUp) onUp();
  });
}

bindButton(document.getElementById('bA'), function(){ doAttack(); }, null);
bindButton(document.getElementById('bB'), function(){ doInteract(); }, null);
bindButton(document.getElementById('bRun'), function(){ runHeld = true; }, function(){ runHeld = false; });

/* ---- Keyboard ---- */
window.addEventListener('keydown', function(e){
  const k = e.key.toLowerCase();
  keys[k] = true;
  if(['arrowup','arrowdown','arrowleft','arrowright',' '].indexOf(k) >= 0) e.preventDefault();
  initAudio();
  if(!e.repeat){
    if(k === ' ' || k === 'j') doAttack();
    if(k === 'e' || k === 'f') doInteract();
  }
});
window.addEventListener('keyup', function(e){
  keys[e.key.toLowerCase()] = false;
});

/* ---- Canvas tap to advance dialogue ---- */
cvs.addEventListener('pointerdown', function(e){
  initAudio();
  if(dialogue){ advanceDialogue(); }
});

/* ---- Prevent scrolling / zoom ---- */
document.addEventListener('touchmove', function(e){ e.preventDefault(); }, {passive:false});
document.addEventListener('gesturestart', function(e){ e.preventDefault(); });
document.addEventListener('contextmenu', function(e){ e.preventDefault(); });

/* ---- Mute ---- */
const muteEl = document.getElementById('mute');
muteEl.addEventListener('pointerdown', function(e){
  e.preventDefault(); e.stopPropagation();
  muted = !muted;
  muteEl.textContent = muted ? '🔇' : '🔊';
  if(!muted){ initAudio(); beep(880,0.08,'square',0.05); }
});

/* ---------------- ENTITY FACTORIES ---------------- */
function resetGame(){
  player = {
    x: 240, y: 470,
    dir: 'down',
    hp: 5, maxHp: 5,
    coins: 0, crystals: 0,
    walking: false, walkTimer: 0,
    attackTimer: 0, attackCd: 0,
    invuln: 0,
    hitSet: new Set(),
    kbx: 0, kby: 0
  };

  dialogue = null;
  floats = [];
  bossSpawned = false;
  boss = null;
  questStarted = false;
  G.msg = '';
  G.msgTimer = 0;
  G.shake = 0;

  // Enemies
  enemies = [];
  const slimeSpots = [
    [420,520],[600,620],[300,760],[820,420],[860,640],
    [160,640],[560,290],[700,860],[250,880],[960,320]
  ];
  slimeSpots.forEach(function(p, i){
    enemies.push({
      x:p[0], y:p[1], r:9, hp:1, maxHp:1,
      alive:true, speed:42, seed:i*1.7,
      hitFlash:0, boss:false
    });
  });

  // NPCs
  npcs = [
    {
      x:240, y:390, name:'Elder',
      color:'#4a6fa5', color2:'#35527a', hair:'#d8d8d8',
      marker:true,
      onTalk: function(){
        questStarted = true;
        if(player.crystals >= 3){
          return [
            "You have gathered all three crystals!",
            "The castle door will open for you now.",
            "The Slime King awaits inside... be brave, hero!"
          ];
        }
        return [
          "Ah, a brave traveler! Our land is in peril.",
          "The Crystal of Light was shattered into 3 pieces.",
          "Find them all, and the castle gate shall open.",
          "One lies in the dark forest to the south-west.",
          "One is across the river, far to the east.",
          "The last is near the cave in the north-east.",
          "You have " + player.crystals + " of 3 crystals. Go!"
        ];
      }
    },
    {
      x:340, y:300, name:'Merchant',
      color:'#a55a2a', color2:'#7a3f1a', hair:'#3a2a1a',
      hat:'#c9a227',
      marker:false,
      onTalk: function(){
        if(player.hp < player.maxHp && player.coins >= 10){
          player.coins -= 10;
          player.hp++;
          sfxCoin();
          return [
            "Ouch! You look hurt, friend.",
            "Here, a healing potion. That'll be 10 coins.",
            "Your heart was restored!"
          ];
        }
        if(player.coins < 10){
          return [
            "Welcome to my shop! (Closed, actually.)",
            "Slimes drop coins when you defeat them.",
            "Bring me 10 coins and I'll heal your wounds."
          ];
        }
        return [
          "You're looking healthy already!",
          "10 coins buys a healing potion anytime.",
          "Tip: Hold RUN to move faster in danger."
        ];
      }
    },
    {
      x:505, y:250, name:'Guard',
      color:'#5a5a6a', color2:'#3f3f4d', hair:'#2a1a0a',
      hat:'#8a8a9a',
      marker:false,
      onTalk: function(){
        if(player.crystals >= 3){
          return [
            "You have the crystals! The gate glows!",
            "Go on then. Show that slime who's boss.",
            "Press A to swing your sword. Good luck!"
          ];
        }
        return [
          "Halt! The castle is sealed by ancient magic.",
          "Only the 3 lost crystals can break the seal.",
          "The Slime King rules within. Terrible thing.",
          "Come back when you have all three."
        ];
      }
    }
  ];

  // Crystals
  crystals = [
    { x:200, y:780, taken:false },
    { x:900, y:700, taken:false },
    { x:880, y:230, taken:false }
  ];

  // Heart pickups
  hearts = [
    { x:130, y:420, taken:false },
    { x:640, y:740, taken:false },
    { x:930, y:520, taken:false }
  ];

  // Coins
  coins = [];
  const coinSpots = [
    [380,440],[470,540],[210,560],[680,420],[760,700],
    [520,700],[330,660],[880,760],[150,820],[700,300],
    [960,640],[430,860]
  ];
  coinSpots.forEach(function(p){ coins.push({x:p[0], y:p[1], taken:false}); });

  updateCamera();
}

/* ---------------- ATTACK ---------------- */
function getAttackHitbox(){
  const p = player;
  if(p.dir === 'down')  return {x:p.x-13, y:p.y-6,  w:26, h:26};
  if(p.dir === 'up')    return {x:p.x-13, y:p.y-28, w:26, h:26};
  if(p.dir === 'left')  return {x:p.x-28, y:p.y-16, w:26, h:26};
  return                       {x:p.x+2,  y:p.y-16, w:26, h:26};
}

function circleHitsRect(cx, cy, r, rc){
  const nx = clamp(cx, rc.x, rc.x+rc.w);
  const ny = clamp(cy, rc.y, rc.y+rc.h);
  const dx = cx-nx, dy = cy-ny;
  return dx*dx + dy*dy <= r*r;
}

function doAttack(){
  if(G.state !== 'playing') return;
  if(dialogue) return;
  if(player.attackCd > 0) return;
  player.attackTimer = 0.28;
  player.attackCd = 0.34;
  player.hitSet.clear();
  sfxSwing();
}

function damageEnemy(e, dmg){
  e.hp -= dmg;
  e.hitFlash = 0.12;
  sfxHit();
  if(e.hp <= 0){
    e.alive = false;
    if(e.boss){
      G.state = 'win';
      sfxWin();
      showMenu('VICTORY!', 'THE SLIME KING IS DEFEATED',
        'The land is safe once more.\nCoins collected: ' + player.coins +
        '\n\nYou are a true hero of Pixel Quest!',
        'PLAY AGAIN', startGame);
    } else {
      player.coins += 2;
      addFloat(e.x, e.y-16, '+2', '#ffd94a');
      beep(300,0.08,'square',0.05);
    }
  } else {
    addFloat(e.x, e.y-16, '-1', '#ffffff');
  }
}

function hurtPlayer(dmg, fx, fy){
  if(player.invuln > 0) return;
  player.hp -= dmg;
  player.invuln = 1.4;
  G.shake = 0.25;
  sfxHurt();

  const dx = player.x - fx;
  const dy = player.y - fy;
  const d = Math.hypot(dx,dy) || 1;
  player.kbx = dx/d * 170;
  player.kby = dy/d * 170;

  if(player.hp <= 0){
    player.hp = 0;
    G.state = 'lose';
    sfxLose();
    showMenu('GAME OVER', 'YOU HAVE FALLEN',
      'The crystals remain lost...\nCoins collected: ' + player.coins +
      '\n\nTry again, hero!',
      'RESTART', startGame);
  }
}

/* ---------------- DIALOGUE ---------------- */
function talkTo(npc){
  const lines = npc.onTalk();
  dialogue = { lines: lines, i: 0 };
  sfxTalk();
}

function advanceDialogue(){
  if(!dialogue) return;
  dialogue.i++;
  sfxTalk();
  if(dialogue.i >= dialogue.lines.length) dialogue = null;
}

function doInteract(){
  if(G.state !== 'playing') return;
  if(dialogue){ advanceDialogue(); return; }

  let best = null, bd = 46;
  for(let i=0;i<npcs.length;i++){
    const n = npcs[i];
    const d = Math.hypot(n.x - player.x, n.y - player.y);
    if(d < bd){ bd = d; best = n; }
  }
  if(best) talkTo(best);
}

/* ---------------- FLOATING TEXT ---------------- */
function addFloat(x, y, text, color){
  floats.push({ x:x, y:y, text:text, color:color, t:0, life:0.9 });
}

/* ---------------- MESSAGE ---------------- */
function showMessage(txt){
  G.msg = txt;
  G.msgTimer = 2.6;
}

/* ---------------- CAMERA ---------------- */
function updateCamera(){
  let cx, cy;
  if(WORLD_W <= VIEW_W) cx = (WORLD_W - VIEW_W)/2;
  else cx = clamp(player.x - VIEW_W/2, 0, WORLD_W - VIEW_W);
  if(WORLD_H <= VIEW_H) cy = (WORLD_H - VIEW_H)/2;
  else cy = clamp(player.y - VIEW_H/2, 0, WORLD_H - VIEW_H);
  cam.x = Math.round(cx);
  cam.y = Math.round(cy);
}

/* ---------------- UPDATE ---------------- */
function update(dt){
  G.t += dt;

  if(G.msgTimer > 0) G.msgTimer -= dt;
  if(G.shake > 0) G.shake = Math.max(0, G.shake - dt);

  // floating texts always animate
  for(let i=floats.length-1;i>=0;i--){
    const f = floats[i];
    f.t += dt;
    f.y -= 22*dt;
    if(f.t >= f.life) floats.splice(i,1);
  }

  if(G.state !== 'playing') return;
  if(dialogue) return;

  updatePlayer(dt);
  updateEnemies(dt);
  updatePickups(dt);
  updateCamera();
  checkCastleDoor();
}

function updatePlayer(dt){
  const p = player;

  p.attackCd = Math.max(0, p.attackCd - dt);
  p.invuln = Math.max(0, p.invuln - dt);

  // ---- attack active window ----
  if(p.attackTimer > 0){
    p.attackTimer -= dt;
    if(p.attackTimer > 0.04 && p.attackTimer < 0.22){
      const hb = getAttackHitbox();
      for(let i=0;i<enemies.length;i++){
        const e = enemies[i];
        if(!e.alive || p.hitSet.has(e)) continue;
        if(circleHitsRect(e.x, e.y, e.r + 2, hb)){
          p.hitSet.add(e);
          damageEnemy(e, 1);
        }
      }
    }
  }

  // ---- movement input ----
  let ax = 0, ay = 0;
  if(keys['arrowleft'] || keys['a']) ax -= 1;
  if(keys['arrowright'] || keys['d']) ax += 1;
  if(keys['arrowup'] || keys['w']) ay -= 1;
  if(keys['arrowdown'] || keys['s']) ay += 1;

  if(joy.active){
    ax += joy.x;
    ay += joy.y;
  }

  let mag = Math.hypot(ax, ay);
  if(mag > 1){ ax /= mag; ay /= mag; mag = 1; }

  const running = keys['shift'] || runHeld;
  const speed = running ? 148 : 88;

  if(mag > 0.15){
    if(Math.abs(ax) > Math.abs(ay)){
      p.dir = ax > 0 ? 'right' : 'left';
    } else {
      p.dir = ay > 0 ? 'down' : 'up';
    }
    p.walking = true;
    p.walkTimer += dt * (running ? 11 : 7);
    tryMove(p, ax * speed * dt, ay * speed * dt);
  } else {
    p.walking = false;
    p.walkTimer = 0;
  }

  // ---- knockback ----
  if(Math.abs(p.kbx) > 2 || Math.abs(p.kby) > 2){
    tryMove(p, p.kbx*dt, p.kby*dt);
    const decay = Math.pow(0.0015, dt);
    p.kbx *= decay;
    p.kby *= decay;
  } else {
    p.kbx = 0; p.kby = 0;
  }

  p.x = clamp(p.x, 8, WORLD_W-8);
  p.y = clamp(p.y, 12, WORLD_H-4);
}

function updateEnemies(dt){
  for(let i=0;i<enemies.length;i++){
    const e = enemies[i];
    if(!e.alive) continue;

    if(e.hitFlash > 0) e.hitFlash -= dt;

    const dx = player.x - e.x;
    const dy = player.y - e.y;
    const d = Math.hypot(dx, dy) || 1;

    const aggro = e.boss ? 400 : 140;

    if(d < aggro){
      let spd = e.speed;
      if(e.boss){
        spd = 46 + Math.sin(G.t*3) * 26;
        if(spd < 8) spd = 8;
      }
      const nx = e.x + (dx/d) * spd * dt;
      const ny = e.y + (dy/d) * spd * dt;
      if(!collidesAt(nx, e.y)) e.x = nx;
      if(!collidesAt(e.x, ny)) e.y = ny;
    }

    // contact damage
    if(d < e.r + 7 && player.invuln <= 0){
      hurtPlayer(1, e.x, e.y);
    }
  }
}

function updatePickups(dt){
  // crystals
  for(let i=0;i<crystals.length;i++){
    const c = crystals[i];
    if(c.taken) continue;
    if(Math.hypot(c.x-player.x, c.y-player.y) < 16){
      c.taken = true;
      player.crystals++;
      sfxCrystal();
      addFloat(c.x, c.y-20, '+CRYSTAL', '#8fd3ff');
      showMessage('CRYSTAL FOUND!  (' + player.crystals + '/3)');
      if(player.crystals >= 3) showMessage('ALL CRYSTALS FOUND! THE CASTLE DOOR GLOWS...');
    }
  }

  // coins
  for(let i=0;i<coins.length;i++){
    const c = coins[i];
    if(c.taken) continue;
    if(Math.hypot(c.x-player.x, c.y-player.y) < 14){
      c.taken = true;
      player.coins++;
      sfxCoin();
      addFloat(c.x, c.y-14, '+1', '#ffd94a');
    }
  }

  // hearts
  for(let i=0;i<hearts.length;i++){
    const h = hearts[i];
    if(h.taken) continue;
    if(Math.hypot(h.x-player.x, h.y-player.y) < 14){
      h.taken = true;
      if(player.hp < player.maxHp){
        player.hp++;
        addFloat(h.x, h.y-14, '+HEART', '#ff6b6b');
        beep(880,0.1,'sine',0.06);
        setTimeout(function(){ beep(1320,0.14,'sine',0.06); }, 90);
      } else {
        player.coins += 5;
        addFloat(h.x, h.y-14, '+5', '#ffd94a');
        sfxCoin();
      }
    }
  }
}

function checkCastleDoor(){
  if(bossSpawned) return;
  if(player.crystals < 3) return;

  const doorX = castle.x + castle.w/2;
  const doorY = castle.y + castle.h + 26;
  if(Math.hypot(doorX - player.x, doorY - player.y) < 58){
    bossSpawned = true;
    boss = {
      x: doorX,
      y: castle.y + castle.h + 70,
      r: 20, hp: 12, maxHp: 12,
      alive: true, speed: 50, seed: 3.3,
      hitFlash: 0, boss: true
    };
    enemies.push(boss);
    G.shake = 0.6;
    showMessage('THE SLIME KING AWAKENS!');
    beep(90,0.5,'sawtooth',0.09);
    setTimeout(function(){ beep(70,0.6,'sawtooth',0.08); }, 260);
  }
}

/* ---------------- RENDER ---------------- */
function render(){
  ctx.setTransform(1,0,0,1,0,0);
  ctx.imageSmoothingEnabled = false;

  // background
  ctx.fillStyle = '#0b1a0b';
  ctx.fillRect(0,0,W,H);

  let shakeX = 0, shakeY = 0;
  if(G.shake > 0){
    shakeX = (Math.random()-0.5) * G.shake * 18;
    shakeY = (Math.random()-0.5) * G.shake * 18;
  }

  ctx.save();
  ctx.scale(SCALE, SCALE);
  ctx.translate(-cam.x + shakeX/SCALE, -cam.y + shakeY/SCALE);

  // ---- tilemap ----
  const sx = clamp(Math.floor(cam.x)-2, 0, WORLD_W);
  const sy = clamp(Math.floor(cam.y)-2, 0, WORLD_H);
  const sw = Math.min(WORLD_W - sx, Math.ceil(VIEW_W)+4);
  const sh = Math.min(WORLD_H - sy, Math.ceil(VIEW_H)+4);
  if(sw > 0 && sh > 0){
    ctx.drawImage(mapCanvas, sx, sy, sw, sh, sx, sy, sw, sh);
  }

  // ---- build draw list (y-sorted) ----
  const list = [];

  // houses
  for(let i=0;i<houses.length;i++){
    const h = houses[i];
    list.push({ y: h.y + h.h, fn: (function(hh){ return function(){ drawHouse(ctx, hh); }; })(h) });
  }
  // cave
  list.push({ y: cave.y + cave.h, fn: function(){ drawCave(ctx); } });
  // castle
  list.push({ y: castle.y + castle.h, fn: function(){ drawCastle(ctx); } });

  // pickups
  for(let i=0;i<coins.length;i++){
    const c = coins[i];
    if(c.taken) continue;
    list.push({ y: c.y, fn: (function(cc){ return function(){
      const bob = Math.sin(G.t*4 + cc.x)*1.5;
      ctx.fillStyle = 'rgba(0,0,0,0.2)';
      ctx.fillRect(cc.x-4, cc.y-2, 8, 2);
      ctx.fillStyle = '#f0b400';
      ctx.fillRect(cc.x-4, cc.y-9+bob, 8, 8);
      ctx.fillStyle = '#ffd94a';
      ctx.fillRect(cc.x-3, cc.y-8+bob, 6, 6);
      ctx.fillStyle = '#fff2a0';
      ctx.fillRect(cc.x-2, cc.y-7+bob, 2, 2);
    }; })(c) });
  }

  for(let i=0;i<hearts.length;i++){
    const hp = hearts[i];
    if(hp.taken) continue;
    list.push({ y: hp.y, fn: (function(hh){ return function(){
      const bob = Math.sin(G.t*3 + hh.x)*2;
      drawPattern(HEART_PAT, hh.x-8, hh.y-18+bob, 2, '#e84545');
      drawPattern(HEART_PAT, hh.x-6, hh.y-16+bob, 1, '#ff9a9a');
    }; })(hp) });
  }

  for(let i=0;i<crystals.length;i++){
    const c = crystals[i];
    if(c.taken) continue;
    list.push({ y: c.y, fn: (function(cc){ return function(){
      const bob = Math.sin(G.t*3 + cc.x*0.1)*3;
      const gl = 0.25 + Math.sin(G.t*5)*0.15;
      ctx.fillStyle = 'rgba(140,220,255,' + gl + ')';
      ctx.fillRect(cc.x-14, cc.y-24+bob, 28, 28);
      drawPattern(CRYSTAL_PAT, cc.x-8, cc.y-24+bob, 2, '#5fb8ff');
      drawPattern(CRYSTAL_PAT, cc.x-4, cc.y-20+bob, 1, '#d6f2ff');
      ctx.fillStyle = 'rgba(0,0,0,0.2)';
      ctx.fillRect(cc.x-6, cc.y-2, 12, 3);
    }; })(c) });
  }

  // NPCs
  for(let i=0;i<npcs.length;i++){
    const n = npcs[i];
    list.push({ y: n.y, fn: (function(nn){ return function(){ drawNPC(ctx, nn); }; })(n) });
  }

  // enemies
  for(let i=0;i<enemies.length;i++){
    const e = enemies[i];
    if(!e.alive) continue;
    list.push({ y: e.y, fn: (function(ee){ return function(){ drawSlime(ctx, ee); }; })(e) });
  }

  // player
  if(player){
    list.push({ y: player.y, fn: function(){
      const blink = player.invuln > 0 && Math.floor(G.t*16) % 2 === 0;
      if(blink) return;
      drawHero(
        ctx,
        Math.round(player.x)-8,
        Math.round(player.y)-16,
        player.dir,
        player.walking,
        Math.floor(player.walkTimer),
        player.attackTimer > 0,
        false
      );
    }});
  }

  list.sort(function(a,b){ return a.y - b.y; });
  for(let i=0;i<list.length;i++) list[i].fn();

  // ---- floating text ----
  ctx.font = 'bold 8px "Courier New", monospace';
  ctx.textAlign = 'center';
  for(let i=0;i<floats.length;i++){
    const f = floats[i];
    ctx.globalAlpha = clamp(1 - f.t/f.life, 0, 1);
    ctx.fillStyle = '#000';
    ctx.fillText(f.text, f.x+1, f.y+1);
    ctx.fillStyle = f.color;
    ctx.fillText(f.text, f.x, f.y);
  }
  ctx.globalAlpha = 1;
  ctx.textAlign = 'left';

  ctx.restore();

  // ---- HUD ----
  drawHUD();

  // ---- dialogue ----
  if(dialogue) drawDialogue();

  // ---- message toast ----
  if(G.msgTimer > 0) drawMessage();
}

/* ---------------- HUD ---------------- */
function drawHUD(){
  if(G.state !== 'playing') return;

  const barH = 40;

  ctx.fillStyle = 'rgba(0,0,0,0.55)';
  ctx.fillRect(0,0,W,barH);
  ctx.fillStyle = 'rgba(255,255,255,0.18)';
  ctx.fillRect(0,barH-2,W,2);

  // hearts
  const px = 2, gap = 3;
  const heartW = 8*px;
  let x = 10;
  const y = 12;
  for(let i=0;i<player.maxHp;i++){
    drawPattern(HEART_PAT, x, y, px, i < player.hp ? '#e84545' : '#3a2a2a');
    if(i < player.hp){
      drawPattern(HEART_PAT, x+px, y+px, 1, 'rgba(255,180,180,0.55)');
    }
    x += heartW + gap;
  }

  // crystals
  x += 12;
  drawPattern(CRYSTAL_PAT, x, y-1, px, player.crystals > 0 ? '#5fb8ff' : '#2a3a4a');
  x += 8*px + 6;
  ctx.font = 'bold 15px "Courier New", monospace';
  ctx.textAlign = 'left';
  ctx.fillStyle = '#000';
  ctx.fillText(player.crystals + '/3', x+1, y+15);
  ctx.fillStyle = player.crystals >= 3 ? '#8fd3ff' : '#ffffff';
  ctx.fillText(player.crystals + '/3', x, y+14);
  x += 34;

  // coins
  x += 10;
  drawPattern(COIN_PAT, x, y-1, px, '#f0b400');
  drawPattern(COIN_PAT, x+1, y, 1, '#ffe89a');
  x += 8*px + 6;
  ctx.fillStyle = '#000';
  ctx.fillText('' + player.coins, x+1, y+15);
  ctx.fillStyle = '#ffd94a';
  ctx.fillText('' + player.coins, x, y+14);
}

/* ---------------- DIALOGUE BOX ---------------- */
function drawDialogue(){
  const line = dialogue.lines[dialogue.i] || '';
  const boxH = 86;
  const boxY = H - boxH - 14;
  const boxX = 14;
  const boxW = W - 28;

  ctx.fillStyle = 'rgba(10,18,32,0.92)';
  ctx.fillRect(boxX, boxY, boxW, boxH);
  ctx.strokeStyle = '#5fb8ff';
  ctx.lineWidth = 3;
  ctx.strokeRect(boxX+1.5, boxY+1.5, boxW-3, boxH-3);
  ctx.strokeStyle = 'rgba(255,255,255,0.25)';
  ctx.lineWidth = 1;
  ctx.strokeRect(boxX+5.5, boxY+5.5, boxW-11, boxH-11);

  ctx.font = 'bold 15px "Courier New", monospace';
  ctx.textAlign = 'left';
  ctx.textBaseline = 'top';
  ctx.fillStyle = '#e8f4ff';

  // word wrap
  const maxW = boxW - 34;
  const words = line.split(' ');
  let curLine = '';
  let ly = boxY + 18;
  for(let i=0;i<words.length;i++){
    const test = curLine ? curLine + ' ' + words[i] : words[i];
    if(ctx.measureText(test).width > maxW && curLine){
      ctx.fillText(curLine, boxX + 16, ly);
      ly += 20;
      curLine = words[i];
    } else {
      curLine = test;
    }
  }
  if(curLine) ctx.fillText(curLine, boxX + 16, ly);

  // continue arrow
  const bob = Math.sin(G.t*8)*2;
  ctx.fillStyle = '#5fb8ff';
  ctx.beginPath();
  ctx.moveTo(boxX + boxW - 26, boxY + boxH - 24 + bob);
  ctx.lineTo(boxX + boxW - 14, boxY + boxH - 24 + bob);
  ctx.lineTo(boxX + boxW - 20, boxY + boxH - 14 + bob);
  ctx.closePath();
  ctx.fill();

  ctx.textBaseline = 'alphabetic';
}

/* ---------------- MESSAGE TOAST ---------------- */
function drawMessage(){
  const alpha = clamp(G.msgTimer, 0, 1);
  ctx.globalAlpha = alpha;
  ctx.font = 'bold 15px "Courier New", monospace';
  ctx.textAlign = 'center';
  const tw = ctx.measureText(G.msg).width;
  const bw = Math.min(W-40, tw + 36);
  const bx = (W - bw)/2;
  const by = 52;

  ctx.fillStyle = 'rgba(10,18,32,0.88)';
  ctx.fillRect(bx, by, bw, 34);
  ctx.strokeStyle = '#ffd94a';
  ctx.lineWidth = 2;
  ctx.strokeRect(bx+1, by+1, bw-2, 32);

  ctx.fillStyle = '#000';
  ctx.fillText(G.msg, W/2+1, by+23);
  ctx.fillStyle = '#ffd94a';
  ctx.fillText(G.msg, W/2, by+22);

  ctx.globalAlpha = 1;
  ctx.textAlign = 'left';
}

/* ---------------- MENU ---------------- */
const menuEl = document.getElementById('menu');
const menuInner = document.getElementById('menuInner');

function showMenu(title, subtitle, text, btnLabel, action){
  menuInner.innerHTML =
    '<h1>' + title + '</h1>' +
    '<h2>' + subtitle + '</h2>' +
    '<p>' + text + '</p>' +
    '<button type="button" id="menuBtn">' + btnLabel + '</button>';
  menuEl.style.display = 'flex';
  const btn = document.getElementById('menuBtn');
  btn.addEventListener('click', function(e){
    e.preventDefault();
    initAudio();
    action();
  });
  btn.addEventListener('pointerdown', function(e){
    e.stopPropagation();
  });
}

function hideMenu(){
  menuEl.style.display = 'none';
}

function startGame(){
  resetGame();
  G.state = 'playing';
  document.body.classList.add('playing');
  hideMenu();
  showMessage('Talk to the Elder with B!');
}

function showTitle(){
  G.state = 'title';
  document.body.classList.remove('playing');
  showMenu(
    'PIXEL QUEST',
    'THE LOST CRYSTAL',
    'Find the 3 lost crystals, open the castle,\nand defeat the SLIME KING!\n\n' +
    'MOBILE: joystick to move, A = sword, B = talk, RUN = sprint\n' +
    'PC: WASD / Arrows, Space or J = sword, E = talk, Shift = run',
    'START GAME',
    startGame
  );
}

/* ---------------- MAIN LOOP ---------------- */
let lastTime = 0;

function loop(ts){
  requestAnimationFrame(loop);
  if(!lastTime) lastTime = ts;
  let dt = (ts - lastTime) / 1000;
  lastTime = ts;
  if(dt > 0.05) dt = 0.05;
  if(dt < 0) dt = 0;

  update(dt);
  render();
}

/* ---------------- BOOT ---------------- */
function boot(){
  generateMap();
  renderMapCanvas();
  buildSolids();
  resetGame();
  showTitle();
  requestAnimationFrame(loop);
}

boot();

</script>
</body>
</html>

Game Source: Pixel Quest - The Lost Crystal

Creator: PixelFlame92

Libraries: none

Complexity: complex (1805 lines, 48.2 KB)

The full source code is displayed above on this page.

Remix Instructions

To remix this game, copy the source code above and modify it. Add a ARCADELAB header at the top with "remix_of: pixel-quest-the-lost-crystal-pixelflame92" to link back to the original. Then publish at arcadelab.ai/publish.