虎扑-热帖 01月30日
ds确实牛逼啊,我这html小白都能一分钟生成贪吃蛇小游戏。
index_new5.html
../../../zaker_core/zaker_tpl_static/wap/tpl_guoji1.html

 

本文介绍了使用HTML5 Canvas和JavaScript实现的经典贪吃蛇游戏。游戏具有简洁的用户界面,包括开始按钮、得分显示和游戏画布。游戏逻辑包括初始化、食物生成、蛇的移动、碰撞检测以及游戏结束处理。蛇通过键盘方向键控制移动,吃到食物得分增加。游戏采用定时器驱动,并提供暂停功能。代码中还包含了颜色渐变函数,使蛇的身体呈现渐变效果。该游戏逻辑清晰,代码结构良好,适合初学者学习和实践。

🕹️ 游戏初始化:游戏开始时,蛇的初始位置在画布中央,方向向右。同时,随机生成一个食物,并开始游戏主循环,根据预设的速度不断更新游戏状态。

🍎 食物生成与碰撞检测:食物会随机生成在画布上,且不与蛇的身体重叠。当蛇头与食物位置重合时,蛇的长度增加,得分提高,并生成新的食物。同时,游戏会检测蛇是否撞到边界或自身,若发生碰撞则游戏结束。

🐍 蛇的移动和绘制:蛇的移动由键盘方向键控制,每次移动一个网格单位。蛇的身体通过数组存储,每次移动时,蛇头增加到数组头部,尾部移除。游戏使用 Canvas 绘制蛇和食物,蛇身采用渐变色,使得游戏画面更具视觉效果。

⏸️ 暂停功能:玩家可以通过空格键暂停和恢复游戏,暂停时游戏循环停止,恢复时继续进行。这使得玩家可以在游戏中休息或调整策略。

最后放出网页代码

贪吃蛇游戏

canvas {

border: 2px solid #333;

background-color: #f0f0f0;

}

body {

display: flex;

flex-direction: column;

align-items: center;

font-family: Arial, sans-serif;

background-color: #f5f6fa;

}

#controlPanel {

margin: 15px 0;

}

#startBtn {

padding: 12px 30px;

font-size: 18px;

background: #2ecc71;

color: white;

border: none;

border-radius: 25px;

cursor: pointer;

transition: all 0.3s;

box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);

}

#startBtn:hover {

background: #27ae60;

transform: translateY(-2px);

box-shadow: 0 6px 8px rgba(0, 0, 0, 0.2);

}

#score {

font-size: 24px;

color: #2c3e50;

margin: 10px 0;

}

经典贪吃蛇

得分: 0

开始游戏

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

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

const scoreElement = document.getElementById('score');

const startBtn = document.getElementById('startBtn');

// 游戏参数配置

const config = {

gridSize: 20,

initSpeed: 150,

snakeColor: '#2ecc71',

foodColor: '#e74c3c',

backgroundColor: '#f0f0f0'

};

// 游戏状态

let gameState = {

snake: [],

food: { x: 0, y: 0 },

dx: 0,

dy: 0,

score: 0,

gameLoop: null,

isPaused: false

};

// 初始化游戏

function initGame() {

// 重置游戏状态

gameState = {

snake: [{ x: 10, y: 10 }],

food: generateFood(),

dx: 1, // 初始向右移动

dy: 0,

score: 0,

gameLoop: null,

isPaused: false

};

scoreElement.textContent = `得分: 0`;

startBtn.style.display = 'none';

if (gameState.gameLoop) clearInterval(gameState.gameLoop);

gameState.gameLoop = setInterval(gameLoop, config.initSpeed);

}

// 生成食物(优化算法)

function generateFood() {

let newFood;

const maxAttempts = 1000;

let attempts = 0;

do {

newFood = {

x: Math.floor(Math.random() * (canvas.width / config.gridSize)),

y: Math.floor(Math.random() * (canvas.height / config.gridSize))

};

attempts++;

} while (

gameState.snake.some(segment =>

segment.x === newFood.x &&

segment.y === newFood.y

) && attempts < maxAttempts

);

return newFood;

}

