萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML5 教學

HTML5 Canvas 打造經典坦克大戰:移動、射擊與敵人 AI

延續上一篇可移動坦克範例,本文完整實作「坦克大戰」核心玩法:玩家控制英雄坦克移動射擊,敵方坦克自動巡邏,子彈碰撞邏輯與遊戲主迴圈。

遊戲架構概覽

  • Tank 基類:封裝座標、方向、速度、顏色與移動方法。
  • Hero 類別:繼承 Tank,新增 shotEnemy() 發射子彈。
  • EnemyTank 類別:繼承 Tank,未來可擴充 AI 行為。
  • Bullet 類別:管理子彈位置、方向、速度、存活狀態與移動邏輯。
  • 遊戲主迴圈:setInterval 定時清空畫布、重繪所有物件。

關鍵程式碼片段

1. 彈藥類別

function Bullet(x, y, direct, speed) {
  this.x = x; this.y = y; this.direct = direct; this.speed = speed;
  this.isLive = true; this.timer = null;
  this.run = function() {
    if (this.x <= 0 || this.x >= 400 || this.y <= 0 || this.y >= 300) {
      clearInterval(this.timer); this.isLive = false; return;
    }
    switch (this.direct) {
      case 0: this.y -= this.speed; break; // 上
      case 1: this.x += this.speed; break; // 右
      case 2: this.y += this.speed; break; // 下
      case 3: this.x -= this.speed; break; // 左
    }
  };
}

2. 坦克基類與英雄類別

function Tank(x, y, direct, color) {
  this.x = x; this.y = y; this.speed = 1; this.direct = direct; this.color = color;
  this.moveUp = function() { this.y -= this.speed; this.direct = 0; };
  this.moveRight = function() { this.x += this.speed; this.direct = 1; };
  this.moveDown = function() { this.y += this.speed; this.direct = 2; };
  this.moveLeft = function() { this.x -= this.speed; this.direct = 3; };
}

function Hero(x, y, direct, color) {
  this.tank = Tank; this.tank(x, y, direct, color); // 對象冒充繼承
  this.shotEnemy = function() {
    let bx, by;
    switch (this.direct) {
      case 0: bx = this.x + 9; by = this.y; break;
      case 1: bx = this.x + 30; by = this.y + 9; break;
      case 2: bx = this.x + 9; by = this.y + 30; break;
      case 3: bx = this.x; by = this.y + 9; break;
    }
    heroBullet = new Bullet(bx, by, this.direct, 3);
    heroBullet.timer = setInterval(() => heroBullet.run(), 50);
  };
}

3. 繪製函數與鍵盤控制

function drawTank(tank) {
  const ctx = tankMap.getContext('2d');
  ctx.fillStyle = tank.color[0];
  // 畫履帶、車體、砲塔、砲管(依方向調整)
  // ... 此處省略詳細幾何繪製代碼 ...
}

function flashTankMap() {
  ctx.clearRect(0, 0, 400, 300);
  drawTank(hero);
  if (heroBullet && heroBullet.isLive) {
    ctx.fillStyle = '#FEF26E'; ctx.fillRect(heroBullet.x, heroBullet.y, 2, 2);
  }
  enemyTanks.forEach(t => drawTank(t));
}

document.body.onkeydown = function(e) {
  const code = e.keyCode;
  switch (code) {
    case 87: hero.moveUp(); break;    // W
    case 68: hero.moveRight(); break; // D
    case 83: hero.moveDown(); break;  // S
    case 65: hero.moveLeft(); break;  // A
    case 74: hero.shotEnemy(); break; // J
  }
  flashTankMap();
};

setInterval(flashTankMap, 100); // 主迴圈

擴充方向

  • 加入碰撞偵測:子彈擊中敵人坦克觸發爆炸動畫並移除。
  • 敵人 AI:隨機改變方向、自動射擊、尋路演算法。
  • 障礙物與地圖編輯器:磚牆、鋼鐵、河流、草叢等地形互動。
  • 分數、生命、關卡系統與本地儲存。
copyright © 萬盛學電腦網 all rights reserved