HTML5 Canvas 星空战机游戏开发全解析

news2025/6/3 13:46:36

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.coloradmin.cn/o/2395561.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

箱式不确定集

“箱式不确定集&#xff08;Box Uncertainty Set&#xff09;”可以被认为是一种 相对简单但实用的不确定集建模方式。 ✅ 一、什么是“简单的不确定集”&#xff1f; 在鲁棒优化领域&#xff0c;“简单不确定集”通常指的是&#xff1a; 特点描述形式直观数学表达简洁&#…

内存管理 : 04段页结合的实际内存管理

一、课程核心主题引入 这一讲&#xff0c;我要给大家讲的是真正的内存管理&#xff0c;也就是段和页结合在一起的内存管理方式。之前提到过&#xff0c;我们先学习了分段管理内存的工作原理&#xff0c;知道操作系统采用分段的方式&#xff0c;让用户程序能以分段的结构进行编…

vue3: baidusubway using typescript

项目结构&#xff1a; <!--npm install -D tailwindcss-3d BaiduSubwayMap.vue npm install -D tailwindcss postcss autoprefixer--> <template><div class"relative w-full h-screen"><!-- 地图容器 --><div id"subway-container…

Redis最佳实践——性能优化技巧之集群与分片

Redis集群与分片在电商应用中的性能优化技巧 一、Redis集群架构模式解析 1. 主流集群方案对比 方案核心原理适用场景电商应用案例主从复制读写分离数据冗余中小规模读多写少商品详情缓存Redis Sentinel自动故障转移监控高可用需求场景订单状态缓存Redis Cluster原生分布式分片…

常见相机的ISP算法

常见的ISP算法 3A算法 去雾算法 图像增强算法 图像宽动态算法 图像的电子缩放算法&#xff0c;无极电子缩放 图像降噪算法 相机常见问题 1.相机启动速度问题&#xff0c;启动速度较慢 2.相机扛不住高低温问题 3.相机散热问题问题 4.相机高低温芯片保护掉电 5.相机的成像效果或者…

2024 CKA模拟系统制作 | Step-By-Step | 8、题目搭建-创建 Ingress

目录 ​​​​​​免费获取题库配套 CKA_v1.31_模拟系统 一、题目 二、核心考点 Ingress 资源定义 Ingress Controller 依赖 服务暴露验证 网络层次关系 三、搭建模拟环境 1.创建命名空间 2.安装ingress ingress-nginx-controller 3.创建hello.yaml并部署 四、总结 …

OldRoll复古胶片相机:穿越时光,定格经典

在数字摄影盛行的今天&#xff0c;复古胶片相机的独特魅力依然吸引着无数摄影爱好者。OldRoll复古胶片相机这款软件&#xff0c;以其独特的复古风格和丰富的胶片滤镜效果&#xff0c;让用户仿佛穿越回了那个胶片摄影的黄金时代。它不仅模拟了胶片相机的操作界面&#xff0c;还提…

通俗易懂的 JS DOM 操作指南:从创建到挂载

目录 &#x1f9e9; 1. 创建元素&#xff1a;document.createElement / createElementNS &#x1f4dd; 2. 创建文本&#xff1a;document.createTextNode ✏️ 3. 修改文本&#xff1a;node.nodeValue &#x1f5d1;️ 4. 移除元素&#xff1a;el.removeChild() &#x1…

CSS Day07

1.搭建项目目录 2.网页头部SEO三大标签 3.Favicon图标与版心 &#xff08;1&#xff09;Favicon图标 &#xff08;2&#xff09;版心 4.快捷导航 5.头部-布局 6.头部-logo 7.头部-导航 8.头部-搜索 9头部-购物车 10.底部-布局 11.底部-服务区域 12.底部-帮助中心 13.底部-版权…

RV1126-OPENCV 交叉编译

一.下载opencv-3.4.16.zip到自己想装的目录下 二.解压并且打开 opencv 目录 先用 unzip opencv-3.4.16.zip 来解压 opencv 的压缩包&#xff0c;并且进入 opencv 目录(cd opencv-3.4.16) 三. 修改 opencv 的 cmake 脚本的内容 先 cd platforms/linux 然后修改 arm-gnueabi.to…

