延續上一篇可移動坦克範例,本文完整實作「坦克大戰」核心玩法:玩家控制英雄坦克移動射擊,敵方坦克自動巡邏,子彈碰撞邏輯與遊戲主迴圈。
shotEnemy() 發射子彈。setInterval 定時清空畫布、重繪所有物件。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; // 左
}
};
}
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);
};
}
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); // 主迴圈