🎮ArcadeLab

TANK TROUBLE

by ChromeFlame24
511 lines19.5 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">
<title>TANK TROUBLE</title>
<style>
  * { margin:0; padding:0; box-sizing:border-box; -webkit-tap-highlight-color:transparent; }
  html,body { width:100%; height:100%; overflow:hidden; background:#05070d; font-family:"Arial Black",Arial,sans-serif; color:#fff; touch-action:none; }
  #game { position:fixed; inset:0; }
  canvas { display:block; width:100%; height:100%; }

  .screen {
    position:fixed; inset:0; z-index:20; display:flex; align-items:center; justify-content:center;
    background:radial-gradient(circle at 50% 35%, #101a2e 0%, #05070d 70%);
    text-align:center; padding:18px;
  }
  .hidden { display:none !important; }

  .panel {
    width:min(760px, 96vw); max-height:96vh; overflow:auto; padding:26px 22px;
    border:3px solid #22e0ff; border-radius:18px; background:rgba(4,10,22,.92);
    box-shadow:0 0 35px rgba(34,224,255,.35), inset 0 0 30px rgba(34,224,255,.08);
  }
  h1 {
    font-size:clamp(34px,9vw,72px); letter-spacing:5px; color:#22e0ff;
    text-shadow:0 0 12px #22e0ff, 0 0 35px #0088ff; margin-bottom:8px;
  }
  h2 { font-size:clamp(20px,5vw,34px); color:#ff3b6b; text-shadow:0 0 15px #ff3b6b; margin-bottom:16px; }
  .subtitle { color:#9fd8ff; font-size:14px; letter-spacing:3px; margin-bottom:20px; }

  .btn {
    display:block; width:min(420px,92%); margin:10px auto; padding:15px 18px; font:700 18px Arial;
    color:#031018; background:linear-gradient(90deg,#22e0ff,#7cffc4); border:0; border-radius:12px;
    cursor:pointer; box-shadow:0 0 18px rgba(34,224,255,.55); text-transform:uppercase; letter-spacing:2px;
  }
  .btn.red { background:linear-gradient(90deg,#ff5f7e,#ffb36b); box-shadow:0 0 18px rgba(255,95,126,.55); }
  .btn.small { width:auto; padding:10px 16px; font-size:14px; }

  .controls {
    display:grid; grid-template-columns:repeat(auto-fit,minmax(230px,1fr)); gap:12px; margin:18px 0;
    text-align:left; font-size:13px; line-height:1.5;
  }
  .controls div {
    background:rgba(10,20,40,.75); border:1px solid rgba(34,224,255,.28); border-radius:10px; padding:12px;
  }
  .key { display:inline-block; min-width:28px; padding:3px 7px; margin:2px; border:1px solid #22e0ff; border-radius:5px; color:#22e0ff; font-weight:bold; }
  .blue { color:#4fc3ff; } .red { color:#ff5f7e; }

  #hud {
    position:fixed; top:0; left:0; right:0; z-index:10; display:flex; justify-content:center; gap:10px;
    padding:8px; pointer-events:none; font-size:clamp(13px,2.6vw,22px); font-weight:bold;
  }
  .score {
    min-width:105px; padding:7px 13px; border-radius:10px; background:rgba(3,9,20,.78);
    border:2px solid rgba(255,255,255,.15); letter-spacing:2px;
  }
  #blueScore { color:#4fc3ff; border-color:#4fc3ff; box-shadow:0 0 12px rgba(79,195,255,.4); }
  #redScore { color:#ff5f7e; border-color:#ff5f7e; box-shadow:0 0 12px rgba(255,95,126,.4); }
  #pauseBtn { pointer-events:auto; cursor:pointer; color:#ffd166; border-color:#ffd166; }

  #mobileControls { position:fixed; inset:auto 0 0 0; z-index:15; display:none; padding:10px; justify-content:space-between; align-items:flex-end; }
  .stickZone { width:34vw; max-width:190px; height:34vw; max-height:190px; position:relative; }
  .stickBase { position:absolute; inset:0; border-radius:50%; border:2px solid rgba(255,255,255,.25); background:rgba(255,255,255,.05); }
  .stickKnob { position:absolute; width:44%; height:44%; left:28%; top:28%; border-radius:50%; background:rgba(255,255,255,.25); border:2px solid rgba(255,255,255,.5); }
  .fireBtn {
    width:20vw; max-width:110px; height:20vw; max-height:110px; border-radius:50%; border:3px solid #ff5f7e;
    background:rgba(255,95,126,.18); color:#ff5f7e; font:900 16px Arial; text-transform:uppercase;
  }
  .fireBtn.blue { border-color:#4fc3ff; color:#4fc3ff; background:rgba(79,195,255,.18); }
  #pauseMobile { position:fixed; right:12px; top:52px; z-index:15; display:none; padding:10px 14px; border-radius:10px; border:2px solid #ffd166; color:#ffd166; background:rgba(0,0,0,.5); font-weight:bold; }
</style>
</head>
<body>

<div id="hud" class="hidden">
  <div class="score" id="blueScore">BLUE 0</div>
  <div class="score" id="redScore">RED 0</div>
  <div class="score" id="pauseBtn">P — PAUSE</div>
</div>

<div id="startScreen" class="screen">
  <div class="panel">
    <h1>TANK TROUBLE</h1>
    <div class="subtitle">NEON MAZE BATTLE • FIRST TO 10 WINS</div>
    <button class="btn" id="onePlayerBtn">1 PLAYER VS AI</button>
    <button class="btn red" id="twoPlayerBtn">2 PLAYERS</button>
    <div class="controls">
      <div>
        <strong class="blue">BLUE TANK</strong><br>
        <span class="key">W</span><span class="key">A</span><span class="key">S</span><span class="key">D</span> Move / Turn<br>
        <span class="key">SPACE</span> or <span class="key">F</span> Shoot
      </div>
      <div>
        <strong class="red">RED TANK</strong><br>
        <span class="key">↑</span><span class="key">←</span><span class="key">↓</span><span class="key">→</span> Move / Turn<br>
        <span class="key">ENTER</span> or <span class="key">M</span> Shoot
      </div>
      <div>
        <strong>GAME</strong><br>
        <span class="key">P</span> Pause<br>
        Bullets bounce up to 5 times.<br>
        Your own bullet can destroy you.
      </div>
      <div>
        <strong>POWER-UPS</strong><br>
        Double / Triple cannon, Laser,<br>
        Shield, Speed boost, Big bullet.
      </div>
    </div>
    <button class="btn small" id="musicBtn">MUSIC: ON</button>
  </div>
</div>

<div id="pauseScreen" class="screen hidden">
  <div class="panel">
    <h2>PAUSED</h2>
    <button class="btn" id="resumeBtn">RESUME</button>
    <button class="btn red" id="quitBtn">QUIT TO MENU</button>
  </div>
</div>

<div id="winScreen" class="screen hidden">
  <div class="panel">
    <h1 id="winnerText">WINNER</h1>
    <div class="subtitle" id="finalScore">BLUE 10 — RED 0</div>
    <button class="btn" id="playAgainBtn">PLAY AGAIN</button>
    <button class="btn red" id="menuBtn">MAIN MENU</button>
  </div>
</div>

<div id="mobileControls">
  <div class="stickZone" id="p1Zone"><div class="stickBase"></div><div class="stickKnob" id="p1Knob"></div></div>
  <button class="fireBtn blue" id="p1Fire">FIRE</button>
  <button class="fireBtn" id="p2Fire">FIRE</button>
  <div class="stickZone" id="p2Zone"><div class="stickBase"></div><div class="stickKnob" id="p2Knob"></div></div>
</div>
<button id="pauseMobile">II</button>

<canvas id="game"></canvas>

<script>
"use strict";

const canvas = document.getElementById("game");
const ctx = canvas.getContext("2d");
let W = 0, H = 0, DPR = 1;

const TILE = 58;
const COLS = 17, ROWS = 11;
const MAZE_W = COLS * TILE, MAZE_H = ROWS * TILE;
let ox = 0, oy = 0, scale = 1;

const WIN_SCORE = 10;
const BULLET_BOUNCES = 5;
const MAX_BULLETS = 5;
const POWERUP_INTERVAL = 10000;

const keys = {};
const state = {
  mode: "menu", paused: false, over: false,
  scores: [0, 0], tanks: [], bullets: [], particles: [], powerups: [],
  walls: [], maze: [], lastPowerup: 0, aiTimer: 0, shake: 0, time: 0
};

/* ---------------- Audio ---------------- */
let audioCtx = null, musicOn = true, musicNodes = [], musicTimer = 0;
function ensureAudio() {
  if (!audioCtx) audioCtx = new (window.AudioContext || window.webkitAudioContext)();
  if (audioCtx.state === "suspended") audioCtx.resume();
}
function beep(freq, duration, type = "square", volume = .08, slideTo = null) {
  if (!audioCtx) return;
  const o = audioCtx.createOscillator(), g = audioCtx.createGain();
  o.type = type; o.frequency.setValueAtTime(freq, audioCtx.currentTime);
  if (slideTo) o.frequency.exponentialRampToValueAtTime(Math.max(30, slideTo), audioCtx.currentTime + duration);
  g.gain.setValueAtTime(volume, audioCtx.currentTime);
  g.gain.exponentialRampToValueAtTime(.0001, audioCtx.currentTime + duration);
  o.connect(g); g.connect(audioCtx.destination);
  o.start(); o.stop(audioCtx.currentTime + duration);
}
function noise(duration = .45, volume = .22) {
  if (!audioCtx) return;
  const len = Math.floor(audioCtx.sampleRate * duration);
  const buffer = audioCtx.createBuffer(1, len, audioCtx.sampleRate);
  const data = buffer.getChannelData(0);
  for (let i = 0; i < len; i++) data[i] = (Math.random() * 2 - 1) * (1 - i / len);
  const src = audioCtx.createBufferSource(); src.buffer = buffer;
  const g = audioCtx.createGain(); g.gain.value = volume;
  src.connect(g); g.connect(audioCtx.destination); src.start();
}
function sfxShoot() { beep(680, .11, "square", .09, 180); }
function sfxBounce() { beep(920, .05, "triangle", .05, 620); }
function sfxPower() { beep(480, .09, "sine", .09, 980); setTimeout(() => beep(760, .12, "sine", .09, 1250), 80); }
function sfxExplode() { noise(.5, .28); beep(120, .45, "sawtooth", .13, 35); }
function startMusic() {
  stopMusic();
  if (!musicOn || !audioCtx) return;
  const notes = [110, 146.83, 174.61, 146.83, 130.81, 174.61, 220, 174.61];
  let i = 0;
  musicTimer = setInterval(() => {
    if (!audioCtx || state.paused || state.mode === "menu") return;
    const f = notes[i++ % notes.length];
    beep(f, .22, "triangle", .035);
    if (i % 4 === 1) beep(f / 2, .28, "sine", .045);
  }, 260);
}
function stopMusic() { clearInterval(musicTimer); musicTimer = 0; }

/* ---------------- Maze generation ---------------- */
function generateMaze() {
  const maze = Array.from({ length: ROWS }, () => Array(COLS).fill(0));
  const stack = [[0, 0]];
  const visited = Array.from({ length: ROWS }, () => Array(COLS).fill(false));
  visited[0][0] = true;

  while (stack.length) {
    const [x, y] = stack[stack.length - 1];
    const dirs = [[1,0],[-1,0],[0,1],[0,-1]].filter(([dx,dy]) => {
      const nx = x + dx, ny = y + dy;
      return nx >= 0 && ny >= 0 && nx < COLS && ny < ROWS && !visited[ny][nx];
    });
    if (!dirs.length) { stack.pop(); continue; }
    const [dx, dy] = dirs[Math.floor(Math.random() * dirs.length)];
    const nx = x + dx, ny = y + dy;
    if (dx === 1) maze[y][x] |= 1;
    if (dx === -1) maze[y][nx] |= 1;
    if (dy === 1) maze[y][x] |= 2;
    if (dy === -1) maze[ny][x] |= 2;
    visited[ny][nx] = true;
    stack.push([nx, ny]);
  }

  // Add loops and open areas for Tank Trouble-like arenas.
  for (let y = 0; y < ROWS; y++) for (let x = 0; x < COLS - 1; x++)
    if (Math.random() < .17) maze[y][x] |= 1;
  for (let y = 0; y < ROWS - 1; y++) for (let x = 0; x < COLS; x++)
    if (Math.random() < .17) maze[y][x] |= 2;

  state.maze = maze;
  state.walls = [];
  for (let y = 0; y < ROWS; y++) for (let x = 0; x < COLS; x++) {
    const c = maze[y][x];
    if (!(c & 1)) state.walls.push({ x: (x + 1) * TILE, y: y * TILE, w: 8, h: TILE, vertical: true });
    if (!(c & 2)) state.walls.push({ x: x * TILE, y: (y + 1) * TILE, w: TILE, h: 8, vertical: false });
  }
  // Outer walls
  state.walls.push({ x: 0, y: 0, w: MAZE_W, h: 8, vertical: false });
  state.walls.push({ x: 0, y: MAZE_H - 8, w: MAZE_W, h: 8, vertical: false });
  state.walls.push({ x: 0, y: 0, w: 8, h: MAZE_H, vertical: true });
  state.walls.push({ x: MAZE_W - 8, y: 0, w: 8, h: MAZE_H, vertical: true });
}

function wallRects() { return state.walls; }

/* ---------------- Tanks ---------------- */
function makeTank(index) {
  return {
    index, x: index === 0 ? TILE * 1.5 : MAZE_W - TILE * 1.5,
    y: index === 0 ? TILE * 1.5 : MAZE_H - TILE * 1.5,
    angle: index === 0 ? 0 : Math.PI, speed: 0, radius: 17,
    cooldown: 0, alive: true, shield: 0, speedBoost: 0,
    weapon: "normal", weaponTime: 0, powerIcon: "", ai: false,
    color: index === 0 ? "#4fc3ff" : "#ff5f7e", glow: index === 0 ? "#4fc3ff" : "#ff5f7e",
    input: { up: false, down: false, left: false, right: false, fire: false },
    prevFire: false
  };
}

function resetRound() {
  generateMaze();
  state.bullets = []; state.particles = []; state.powerups = [];
  state.tanks = [makeTank(0), makeTank(1)];
  state.tanks[1].ai = state.mode === "ai";
  state.lastPowerup = performance.now();
  state.over = false;
}

function circleWallCollide(tank, nx, ny) {
  const r = tank.radius;
  for (const w of wallRects()) {
    const cx = Math.max(w.x, Math.min(nx, w.x + w.w));
    const cy = Math.max(w.y, Math.min(ny, w.y + w.h));
    if ((nx - cx) ** 2 + (ny - cy) ** 2 < r * r) return true;
  }
  return false;
}

function moveTank(tank, dt) {
  const boost = tank.speedBoost > 0 ? 1.65 : 1;
  const turn = 3.1 * dt, drive = 205 * boost * dt;
  if (tank.input.left) tank.angle -= turn;
  if (tank.input.right) tank.angle += turn;

  let move = 0;
  if (tank.input.up) move = drive;
  if (tank.input.down) move = -drive * .72;

  const nx = tank.x + Math.cos(tank.angle) * move;
  const ny = tank.y + Math.sin(tank.angle) * move;
  if (!circleWallCollide(tank, nx, tank.y)) tank.x = nx;
  if (!circleWallCollide(tank, tank.x, ny)) tank.y = ny;

  tank.x = Math.max(tank.radius, Math.min(MAZE_W - tank.radius, tank.x));
  tank.y = Math.max(tank.radius, Math.min(MAZE_H - tank.radius, tank.y));

  // Tank-vs-tank collision
  const other = state.tanks[1 - tank.index];
  if (other && other.alive) {
    const dx = tank.x - other.x, dy = tank.y - other.y, d = Math.hypot(dx, dy), min = tank.radius + other.radius;
    if (d < min && d > 0) {
      const push = (min - d) / 2, ux = dx / d, uy = dy / d;
      tank.x += ux * push; tank.y += uy * push;
      other.x -= ux * push; other.y -= uy * push;
    }
  }
}

function fireTank(tank) {
  if (tank.cooldown > 0 || !tank.alive) return;
  const count = tank.weapon === "triple" ? 3 : tank.weapon === "double" ? 2 : 1;
  const live = state.bullets.filter(b => b.owner === tank.index).length;
  if (live + count > MAX_BULLETS) return;

  for (let i = 0; i < count; i++) {
    const spread = count === 1 ? 0 : (i - (count - 1) / 2) * .13;
    const a = tank.angle + spread;
    state.bullets.push({
      owner: tank.index, x: tank.x + Math.cos(a) * 25, y: tank.y + Math.sin(a) * 25,
      vx: Math.cos(a) * 520, vy: Math.sin(a) * 520, bounces: 0, life: 9,
      big: tank.weapon === "big", laser: tank.weapon === "laser", r: tank.weapon === "big" ? 9 : 5
    });
  }
  tank.cooldown = .32;
  sfxShoot();
}

/* ---------------- Bullets ---------------- */
function updateBullets(dt) {
  for (let i = state.bullets.length - 1; i >= 0; i--) {
    const b = state.bullets[i];
    b.life -= dt;
    if (b.life <= 0) { state.bullets.splice(i, 1); continue; }

    const steps = 3;
    for (let s = 0; s < steps; s++) {
      const px = b.x, py = b.y;
      b.x += b.vx * dt / steps;
      b.y += b.vy * dt / steps;

      let hit = false;
      for (const w of wallRects()) {
        if (b.x + b.r > w.x && b.x - b.r < w.x + w.w && b.y + b.r > w.y && b.y - b.r < w.y + w.h) {
          const overlapL = b.x + b.r - w.x, overlapR = w.x + w.w - (b.x - b.r);
          const overlapT = b.y + b.r - w.y, overlapB = w.y + w.h - (b.y - b.r);
          const minOverlap = Math.min(overlapL, overlapR, overlapT, overlapB);

          if (minOverlap === overlapL || minOverlap === overlapR) b.vx *= -1;
          else b.vy *= -1;

          b.x = px; b.y = py;
          b.bounces++;
          hit = true;
          break;
        }
      }
      if (hit) {
        sfxBounce();
        spawnParticles(b.x, b.y, "#ffd166", 4, 90);
        if (b.bounces > BULLET_BOUNCES) { state.bullets.splice(i, 1); break; }
      }
    }

    for (const t of state.tanks) {
      if (!t.alive) continue;
      if (Math.hypot(t.x - b.x, t.y - b.y) < t.radius + b.r) {
        if (t.shield > 0) {
          state.bullets.splice(i, 1);
          spawnParticles(b.x, b.y, "#7cffc4", 14, 180);
          sfxBounce();
          break;
        }
        killTank(t, b);
        state.bullets.splice(i, 1);
        break;
      }
    }
  }
}

function killTank(tank, bullet) {
  tank.alive = false;
  state.shake = 16;
  sfxExplode();
  spawnParticles(tank.x, tank.y, tank.color, 45, 340);
  spawnParticles(tank.x, tank.y, "#ffae42", 25, 220);
  spawnParticles(tank.x, tank.y, "#8a8a8a", 20, 80);

  const killer = state.tanks[1 - tank.index];
  if (killer && killer.alive) state.scores[killer.index]++;
  updateScoreUI();

  if (state.scores[killer ? killer.index : 0] >= WIN_SCORE) endGame(killer.index);
  else setTimeout(() => { if (state.mode !== "menu" && !state.over) resetRound(); }, 1300);
}

/* ---------------- Power-ups ---------------- */
const POWER_TYPES = [
  { id: "double", name: "2X", color: "#7cffc4" },
  { id: "triple", name: "3X", color: "#c17cff" },
  { id: "laser", name: "LASER", color: "#ff4d6d" },
  { id: "shield", name: "SHIELD", color: "#22e0ff" },
  { id: "speed", name: "SPEED", color: "#ffd166" },
  { id: "big", name: "BIG", color: "#ff9f43" }
];

function spawnPowerup() {
  for (let attempt = 0; attempt < 80; attempt++) {
    const x = TILE * (1 + Math.floor(Math.random() * (COLS - 2))) + TILE / 2;
    const y = TILE * (1 + Math.floor(Math.random() * (ROWS - 2))) + TILE / 2;
    if (!circleWallCollide({ radius: 20 }, x, y)) {
      const type = POWER_TYPES[Math.floor(Math.random() * POWER_TYPES.length)];
      state.powerups.push({ x, y, type, born: performance.now() });
      return;
    }
  }
}

function updatePowerups(now, dt) {
  if (now - state.lastPowerup > POWERUP_INTERVAL) {
    state.lastPowerup = now;
    if (state.powerups.length < 3) spawnPowerup();
  }
  for (let i = state.powerups.length - 1; i >= 0; i--) {
    const p = state.powerups[i];
    if (now - p.born > 18000) { state.powerups.splice(i, 1); continue; }
    for (const t of state.tanks) {
      if (t.alive && Math.hypot(t.x - p.x, t.y - p.y) < t.radius + 17) {
        applyPower(t, p.type.id);
        state.powerups.splice(i, 1);
        sfxPower();
        break;
      }
    }
  }
  for (const t of state.tanks) {
    t.shield = Math.max(0, t.shield - dt);
    t.speedBoost = Math.max(0, t.speedBoost - dt);
    t.weaponTime = Math.max(0, t.weaponTime - dt);
    if (t.weaponTime <= 0) { t.weapon = "normal"; t.powerIcon = ""; }
  }
}

function applyPower(tank, id) {
  if (id === "shield") { tank.shield = 5; tank.powerIcon = "SHIELD"; }
  else if (id === "speed") { tank.speedBoost = 7; tank.powerIcon = "SPEED"; }
  else {
    tank.weapon = id;
    tank.weaponTime = id === "laser" ? 8 : 10;
    tank.powerIcon = id.toUpperCase();
  }
}

/* ---------------- Particles ---------------- */
function spawnParticles(x, y, color, count, speed) {
  for (let i = 0; i < count; i++) {
    const a = Math.random() * Math.PI * 2, v = Math.random() * speed;
    state.particles.push({
      x, y, vx: Math.cos(a) * v, vy: Math.sin(a) * v,
      life: .5 + Math.random() * .7, max: 1, color, size: 2 + Math.random() * 4
    });
  }
}
function updateParticles(dt) {
  for (let i = state.particles.length - 1; i >= 0; i--) {
    const p = state.particles[i];
    p.x += p.vx * dt; p.y += p.vy * dt;
    p.vx *= .94; p.vy *= .94;
    p.life -= dt;
    if (p.life <= 0) state.particles.splice(i, 1);
  }
}

/* ---------------- AI ---------------- */
function updateAI(dt) {
  const ai = state.tanks[1], player = state.tanks[0];
  if (!ai.alive || !player.alive) return;
  ai.input = { up: false, down: false, left: false, right: false, fire: false };

  const dx = player.x - ai.x, dy = player.y - ai.y;
  const target = Math.atan2(dy, dx);
  let diff = ((target - ai.angle + Math.PI * 3) % (Math.PI * 2)) - Math.PI;

  if (Math.abs(diff) > .12) {
    if (diff > 0) ai.input.right = true; else ai.input.left = true;
  } else if (Math.hypot(dx, dy) > 145) ai.input.up = true;

  state.aiTimer -= dt;
  const clear = hasClearShot(ai, player);
  if (clear && state.aiTimer <= 0) {
    fireTank(ai);
    state.aiTimer = .55 + Math.random() * .5;
  }
  if (!clear && Math.random() < .005) fireTank(ai);
}

function hasClearShot(from, target) {
  const dx = target.x - from.x, dy = target.y - from.y;
  const dist = Math.hypot(dx, dy);
  if (dist < 30) return false;
  

Game Source: TANK TROUBLE

Creator: ChromeFlame24

Libraries: none

Complexity: complex (511 lines, 19.5 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: tank-trouble-chromeflame24" to link back to the original. Then publish at arcadelab.ai/publish.