当前位置:首页 > JavaScript

js代码实现贪吃蛇

2026-03-01 20:38:29JavaScript

实现贪吃蛇的基本思路

使用HTML5的Canvas绘制游戏界面,通过JavaScript控制蛇的移动、食物生成和碰撞检测。核心逻辑包括蛇的移动方向控制、身体增长、边界检测和食物交互。

初始化游戏画布和变量

const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const gridSize = 20;
const tileCount = canvas.width / gridSize;

let snake = [{x: 10, y: 10}];
let food = {x: 5, y: 5};
let xVelocity = 0;
let yVelocity = 0;
let score = 0;
let gameSpeed = 100;
let gameRunning = true;

绘制游戏元素

function drawGame() {
    // 清空画布
    ctx.fillStyle = 'black';
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    // 绘制蛇
    ctx.fillStyle = 'lime';
    snake.forEach(segment => {
        ctx.fillRect(segment.x * gridSize, segment.y * gridSize, gridSize-2, gridSize-2);
    });

    // 绘制食物
    ctx.fillStyle = 'red';
    ctx.fillRect(food.x * gridSize, food.y * gridSize, gridSize-2, gridSize-2);

    // 显示分数
    ctx.fillStyle = 'white';
    ctx.font = '20px Arial';
    ctx.fillText('Score: ' + score, 10, 20);
}

更新蛇的位置

function updateSnake() {
    const head = {x: snake[0].x + xVelocity, y: snake[0].y + yVelocity};
    snake.unshift(head);

    // 检查是否吃到食物
    if (head.x === food.x && head.y === food.y) {
        score++;
        generateFood();
        increaseSpeed();
    } else {
        snake.pop();
    }
}

生成随机食物位置

function generateFood() {
    food = {
        x: Math.floor(Math.random() * tileCount),
        y: Math.floor(Math.random() * tileCount)
    };

    // 确保食物不会出现在蛇身上
    snake.forEach(segment => {
        if (segment.x === food.x && segment.y === food.y) {
            generateFood();
        }
    });
}

碰撞检测

function checkCollision() {
    const head = snake[0];

    // 边界碰撞
    if (head.x < 0 || head.x >= tileCount || head.y < 0 || head.y >= tileCount) {
        gameOver();
    }

    // 自身碰撞
    for (let i = 1; i < snake.length; i++) {
        if (head.x === snake[i].x && head.y === snake[i].y) {
            gameOver();
        }
    }
}

键盘控制

document.addEventListener('keydown', (e) => {
    // 防止180度转向
    switch(e.key) {
        case 'ArrowUp':
            if (yVelocity !== 1) {
                xVelocity = 0;
                yVelocity = -1;
            }
            break;
        case 'ArrowDown':
            if (yVelocity !== -1) {
                xVelocity = 0;
                yVelocity = 1;
            }
            break;
        case 'ArrowLeft':
            if (xVelocity !== 1) {
                xVelocity = -1;
                yVelocity = 0;
            }
            break;
        case 'ArrowRight':
            if (xVelocity !== -1) {
                xVelocity = 1;
                yVelocity = 0;
            }
            break;
    }
});

游戏主循环

function gameLoop() {
    if (gameRunning) {
        updateSnake();
        checkCollision();
        drawGame();
        setTimeout(gameLoop, gameSpeed);
    }
}

function gameOver() {
    gameRunning = false;
    ctx.fillStyle = 'white';
    ctx.font = '40px Arial';
    ctx.fillText('Game Over!', canvas.width/2 - 100, canvas.height/2);
}

function increaseSpeed() {
    if (gameSpeed > 50) {
        gameSpeed -= 5;
    }
}

// 开始游戏
generateFood();
gameLoop();

HTML结构

<!DOCTYPE html>
<html>
<head>
    <title>贪吃蛇游戏</title>
    <style>
        canvas {
            border: 1px solid black;
            display: block;
            margin: 0 auto;
        }
    </style>
</head>
<body>
    <canvas id="gameCanvas" width="400" height="400"></canvas>
    <script src="snake.js"></script>
</body>
</html>

扩展功能建议

增加游戏开始界面和重新开始按钮 添加不同难度级别 实现高分记录功能 增加特殊食物类型 添加音效和动画效果

这个实现包含了贪吃蛇游戏的基本功能,包括蛇的移动、食物生成、碰撞检测和分数计算。代码结构清晰,易于理解和扩展。

js代码实现贪吃蛇

标签: 贪吃蛇代码
分享给朋友:

相关文章

淘宝css代码制作

淘宝css代码制作

在淘宝店铺装修中,CSS代码用于自定义页面样式,提升视觉效果和用户体验。以下是常见的CSS代码制作方法和应用场景: 自定义店铺背景 通过CSS可以修改店铺背景颜色或图片,代码示例如下: body…

vue怎么实现文本代码实现

vue怎么实现文本代码实现

Vue 实现文本代码展示的方法 在 Vue 中展示代码文本通常需要结合语法高亮和格式化的功能,以下是几种常见的实现方式: 使用 <pre> 和 <code> 标签 通过 HT…

vue 实现代码

vue 实现代码

Vue 是一个流行的前端框架,用于构建用户界面。以下是一个简单的 Vue 实现代码示例,展示如何创建一个基本的 Vue 应用。 安装 Vue 通过 CDN 引入 Vue: <script s…

代码雨实现vue

代码雨实现vue

实现代码雨效果(Vue版) 使用Vue实现代码雨效果可以通过Canvas绘制结合动画帧实现。以下是完整实现方案: 核心代码结构 <template> <div class="…

vue实现代码插件

vue实现代码插件

Vue 实现代码插件的方法 使用第三方库(如 Prism.js 或 Highlight.js) 安装 Prism.js 或 Highlight.js 库,这些库专门用于代码高亮显示。在 Vue 项目中…

vue代码怎么实现拼音

vue代码怎么实现拼音

实现拼音功能的方法 在Vue中实现拼音功能,可以通过拼音转换库将中文转换为拼音。以下是具体实现步骤: 安装拼音转换库 推荐使用pinyin或v-chinese2pinyin库。通过npm或yarn安…