【深度学习】 19. 生成模型:Diffusion Models

Diffusion Models Diffusion Models 简介 Diffusion 模型是一类通过逐步添加噪声并再逆向还原的方式进行图像生成的深度生成模型。其基本流程包括&#xff1a; 前向过程&#xff08;Forward Process&#xff09;&#xff1a;将真实图像逐步加噪&#xff0c;最终变为高斯噪声…

JMeter 直连数据库

1.直连数据库的使用场景 1.1 参数化&#xff0c;例如登录使用的账户名密码都可以从数据库中取得 1.2 断言&#xff0c;查看实际结果和数据库中的预期结果是否一致 1.3 清理垃圾数据&#xff0c;例如插入一个用户&#xff0c;它的ID不能相同&#xff0c;在测试插入功能后将数据删…

易路 iBuilder:解构企业 AI 落地困境,重构智能体时代生产力范式

一、从大模型到智能体的产业跃迁 2024 年堪称中国人工智能产业的 "战略拐点" 之年。当 DeepSeek R1 模型以 "技术 价格" 双重普惠模式掀起行业震荡时&#xff0c;各企业纷纷意识到&#xff0c;大模型的真正价值不在于技术炫技&#xff0c;而在于成为企业…

计算机网络之路由表更新

1.解题思路 对新接收到的路由表进行更新&#xff0c;全部"距离"1&#xff0c;且"下一跳路由器"都写成发送方路由器的名称。 开始对比新表和原来的路由表 1.看目的网络 如果是新的目的网络&#xff0c;则直接把对应的各项信息填入表中&#xff1b;如果是相同…

万兴PDF手机版

万兴PDF手机版(万兴PDF编辑器)是一款国产PDF编辑工具.万兴PDF安卓版提供PDF文档编辑,AI撰写摘要,文档签名,设置密码保护等功能,万兴PDF专家APP以简约风格及文档编辑功能为核心,支持多设备终端同步保存.全免 万兴 PDF 编辑器是一款功能强大的 PDF 编辑软件&#xff0c;它支持多种…

Qt -使用OpenCV得到SDF

博客主页&#xff1a;【夜泉_ly】 本文专栏&#xff1a;【暂无】 欢迎点赞&#x1f44d;收藏⭐关注❤️ 目录 cv::MatdistanceTransform获得SDF 本文的目标&#xff0c; 是简单学习并使用OpenCV的相关函数&#xff0c; 并获得QImage的SDF(Signed Distance Field 有向距离场) 至…

DDR5 ECC详细原理介绍与基于协议讲解

本文篇幅较长,涉及背景原理介绍方便大家理解其运作方式 以及 基于DDR5协议具体展开介绍。 背景原理介绍 上图参考:DDR 内存中的 ECC 写入操作时,On-die ECC的工作过程如下: SoC将需要写入到Memory中的数据发送给控制器控制器将需要写入的数据直接发送给DRAM芯片在DDR5 DR…

EC800X QuecDuino开发板介绍

支持的模组列表 EG800KEC800MEC800GEC800E 功能列表 基本概述 EC800X QuecDuino EVB 搭载移远 EC800 系列模组。支持模组型号为&#xff1a; EC800M 系列、EC800K 系列、EG800K 系列、EC800E 系列等。 渲染图 开发板的主要组件、接口布局见下图 资料下载 EC800X-QuecDui…

PHP轻量级聊天室源码(源码下载)

最新版本&#xff1a;v2.1.2 (2024.08更新) 运行环境&#xff1a;PHP5.6&#xff08;无需MySQL&#xff09; 核心特性&#xff1a;手机电脑自适应、TXT数据存储、50条历史消息 适用场景&#xff1a;小型社区/企业内网/教育培训即时通讯 一、核心功能亮点&#xff08;SEO关键词布…

leetcode hot100刷题日记——33.二叉树的层序遍历

解题总结二维vector的初始化方法 题目描述情况1&#xff1a;不确定行数和列数情况2&#xff1a;已知行数和列数情况3&#xff1a;已知行数但不知道列数情况4&#xff1a;已知列数但不知道行数 题目描述 解答&#xff1a;用队列 思路都差不多&#xff0c;我觉得对于我自己来说&a…