HTML5 Canvas 星空戰機游戲開發全解析

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. 敵人系統設計

敵人類型速度生命值分數特性
基礎型3110普通移動
快速型5120高速移動
坦克型2550高生命值

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>

在這里插入圖片描述

五、擴展方向

  1. 添加BOSS戰系統
  2. 實現武器升級機制
  3. 加入粒子爆炸特效
  4. 添加背景音樂和音效

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/bicheng/82864.shtml
繁體地址,請注明出處:http://hk.pswp.cn/bicheng/82864.shtml
英文地址,請注明出處:http://en.pswp.cn/bicheng/82864.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Telegram平臺分發其聊天機器人Grok

每周跟蹤AI熱點新聞動向和震撼發展 想要探索生成式人工智能的前沿進展嗎&#xff1f;訂閱我們的簡報&#xff0c;深入解析最新的技術突破、實際應用案例和未來的趨勢。與全球數同行一同&#xff0c;從行業內部的深度分析和實用指南中受益。不要錯過這個機會&#xff0c;成為AI領…

【GlobalMapper精品教程】095:如何獲取無人機照片的拍攝方位角

文章目錄 一、加載無人機照片二、計算方位角三、Globalmapper符號化顯示方向四、arcgis符號化顯示方向一、加載無人機照片 打開軟件,加載無人機照片,在GLobalmapperV26中文版中,默認顯示如下的航線信息。 關于航線的起止問題,可以直接從照片名稱來確定。 二、計算方位角 …

SpringBoot使用ffmpeg實現視頻壓縮

ffmpeg簡介 FFmpeg 是一個開源的跨平臺多媒體處理工具集&#xff0c;用于錄制、轉換、編輯和流式傳輸音頻和視頻。它功能強大&#xff0c;支持幾乎所有常見的音視頻格式&#xff0c;是多媒體處理領域的核心工具之一。 官方文檔&#xff1a;https://ffmpeg.org/documentation.h…

OpenCv高階(十九)——dlib關鍵點定位

文章目錄 一、什么是人臉關鍵點定位&#xff1f;二、關鍵點模型的下載及關鍵信息的理解三、dlib關鍵點定位的簡單實現&#xff08;1&#xff09;導入必要的庫&#xff08;2&#xff09;從指定路徑讀取圖像文件&#xff08;3&#xff09;創建dlib的正面人臉檢測器對象&#xff0…

人工智能100問?第36問:什么是BERT?

目錄 一、通俗解釋 二、專業解析 三、權威參考 BERT是基于Transformer Encoder的雙向語言預訓練模型,具備強大的語義理解能力,是現代自然語言處理的重要基石。它是一套讓機器像人一樣“前后一起看”的語言理解技術,它讓AI不光“讀得快”,還“讀得懂”。現在很多搜索引擎…

Chrome/ Edge 瀏覽器彈出窗口隱藏菜單地址欄

Chrome 利用快捷方式&#xff0c;打開一個無地址欄的瀏覽器窗口&#xff0c;以百度為例 創建瀏覽器快捷方式&#xff0c;在目標欄里 添加 -apphttps://www.baidu.com 點擊【應用】&#xff0c;【確定】按鈕保存生效。后面通過空上快捷方式打開的瀏覽器沒有地址欄。 Edge瀏覽…

計算機網絡常見體系結構、分層必要性、分層設計思想以及專用術語介紹

計算機網絡體系結構 從本此開始&#xff0c;我們就要開始介紹有關計算機網絡體系結構的知識了。內容包括&#xff1a; 常見的計算機網絡體系結構 計算機網絡體系結構分層的必要性 計算機網絡體系結構的設計思想 舉例說明及專用術語 計算機網絡體系結構是計算機網絡課程中…

【C++】“多態”特性

文章目錄 一、多態的概念二、多態的定義實現1. 多態的構成條件1.1 虛函數1.2 虛函數的重寫 2. 多態的調用3. 虛函數重寫的其他問題3.1 協變3.2 析構函數的重寫 三、override和final關鍵字四、重載/重寫/隱藏的對比五、純虛函數和抽象類六、多態的原理 C的三大主要特性&#xff…

2025.5.27學習日記 linux三劍客 sed與正則表達式

sed是Stream Editor(字符流編輯器)的縮寫,簡稱流編輯器。 sed是操作、過濾和轉換文本內容的強大工具。 常用功能包括結合正則表達式對文件實現快速增刪改查 , 其中查詢的功能中最常用的兩大功能是過 濾 ( 過濾指定字符串)、取行(取出指定行)。 注意sed和awk使用單引號,雙引號…

文科小白學習Linux系統之安全管理

