专业编程基础技术教程

网站首页 > 基础教程 正文

用DEEPSEEK 写的小游戏,直接运行太牛了!~

ccvgpt 2025-04-28 23:35:43 基础教程 4 ℃

由于DEEPSEEK服务器繁忙,通过OLLAMA来部署各种大模型都可以,电脑配置不够高,能用DEEPSEEK R1 14B,也只能在CMD下运行,AI可视化软件Chatbox跑不动,具体写内容如下


用DEEPSEEK 写的小游戏,直接运行太牛了!~

>>> 写一个网页版射击小游戏,单人元,直接用网页运行

<think>

嗯,用户想要写一个网页版的射击小游戏,要求是单人游戏,可以直接在网页上运行。我得先考虑如何实现这个功能。

首先,我应该选择合适的编程语言和技术。因为要在网页上运行,所以前端技术栈比较合适。HTML、CSS和JavaScript是基础。可能还需要用到Canvas或者 WebGL来处理图形渲染。

接下来,我需要确定游戏的基本玩法。用户提到的是射击游戏,单人模式,所以可以考虑让玩家控制一个角色,比如一个小球或飞船,通过键盘事件移动并射击。敌人会从屏幕上方或下方出现,玩家需要躲避子弹和敌人的攻击,直到击败所有敌人或者失败。

然后是技术实现部分。我需要用Canvas来绘制图形,因为这样可以在网页上渲染游戏画面。创建画布元素,并使用JavaScript的绘图API来进行绘图操作。我需要设置一个固定的游戏循环,每帧更新游戏状态并重新绘制画布,以确保游戏流畅运行。

角色控制方面,玩家通常用键盘方向键或 WASD 键来移动,空格键开枪。所以我要监听键盘事件,改变玩家的位置和速度,并触发射击动作。同时,我需要处理边界条件,防止玩家跑出屏幕范围。

敌人生成部分,可以设定一个时间间隔,在固定的时间后随机生成敌人从上方或下方出现。敌人有一定的移动速度,朝玩家的方向移动。或者也可以让敌人沿着特定的路径移动,增加游戏难度。

子弹管理也是关键。每次射击时需要在屏幕上添加一颗子弹,并跟踪其位置和飞行方向。同时,要检测子弹是否击中敌人或超出边界,及时移除不再存在的子弹,避免内存泄漏。

碰撞检测是游戏的核心部分之一。我需要计算玩家、敌人和子弹之间的相对位置,判断是否有碰撞发生。比如,当敌人的矩形区域与玩家的区域重叠时,触发扣分或者生命值减少;同样,子弹击中敌人也要触发得分增加,并移除相应的元素。

音效方面,虽然不是必须的,但能提升用户体验。我需要找到或创建简单的射击和爆炸声音文件,使用Web Audio API加载并播放这些音效,在相应的事件触发时调用。

游戏状态管理也很重要。需要跟踪玩家的生命值、分数、关卡进度等信息,并在界面上显示出来。当玩家生命耗尽或击败所有敌人时,展示游戏结束的画面,并提供重新开始的选项。

最后是用户界面设计,确保布局简洁明了,功能易于操作。游戏开始前可能需要一个启动画面,或者直接进入游戏循环。同时,要处理Canvas缩放问题,使得在不同分辨率下都能良好显示。

综上所述,我需要一步步实现这些功能模块,先搭建基本的HTML结构和CSS样式,然后逐步添加JavaScript逻辑,确保每个部分都正常工作,并进行测试优化。

</think>

以下是一个简单的网页版射击小游戏的代码。这个游戏使用 HTML5 Canvas 和 JavaScript 实现,玩家可以通过键盘控制角色射击:


html

<!DOCTYPE html>

<html>

<head>

<title>简单射击游戏</title>

<style>

canvas {

border: 1px solid black;

}

body {

display: flex;

justify-content: center;

align-items: center;

height: 100vh;

margin: 0;

background-color: #f0f0f0;

}

</style>

</head>

<body>

<canvas id="gameCanvas" width="800" height="600"></canvas>

<script>

const canvas = document.getElementById('gameCanvas');

const ctx = canvas.getContext('2d');

// 游戏状态

let score = 0;

let lives = 3;

// 玩家角色

const player = {

x: canvas.width / 2,

y: canvas.height - 30,

width: 40,

height: 40,

speed: 5,

bullets: []

};

// 敌人数组

let enemies = [];

// 子弹速度和时间控制

const BULLET_SPEED = 10;

const ENEMY_SPEED = 2;

const FIRE_RATE = 10;

// 游戏循环间隔

let gameLoop;

document.addEventListener('keydown', handleKeyDown);

