HTML5 Canvas 星空戰機游戲開發全解析
一、游戲介紹
這是一款基于HTML5 Canvas開發的2D射擊游戲,具有以下特色功能:
- 🚀 純代碼繪制的星空動態背景
- ?? 三種不同特性的敵人類型
- 🎮 鍵盤控制的玩家戰機
- 📊 完整的分數統計和排行榜系統
- ?? 三種難度可選
二、核心代碼解析
1. 游戲初始化
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
let game = {// 游戲狀態對象stars: [], // 星星數組bullets: [], // 玩家子彈enemies: [], // 敵人數組score: 0, // 當前分數level: 1, // 當前關卡player: { // 玩家對象x: canvas.width/2,y: canvas.height-100,width: 40,health: 100}
};
2. 游戲主循環
function gameLoop() {// 1. 清空畫布ctx.clearRect(0, 0, canvas.width, canvas.height);// 2. 更新游戲狀態updateGame();// 3. 繪制所有元素drawBackground();drawPlayer();drawEnemies();drawBullets();// 4. 請求下一幀requestAnimationFrame(gameLoop);
}
3. 玩家控制實現
// 鍵盤事件監聽
const keys = {};
window.addEventListener('keydown', e => keys[e.key] = true);
window.addEventListener('keyup', e => keys[e.key] = false);// 玩家移動邏輯
function movePlayer() {if (keys['ArrowLeft']) {// 左移限制:不能超出左邊界game.player.x = Math.max(game.player.width/2, game.player.x - 8);}if (keys['ArrowRight']) {// 右移限制:不能超出右邊界game.player.x = Math.min(canvas.width-game.player.width/2, game.player.x + 8);}if (keys[' ']) {// 空格鍵射擊fireBullet();}
}
三、關鍵技術點
1. 敵人系統設計
敵人類型 | 速度 | 生命值 | 分數 | 特性 |
---|---|---|---|---|
基礎型 | 3 | 1 | 10 | 普通移動 |
快速型 | 5 | 1 | 20 | 高速移動 |
坦克型 | 2 | 5 | 50 | 高生命值 |
2. 碰撞檢測優化
采用圓形碰撞檢測算法:
function checkCollision(bullet, enemy) {const dx = bullet.x - enemy.x;const dy = bullet.y - enemy.y;const distance = Math.sqrt(dx * dx + dy * dy);return distance < (bullet.radius + enemy.width/2);
}
3. 排行榜實現
使用localStorage存儲數據:
function saveHighScore(name, score) {const scores = JSON.parse(localStorage.getItem('highScores')) || [];scores.push({ name, score });scores.sort((a, b) => b.score - a.score);localStorage.setItem('highScores', JSON.stringify(scores.slice(0, 10)));
}
四、完整代碼
<!DOCTYPE html>
<html>
<head><title>星空戰機</title><style>body { margin: 0; overflow: hidden; font-family: Arial, sans-serif; }canvas { display: block; }#ui {position: absolute;top: 20px;left: 20px;color: white;font-size: 16px;text-shadow: 2px 2px 4px rgba(0,0,0,0.5);}#menu {position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);background: rgba(0, 0, 0, 0.8);padding: 20px;border-radius: 10px;color: white;text-align: center;}button {padding: 10px 20px;margin: 10px;font-size: 16px;cursor: pointer;border: none;border-radius: 5px;background: #3498db;color: white;}</style>
</head>
<body>
<canvas id="gameCanvas"></canvas>
<div id="ui"></div>
<div id="menu"><h1>星空戰機</h1><p>選擇難度:</p><button onclick="startGame('easy')">簡單</button><button onclick="startGame('normal')">普通</button><button onclick="startGame('hard')">困難</button><div id="highScores"></div>
</div><script>
// 初始化
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const ui = document.getElementById('ui');
const menu = document.getElementById('menu');
const highScores = document.getElementById('highScores');let game = {stars: [],bullets: [],enemyBullets: [],enemies: [],powerups: [],explosions: [],score: 0,level: 1,difficulty: 'normal',player: {x: 0, // 初始位置會在 startGame 中設置y: 0, // 初始位置會在 startGame 中設置width: 40,height: 60,speed: 8,canShoot: true,health: 100,weapon: 'normal',shield: 0},running: false
};// 調整畫布大小
function resizeCanvas() {canvas.width = window.innerWidth;canvas.height = window.innerHeight;if (game.running) {// 如果游戲運行中調整畫布大小,重置玩家位置game.player.x = canvas.width / 2;game.player.y = canvas.height - 100;}
}
resizeCanvas();
window.addEventListener('resize', resizeCanvas);// 顯示高分榜
function showHighScores() {const scores = JSON.parse(localStorage.getItem('highScores')) || [];highScores.innerHTML = '<h2>高分榜</h2>' +scores.map((score, i) => `<div>${i + 1}. ${score.name}: ${score.score}</div>`).join('');
}// 開始游戲
function startGame(difficulty) {game = {...game,stars: [],bullets: [],enemyBullets: [],enemies: [],powerups: [],explosions: [],score: 0,level: 1,difficulty,player: {...game.player,x: canvas.width / 2, // 初始位置在畫布中央y: canvas.height - 100, // 初始位置在畫布底部health: difficulty === 'easy' ? 150 : difficulty === 'normal' ? 100 : 75,weapon: 'normal',shield: 0},running: true};menu.style.display = 'none';createStars();gameLoop();
}// 游戲結束
function gameOver() {game.running = false;const name = prompt('游戲結束!請輸入你的名字:');if (name) {saveHighScore(name, game.score);}menu.style.display = 'block';showHighScores();
}// 保存高分
function saveHighScore(name, score) {const scores = JSON.parse(localStorage.getItem('highScores')) || [];scores.push({ name, score });scores.sort((a, b) => b.score - a.score);localStorage.setItem('highScores', JSON.stringify(scores.slice(0, 10)));
}// 生成星星
function createStars() {for (let i = 0; i < 200; i++) {game.stars.push({x: Math.random() * canvas.width,y: Math.random() * canvas.height,size: Math.random() * 3,alpha: Math.random()});}
}// 繪制背景
function drawBackground() {const gradient = ctx.createLinearGradient(0, 0, 0, canvas.height);gradient.addColorStop(0, "#000428");gradient.addColorStop(1, "#004e92");ctx.fillStyle = gradient;ctx.fillRect(0, 0, canvas.width, canvas.height);ctx.fillStyle = "white";game.stars.forEach(star => {ctx.globalAlpha = star.alpha;ctx.beginPath();ctx.arc(star.x, star.y, star.size, 0, Math.PI * 2);ctx.fill();});ctx.globalAlpha = 1;
}// 繪制玩家
function drawPlayer() {// 護盾if (game.player.shield > 0) {ctx.strokeStyle = `rgba(0, 255, 255, ${game.player.shield / 100})`;ctx.lineWidth = 2;ctx.beginPath();ctx.arc(game.player.x, game.player.y, 40, 0, Math.PI * 2);ctx.stroke();}// 機身ctx.fillStyle = "#4a90e2";ctx.beginPath();ctx.moveTo(game.player.x, game.player.y);ctx.lineTo(game.player.x - game.player.width / 2, game.player.y + game.player.height);ctx.lineTo(game.player.x + game.player.width / 2, game.player.y + game.player.height);ctx.closePath();ctx.fill();// 機翼ctx.fillStyle = "#2c3e50";ctx.fillRect(game.player.x - 25, game.player.y + 20, 50, 15);// 推進器火焰ctx.fillStyle = `hsl(${Math.random() * 30 + 30}, 100%, 50%)`;ctx.beginPath();ctx.ellipse(game.player.x, game.player.y + game.player.height + 5, 8, 15, 0, 0, Math.PI * 2);ctx.fill();
}// 生成敵人
function createEnemy() {const enemyTypes = ['basic', 'fast', 'tank'];const type = enemyTypes[Math.floor(Math.random() * enemyTypes.length)];game.enemies.push({x: Math.random() * canvas.width,y: -50,width: 40,height: 40,speed: type === 'fast' ? 5 : type === 'tank' ? 2 : 3,health: type === 'tank' ? 5 : 1,type});
}// 敵人射擊
function enemyShoot() {game.enemies.forEach(enemy => {if (Math.random() < 0.02) {game.enemyBullets.push({x: enemy.x,y: enemy.y + enemy.height / 2,speed: 5});}});
}// 碰撞檢測
function checkCollisions() {// 玩家子彈擊中敵人game.bullets.forEach((bullet, bIndex) => {game.enemies.forEach((enemy, eIndex) => {if (bullet.x > enemy.x - enemy.width / 2 &&bullet.x < enemy.x + enemy.width / 2 &&bullet.y > enemy.y - enemy.height / 2 &&bullet.y < enemy.y + enemy.height / 2) {game.score += 10;game.bullets.splice(bIndex, 1);enemy.health -= 1;if (enemy.health <= 0) {game.enemies.splice(eIndex, 1);}}});});// 敵人子彈擊中玩家game.enemyBullets.forEach((bullet, index) => {if (bullet.x > game.player.x - game.player.width / 2 &&bullet.x < game.player.x + game.player.width / 2 &&bullet.y > game.player.y - game.player.height / 2 &&bullet.y < game.player.y + game.player.height / 2) {game.player.health -= 10;game.enemyBullets.splice(index, 1);if (game.player.health <= 0) {gameOver();}}});
}// 更新關卡
function updateLevel() {if (game.score >= game.level * 1000) {game.level++;}
}// 游戲主循環
function gameLoop() {if (!game.running) return;// 更新游戲狀態updateGame();// 繪制游戲元素drawBackground();drawPlayer();drawBullets();drawEnemies();drawUI();requestAnimationFrame(gameLoop);
}// 更新游戲狀態
function updateGame() {// 更新星星位置game.stars.forEach(star => {star.y += 2;if (star.y > canvas.height) {star.y = 0;star.x = Math.random() * canvas.width;}});// 更新子彈位置game.bullets.forEach(bullet => bullet.y -= 10);game.bullets = game.bullets.filter(bullet => bullet.y > 0);// 更新敵人子彈位置game.enemyBullets.forEach(bullet => bullet.y += bullet.speed);game.enemyBullets = game.enemyBullets.filter(bullet => bullet.y < canvas.height);// 更新敵人位置game.enemies.forEach(enemy => enemy.y += enemy.speed);game.enemies = game.enemies.filter(enemy => enemy.y < canvas.height + 50);// 生成敵人if (Math.random() < 0.03) {createEnemy();}// 敵人射擊enemyShoot();// 碰撞檢測checkCollisions();// 更新關卡updateLevel();
}// 繪制UI
function drawUI() {ui.innerHTML = `<div>分數: ${game.score}</div><div>生命值: ${game.player.health}</div><div>護盾: ${game.player.shield}</div><div>武器: ${game.player.weapon}</div><div>關卡: ${game.level}</div>`;
}// 繪制子彈
function drawBullets() {ctx.fillStyle = "#ffdd57";game.bullets.forEach(bullet => {ctx.beginPath();ctx.arc(bullet.x, bullet.y, 5, 0, Math.PI * 2);ctx.fill();});ctx.fillStyle = "#e74c3c";game.enemyBullets.forEach(bullet => {ctx.beginPath();ctx.arc(bullet.x, bullet.y, 5, 0, Math.PI * 2);ctx.fill();});
}// 繪制敵人
function drawEnemies() {ctx.fillStyle = "#e74c3c";game.enemies.forEach(enemy => {ctx.beginPath();ctx.ellipse(enemy.x, enemy.y, enemy.width / 2, enemy.height / 2, 0, 0, Math.PI * 2);ctx.fill();});
}// 鍵盤控制
const keys = {};
window.addEventListener('keydown', e => keys[e.key] = true);
window.addEventListener('keyup', e => keys[e.key] = false);// 玩家移動
function movePlayer() {if (keys['ArrowLeft'] && game.player.x > game.player.width / 2) {game.player.x -= game.player.speed;}if (keys['ArrowRight'] && game.player.x < canvas.width - game.player.width / 2) {game.player.x += game.player.speed;}if (keys[' '] && game.player.canShoot) {game.bullets.push({ x: game.player.x, y: game.player.y });game.player.canShoot = false;setTimeout(() => game.player.canShoot = true, 200);}
}// 運行游戲
setInterval(movePlayer, 1000 / 60);
showHighScores();
</script>
</body>
</html>
五、擴展方向
- 添加BOSS戰系統
- 實現武器升級機制
- 加入粒子爆炸特效
- 添加背景音樂和音效