目錄 前言 一、SELinux安全上下文 1、SELinux 簡介 2、基礎操作命令 1. 查看SELinux狀態 2. 切換工作模式 3、安全上下文&#xff08;Security Context&#xff09; 1. 查看上下文 2. 修改上下文 chcon命令 semanage 命令 4、SELinux布爾值&#xff08;Booleans&am…

企業內訓系統源碼開發詳解:直播+錄播+考試的混合式學習平臺搭建

在企業數字化轉型的大潮中&#xff0c;員工培訓早已不再是傳統教室中的一場場“走過場”&#xff0c;而是通過技術驅動的“系統化能力提升”。尤其在知識更新換代加速、競爭壓力日益激烈的背景下&#xff0c;企業越來越傾向于建設自主可控、功能靈活、支持多種學習形態的內訓平…

智能化報銷與精細化管理:購物小票識別系統全面提升企業運營效率

在現代企業管理中&#xff0c;購物小票的處理一直是財務和運營管理中的一項挑戰。尤其在企業費用報銷、會員管理、庫存監控等環節&#xff0c;手動整理與核對小票不僅耗時費力&#xff0c;還容易產生錯誤。隨著人工智能技術的發展&#xff0c;企業亟需一種高效、智能的解決方案…

毫秒級數據采集的極致優化:如何用C#實現高性能、無冗余的實時文件寫入?

在工業控制、通信系統或高頻交易領域&#xff0c;毫秒級數據采集的精度直接決定系統性能。但一個棘手問題常被忽視&#xff1a;如何處理同一毫秒內的重復數據&#xff1f; 若簡單寫入所有數據&#xff0c;會導致文件臃腫、分析效率驟降&#xff1b;若處理不當&#xff0c;又可能…

NLua性能對比:C#注冊函數 vs 純Lua實現

引言 在NLua開發中&#xff0c;我們常面臨一個重要選擇&#xff1a;將C#函數注冊到Lua環境調用&#xff0c;還是直接在Lua中實現邏輯&#xff1f; 直覺告訴我們&#xff0c;C#作為編譯型語言性能更高&#xff0c;但跨語言調用的開銷是否會影響整體性能&#xff1f;本文通過基準…

go并發與鎖之sync.Mutex入門

sync.Mutex 原理&#xff1a;一個共享的變量&#xff0c;哪個線程握到了&#xff0c;哪個線程可以執行代碼 功能&#xff1a;一個性能不錯的悲觀鎖&#xff0c;使用方式和Java的ReentrantLock很像&#xff0c;就是手動Lock&#xff0c;手動UnLock。 使用例子&#xff1a; v…

【HarmonyOS5】DevEco Studio 使用指南:代碼閱讀與編輯功能詳解

?本期內容&#xff1a;【HarmonyOS5】DevEco Studio 使用指南&#xff1a;代碼閱讀與編輯功能詳解 &#x1f3c6;系列專欄&#xff1a;鴻蒙HarmonyOS&#xff1a;探索未來智能生態新紀元 文章目錄 前言代碼閱讀代碼導航功能代碼折疊語法高亮跨語言跳轉代碼查找 快速查閱API接口…

【Python 深度學習】1D~3D iou計算

一維iou 二維 import numpy as npdef iou_1d(set_a, set_b):# 獲得集合A和B的邊界 x1, x2 set_ay1, y2 set_b# 計算交集的上下界low max(x1,y1)high - min(x2, y2)# 計算交集if high - low < 0:inter 0else:inter high - low# 計算并集union (x2 -x1) (y2 - y1) - in…

SpringBoot Controller接收參數方式, @RequestMapping

一. 通過原始的HttpServletRequest對象獲取請求參數 二. 通過Spring提供的RequestParam注解&#xff0c;將請求參數綁定給方法參數 三. 如果請求參數名與形參變量名相同&#xff0c;直接定義方法形參即可接收。(省略RequestParam) 四. JSON格式的請求參數(POST、PUT) 主要在PO…

智能防護實戰:從攻擊成本看企業安全降本增效

1. 網絡攻擊的低成本與高回報陷阱 暗網中&#xff0c;一次完整的網絡釣魚攻擊僅需30美元/月起步&#xff0c;而勒索軟件攻擊成本平均1000美元&#xff0c;卻能導致企業損失高達445萬美元&#xff08;IBM 2023年數據&#xff09;。例如&#xff0c;信用卡信息每條僅售10美元&am…

大語言模型 20 - MCP 在客戶端中使用 Cursor Cline 中配置 MCP 服務

MCP 基本介紹 官方地址&#xff1a; https://modelcontextprotocol.io/introduction “MCP 是一種開放協議&#xff0c;旨在標準化應用程序向大型語言模型&#xff08;LLM&#xff09;提供上下文的方式。可以把 MCP 想象成 AI 應用程序的 USB-C 接口。就像 USB-C 提供了一種…