// 主游戏循环

function gameLoop() {

if (gameState.isPaused) return;

const newHead = {

x: gameState.snake[0].x + gameState.dx,

y: gameState.snake[0].y + gameState.dy

};

// 碰撞检测

if (checkCollision(newHead)) {

return gameOver();

}

gameState.snake.unshift(newHead);

// 食物检测

if (newHead.x === gameState.food.x && newHead.y === gameState.food.y) {

gameState.score += 10;

scoreElement.textContent = `得分: ${gameState.score}`;

gameState.food = generateFood();

} else {

gameState.snake.pop();

}

drawGame();

}

// 碰撞检测函数

function checkCollision(head) {

// 边界检测

if (head.x = canvas.width / config.gridSize ||

head.y = canvas.height / config.gridSize) {

return true;

}

// 自身碰撞检测(跳过头部)

return gameState.snake.some((segment, index) =>

index > 0 &&

segment.x === head.x &&

segment.y === head.y

);

}

// 绘制游戏画面

function drawGame() {

// 清空画布

ctx.fillStyle = config.backgroundColor;

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

// 绘制食物

ctx.fillStyle = config.foodColor;

ctx.fillRect(

gameState.food.x * config.gridSize,

gameState.food.y * config.gridSize,

config.gridSize - 2,

config.gridSize - 2

);

// 绘制蛇

gameState.snake.forEach((segment, index) => {

ctx.fillStyle = index === 0 ?

config.snakeColor :

shadeColor(config.snakeColor, -20);

ctx.fillRect(

segment.x * config.gridSize,

segment.y * config.gridSize,

config.gridSize - 2,

config.gridSize - 2

);

});

}

// 颜色渐变函数

function shadeColor(color, percent) {

const num = parseInt(color.replace("#",""),16);

const amt = Math.round(2.55 * percent);

const R = (num >> 16) + amt;

const G = (num >> 8 & 0x00FF) + amt;

const B = (num & 0x0000FF) + amt;

return `#${(1 <<< 24 | (R << 24 | (R < 255 ? R << 24 | (R < 255 ? R < 1 ? 0 : R : 255) << 24 | (R < 255 ? R < 1 ? 0 : R : 255) <<< 24 | (R < 255 ? R < 1 ? 0 : R : 255) << 16 |

(G < 255 ? G < 255 ? G < 1 ? 0 : G : 255) < 255 ? G < 1 ? 0 : G : 255) << 255 ? G < 1 ? 0 : G : 255) << 8 |

(B < 255 ? B < 255 ? B < 1 ? 0 : B : 255)).toString(16).slice(1)}`;

}

// 游戏结束处理

function gameOver() {

clearInterval(gameState.gameLoop);

startBtn.style.display = 'block';

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

}

// 键盘控制

document.addEventListener('keydown', (event) => {

if (!gameState.gameLoop) return;

switch (event.key) {

case 'ArrowUp':

if (gameState.dy !== 1) {

gameState.dx = 0;

gameState.dy = -1;

}

break;

case 'ArrowDown':

if (gameState.dy !== -1) {

gameState.dx = 0;

gameState.dy = 1;

}

break;

case 'ArrowLeft':

if (gameState.dx !== 1) {

gameState.dx = -1;

gameState.dy = 0;

}

break;

case 'ArrowRight':

if (gameState.dx !== -1) {

gameState.dx = 1;

gameState.dy = 0;

}

break;

case ' ':

gameState.isPaused = !gameState.isPaused;

break;

}

});

// 开始游戏按钮

startBtn.addEventListener('click', initGame);

它的思考能力太强了,它能自己找出代码里面的逻辑问题。

Fish AI Reader

Fish AI Reader

AI辅助创作,多种专业模板,深度分析,高质量内容生成。从观点提取到深度思考,FishAI为您提供全方位的创作支持。新版本引入自定义参数,让您的创作更加个性化和精准。

FishAI

FishAI

鱼阅,AI 时代的下一个智能信息助手,助你摆脱信息焦虑

联系邮箱 441953276@qq.com

相关标签

贪吃蛇 Canvas JavaScript 游戏开发
相关文章