function handleKeyDown(e) {

switch (e.key) {

case 'ArrowLeft':

player.x -= player.speed;

break;

case 'ArrowRight':

player.x += player.speed;

break;

case ' ':

shoot();

break;

}

// 确保玩家不会离开屏幕

if (player.x < 0) player.x = 0;

if (player.x + player.width > canvas.width) {

player.x = canvas.width - player.width;

}

}

function shoot() {

const bullet = {

x: player.x + player.width / 2,

y: player.y,

width: 10,

height: 15,

speed: 7

};

player.bullets.push(bullet);

}

// 敌人生成函数

function createEnemy() {

const side = Math.random() < 0.5 ? 'top' : 'bottom';

const enemy = {

x: Math.random() * (canvas.width - 50),

y: side === 'top' ? 0 : canvas.height,

width: 40,

height: 40,

speedX: (Math.random() - 0.5) * ENEMY_SPEED,

speedY: side === 'top' ? ENEMY_SPEED : -ENEMY_SPEED

};

enemies.push(enemy);

}

// 更新游戏状态

function update() {

// 更新子弹位置

player.bullets.forEach((bullet, index) => {

bullet.y -= bullet.speed;

if (bullet.y < 0 || bullet.y > canvas.height) {

player.bullets.splice(index, 1);

}

});

// 更新敌人位置

enemies.forEach((enemy, index) => {

enemy.x += enemy.speedX;

if (enemy.x + enemy.width > canvas.width || enemy.x < 0) {

enemy.speedX = -enemy.speedX;

}

enemy.y += enemy.speedY;

});

// 检测碰撞

enemies.forEach((enemy, index) => {

// 玩家与敌人碰撞检测

if (player.x < enemy.x + enemy.width &&

player.x + player.width > enemy.x &&

player.y < enemy.y + enemy.height &&

player.y + player.height > enemy.y) {

lives--;

enemies.splice(index, 1);

if (lives <= 0) {

gameOver();

}

}

// 子弹与敌人碰撞检测

player.bullets.forEach((bullet, bIndex) => {

if (enemy.x < bullet.x + bullet.width &&

enemy.x + enemy.width > bullet.x &&

enemy.y < bullet.y + bullet.height &&

enemy.y + enemy.height > bullet.y) {

enemies.splice(index, 1);

player.bullets.splice(bIndex, 1);

score += 10;

}

});

});

// 删除超出边界子弹

player.bullets = player.bullets.filter(bullet => bullet.y >= 0 && bullet.y <= canvas.height);

}

// 绘制游戏元素

function draw() {

ctx.clearRect(0, 0, canvas.width, canvas.height);

// 绘制玩家

ctx.fillStyle = 'blue';

ctx.fillRect(player.x, player.y, player.width, player.height);

// 绘制子弹

player.bullets.forEach(bullet => {

ctx.fillStyle = 'yellow';

ctx.fillRect(bullet.x, bullet.y, bullet.width, bullet.height);

});

// 绘制敌人

enemies.forEach(enemy => {

ctx.fillStyle = 'red';

ctx.fillRect(enemy.x, enemy.y, enemy.width, enemy.height);

});

// 绘制 HUD

ctx.fillStyle = 'black';

ctx.font = '20px Arial';

ctx.fillText(`得分: ${score}`, 10, 30);

ctx.fillText(`生命值: ${lives}`, 10, 60);

}

function gameOver() {

clearInterval(gameLoop);

alert(`游戏结束!得分:${score}`);

location.reload();

}

// 主游戏循环

function gameStep(timestamp) {

if (timestamp > 500 && enemies.length === 0) createEnemy();

update();

draw();

gameLoop = requestAnimationFrame(gameStep);

}

// 开始游戏

gameLoop = requestAnimationFrame(gameStep);

// 初始化敌人

setInterval(() => {

createEnemy();

}, 2000);

</script>

</body>

</html>




这个简单的射击游戏包含以下功能:

1. 玩家可以通过左右箭头键控制移动

2. 空格键进行射击

3. 敌人从顶部和底部随机出现并移动

4. 子弹有固定的飞行速度

5. 碰撞检测(玩家与敌人,子弹与敌人)

6. 生命值系统

7. 得分系统

8. 游戏结束时会显示得分

要运行这个游戏:

1. 将代码保存为一个 HTML 文件(例如 `game.html`)

2. 打开该文件所在的目录

3. 在浏览器中打开它

游戏规则:

- 避免与敌人碰撞,否则生命值会减少

- 射击敌人以获得分数

- 当所有敌人被消灭后会生成新的敌人

- 游戏结束时(没有剩余生命)会显示得分并重新加载页面


同样的问题豆包回答

以下是一个较为完整且可直接在网页中运行的单人射击小游戏示例。在这个游戏里,玩家需要通过鼠标点击来射击屏幕上随机移动的敌人,同时会有计分系统和生命值显示。


收起

html

