大家好!今天我將分享如何使用 HTML 和 JavaScript 編寫一個簡單的飛機游戲。這個游戲的核心功能包括:控制飛機移動、發射子彈、敵機生成、碰撞檢測和得分統計。代碼簡潔易懂,適合初學者學習和實踐。
游戲功能概述
-
玩家控制:使用鍵盤的?
←
?和?→
?鍵控制飛機的左右移動,按下?空格鍵
?發射子彈。 -
敵機生成:每隔 1 秒生成一個敵機,敵機從屏幕頂部隨機位置向下移動。
-
碰撞檢測:子彈擊中敵機后,敵機和子彈都會消失,并增加 10 分;如果玩家飛機與敵機碰撞,游戲結束。
-
得分統計:擊中敵機后,得分會顯示在屏幕左上角。
實現步驟
1. HTML 結構
我們使用?<canvas>
?元素作為游戲畫布,所有的游戲元素(如飛機、子彈、敵機)都將在畫布上繪制。
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>飛機游戲</title><style>body {margin: 0;overflow: hidden;background-color: #000;}canvas {display: block;margin: 0 auto;background-color: #000;}</style>
</head>
<body><canvas id="gameCanvas"></canvas><script>// JavaScript 代碼將在下面實現</script>
</body>
</html>
2. JavaScript 邏輯
JavaScript 部分負責實現游戲的核心邏輯,包括玩家控制、敵機生成、碰撞檢測和得分統計。
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');canvas.width = 480;
canvas.height = 640;// 飛機對象
const player = {x: canvas.width / 2 - 25,y: canvas.height - 60,width: 50,height: 50,speed: 5,color: '#00FF00',bullets: [],fire: function() {this.bullets.push({ x: this.x + this.width / 2 - 2.5, y: this.y, width: 5, height: 10, color: '#FF0000' });}
};// 敵機數組
const enemies = [];// 得分
let score = 0;// 監聽鍵盤事件
document.addEventListener('keydown', (e) => {if (e.code === 'ArrowLeft' && player.x > 0) {player.x -= player.speed;}if (e.code === 'ArrowRight' && player.x < canvas.width - player.width) {player.x += player.speed;}if (e.code === 'Space') {player.fire();}
});// 生成敵機
function spawnEnemy() {const x = Math.random() * (canvas.width - 50);enemies.push({ x: x, y: -50, width: 50, height: 50, color: '#0000FF', speed: 2 });
}// 檢測碰撞
function checkCollision(rect1, rect2) {return rect1.x < rect2.x + rect2.width &&rect1.x + rect1.width > rect2.x &&rect1.y < rect2.y + rect2.height &&rect1.y + rect1.height > rect2.y;
}// 更新游戲狀態
function update() {// 移動子彈player.bullets.forEach((bullet, index) => {bullet.y -= 5;if (bullet.y < 0) {player.bullets.splice(index, 1);}});// 移動敵機enemies.forEach((enemy, index) => {enemy.y += enemy.speed;if (enemy.y > canvas.height) {enemies.splice(index, 1);}});// 檢測子彈與敵機的碰撞player.bullets.forEach((bullet, bulletIndex) => {enemies.forEach((enemy, enemyIndex) => {if (checkCollision(bullet, enemy)) {player.bullets.splice(bulletIndex, 1);enemies.splice(enemyIndex, 1);score += 10;}});});// 檢測玩家與敵機的碰撞enemies.forEach((enemy, index) => {if (checkCollision(player, enemy)) {alert('游戲結束!得分:' + score);document.location.reload();}});
}// 繪制游戲元素
function draw() {ctx.clearRect(0, 0, canvas.width, canvas.height);// 繪制玩家飛機ctx.fillStyle = player.color;ctx.fillRect(player.x, player.y, player.width, player.height);// 繪制子彈ctx.fillStyle = '#FF0000';player.bullets.forEach(bullet => {ctx.fillRect(bullet.x, bullet.y, bullet.width, bullet.height);});// 繪制敵機ctx.fillStyle = '#0000FF';enemies.forEach(enemy => {ctx.fillRect(enemy.x, enemy.y, enemy.width, enemy.height);});// 繪制得分ctx.fillStyle = '#FFFFFF';ctx.font = '20px Arial';ctx.fillText('得分: ' + score, 10, 30);
}// 游戲主循環
function gameLoop() {update();draw();requestAnimationFrame(gameLoop);
}// 定時生成敵機
setInterval(spawnEnemy, 1000);// 啟動游戲
gameLoop();
3. 運行游戲
將上述代碼保存為一個?.html
?文件,然后在瀏覽器中打開即可運行游戲。你可以使用鍵盤控制飛機,體驗游戲的樂趣!
擴展與優化
這個游戲是一個簡單的示例,你可以在此基礎上進行擴展和優化,例如:
-
增加敵機類型:添加不同速度和血量的敵機。
-
添加音效:為子彈發射、擊中敵機和游戲結束添加音效。
-
提升游戲難度:隨著時間推移,逐漸增加敵機的生成速度和數量。
-
添加背景音樂:為游戲增加背景音樂,提升沉浸感。
總結
通過這個簡單的飛機游戲項目,你可以學習到如何使用 HTML 和 JavaScript 實現基本的游戲邏輯,包括玩家控制、碰撞檢測和動態生成游戲元素。希望這篇文章對你有所幫助,也歡迎大家在評論區分享你的改進和優化建議!
如果你對游戲開發感興趣,不妨嘗試擴展這個項目,或者基于此開發更多有趣的游戲!🚀
完整代碼
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>飛機游戲</title><style>body {margin: 0;overflow: hidden;background-color: #000;}canvas {display: block;margin: 0 auto;background-color: #000;}</style>
</head>
<body><canvas id="gameCanvas"></canvas><script>const canvas = document.getElementById('gameCanvas');const ctx = canvas.getContext('2d');canvas.width = 480;canvas.height = 640;// 飛機對象const player = {x: canvas.width / 2 - 25,y: canvas.height - 60,width: 50,height: 50,speed: 5,color: '#00FF00',bullets: [],fire: function() {this.bullets.push({ x: this.x + this.width / 2 - 2.5, y: this.y, width: 5, height: 10, color: '#FF0000' });}};// 敵機數組const enemies = [];// 得分let score = 0;// 監聽鍵盤事件document.addEventListener('keydown', (e) => {if (e.code === 'ArrowLeft' && player.x > 0) {player.x -= player.speed;}if (e.code === 'ArrowRight' && player.x < canvas.width - player.width) {player.x += player.speed;}if (e.code === 'Space') {player.fire();}});// 生成敵機function spawnEnemy() {const x = Math.random() * (canvas.width - 50);enemies.push({ x: x, y: -50, width: 50, height: 50, color: '#0000FF', speed: 2 });}// 檢測碰撞function checkCollision(rect1, rect2) {return rect1.x < rect2.x + rect2.width &&rect1.x + rect1.width > rect2.x &&rect1.y < rect2.y + rect2.height &&rect1.y + rect1.height > rect2.y;}// 更新游戲狀態function update() {// 移動子彈player.bullets.forEach((bullet, index) => {bullet.y -= 5;if (bullet.y < 0) {player.bullets.splice(index, 1);}});// 移動敵機enemies.forEach((enemy, index) => {enemy.y += enemy.speed;if (enemy.y > canvas.height) {enemies.splice(index, 1);}});// 檢測子彈與敵機的碰撞player.bullets.forEach((bullet, bulletIndex) => {enemies.forEach((enemy, enemyIndex) => {if (checkCollision(bullet, enemy)) {player.bullets.splice(bulletIndex, 1);enemies.splice(enemyIndex, 1);score += 10;}});});// 檢測玩家與敵機的碰撞enemies.forEach((enemy, index) => {if (checkCollision(player, enemy)) {alert('游戲結束!得分:' + score);document.location.reload();}});}// 繪制游戲元素function draw() {ctx.clearRect(0, 0, canvas.width, canvas.height);// 繪制玩家飛機ctx.fillStyle = player.color;ctx.fillRect(player.x, player.y, player.width, player.height);// 繪制子彈ctx.fillStyle = '#FF0000';player.bullets.forEach(bullet => {ctx.fillRect(bullet.x, bullet.y, bullet.width, bullet.height);});// 繪制敵機ctx.fillStyle = '#0000FF';enemies.forEach(enemy => {ctx.fillRect(enemy.x, enemy.y, enemy.width, enemy.height);});// 繪制得分ctx.fillStyle = '#FFFFFF';ctx.font = '20px Arial';ctx.fillText('得分: ' + score, 10, 30);}// 游戲主循環function gameLoop() {update();draw();requestAnimationFrame(gameLoop);}// 定時生成敵機setInterval(spawnEnemy, 1000);// 啟動游戲gameLoop();</script>
</body>
</html>