<!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 {
            font-family: Arial, sans-serif;
            text-align: center;
            background-color: #f0f0f0;
            margin: 0;
            padding: 0;
        }

        #game-container {
            position: relative;
            width: 800px;
            height: 600px;
            border: 2px solid #333;
            margin: 20px auto;
            background-color: #fff;
            overflow: hidden;
        }

        .enemy {
            position: absolute;
            width: 50px;
            height: 50px;
            background-color: red;
            border-radius: 50%;
        }

        #score-board {
            position: absolute;
            top: 10px;
            left: 10px;
            font-size: 24px;
            color: #333;
        }

        #health-board {
            position: absolute;
            top: 10px;
            right: 10px;
            font-size: 24px;
            color: #333;
        }

        #game-over {
            display: none;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            font-size: 48px;
            color: red;
        }
    </style>
</head>

<body>
    <h1>单人射击小游戏</h1>
    <div id="game-container">
        <div id="score-board">得分: 0</div>
        <div id="health-board">生命值: 10</div>
        <div id="game-over">游戏结束!</div>
    </div>

    <script>
        const gameContainer = document.getElementById('game-container');
        const scoreBoard = document.getElementById('score-board');
        const healthBoard = document.getElementById('health-board');
        const gameOverMessage = document.getElementById('game-over');

        let score = 0;
        let health = 10;
        let isGameOver = false;

        // 创建敌人函数
        function createEnemy() {
            if (isGameOver) return;
            const enemy = document.createElement('div');
            enemy.classList.add('enemy');
            const maxX = gameContainer.offsetWidth - enemy.offsetWidth;
            const maxY = gameContainer.offsetHeight - enemy.offsetHeight;
            const randomX = Math.floor(Math.random() * maxX);
            const randomY = Math.floor(Math.random() * maxY);
            enemy.style.left = randomX + 'px';
            enemy.style.top = randomY + 'px';
            gameContainer.appendChild(enemy);

            // 敌人移动函数
            function moveEnemy() {
                if (isGameOver) return;
                const maxX = gameContainer.offsetWidth - enemy.offsetWidth;
                const maxY = gameContainer.offsetHeight - enemy.offsetHeight;
                const randomX = Math.floor(Math.random() * maxX);
                const randomY = Math.floor(Math.random() * maxY);
                const duration = Math.random() * 2000 + 1000; 
                enemy.animate([
                    { left: enemy.style.left, top: enemy.style.top },
                    { left: randomX + 'px', top: randomY + 'px' }
                ], {
                    duration: duration,
                    easing: 'linear',
                    fill: 'forwards'
                });
                setTimeout(moveEnemy, duration);
            }

            moveEnemy();

            // 射击敌人逻辑
            enemy.addEventListener('click', function () {
                if (isGameOver) return;
                score++;
                scoreBoard.textContent = `得分: ${score}`;
                enemy.remove();
                setTimeout(createEnemy, 1000);
            });

            // 敌人未被击中扣除生命值逻辑
            setTimeout(() => {
                if (isGameOver) return;
                if (gameContainer.contains(enemy)) {
                    health--;
                    healthBoard.textContent = `生命值: ${health}`;
                    enemy.remove();
                    if (health <= 0) {
                        endGame();
                    } else {
                        setTimeout(createEnemy, 1000);
                    }
                }
            }, 5000);
        }

        // 结束游戏函数
        function endGame() {
            isGameOver = true;
            gameOverMessage.style.display = 'block';
        }

        // 开始游戏
        createEnemy();
    </script>
</body>

</html>

代码说明:


  1. HTML 部分:构建了游戏的基本结构,包含一个标题、游戏容器、得分板、生命值板和游戏结束提示信息。
  2. CSS 部分:对页面和游戏元素进行了样式设置,定义了游戏容器的大小、边框和背景,敌人的样式(红色圆形),以及各个信息板和游戏结束提示的样式和位置。
  3. JavaScript 部分变量定义:定义了得分、生命值、游戏是否结束等变量。createEnemy 函数:创建敌人元素,随机设置其初始位置,添加到游戏容器中。同时为敌人添加移动动画和点击事件监听器,点击敌人时得分增加,敌人消失并在一段时间后重新创建新敌人;若敌人在一定时间内未被击中,扣除生命值,生命值为 0 时游戏结束。moveEnemy 函数:实现敌人的随机移动效果,通过 animate 方法创建动画,并在动画结束后递归调用自身实现持续移动。endGame 函数:当生命值耗尽时,将游戏状态设为结束,显示游戏结束提示信息。游戏启动:页面加载完成后,调用 createEnemy 函数开始游戏。



你可以将上述代码保存为一个 .html 文件,然后在浏览器中打开该文件,即可开始玩这个单人射击小游戏。

Tags:

最近发表
标签列表