网站首页 > 技术文章 正文
效果
源文件
deepseek_html_20250823_c571f7.html
源代码
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>贪吃蛇游戏</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Microsoft YaHei', sans-serif;
}
body {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background: linear-gradient(135deg, #1a2a6c, #b21f1f, #fdbb2d);
padding: 20px;
}
.container {
background-color: rgba(255, 255, 255, 0.9);
border-radius: 15px;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
padding: 25px;
text-align: center;
max-width: 500px;
width: 100%;
}
h1 {
color: #2c3e50;
margin-bottom: 15px;
font-size: 2.2rem;
text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
}
.game-info {
display: flex;
justify-content: space-between;
margin-bottom: 15px;
background-color: #f8f9fa;
padding: 10px 15px;
border-radius: 8px;
font-weight: bold;
}
.score, .high-score {
color: #e74c3c;
font-size: 1.2rem;
}
.difficulty {
margin-bottom: 15px;
}
.difficulty label {
margin-right: 10px;
font-weight: bold;
color: #2c3e50;
}
select {
padding: 8px 12px;
border-radius: 5px;
border: 1px solid #ddd;
background-color: white;
font-size: 1rem;
}
.game-container {
position: relative;
margin-bottom: 20px;
}
canvas {
border: 3px solid #2c3e50;
border-radius: 8px;
background-color: #ecf0f1;
display: block;
margin: 0 auto;
}
.controls {
display: flex;
justify-content: center;
gap: 15px;
margin-bottom: 20px;
}
button {
padding: 12px 25px;
border: none;
border-radius: 8px;
font-size: 1rem;
font-weight: bold;
cursor: pointer;
transition: all 0.3s ease;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
#start-btn {
background-color: #2ecc71;
color: white;
}
#start-btn:hover {
background-color: #27ae60;
transform: translateY(-2px);
}
#pause-btn {
background-color: #f39c12;
color: white;
}
#pause-btn:hover {
background-color: #d35400;
transform: translateY(-2px);
}
#restart-btn {
background-color: #e74c3c;
color: white;
}
#restart-btn:hover {
background-color: #c0392b;
transform: translateY(-2px);
}
.instructions {
background-color: #f8f9fa;
padding: 15px;
border-radius: 8px;
text-align: left;
margin-top: 20px;
}
.instructions h2 {
color: #2c3e50;
margin-bottom: 10px;
font-size: 1.2rem;
}
.instructions ul {
list-style-type: none;
padding-left: 20px;
}
.instructions li {
margin-bottom: 8px;
color: #7f8c8d;
}
.game-over {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: rgba(231, 76, 60, 0.9);
color: white;
padding: 20px;
border-radius: 10px;
text-align: center;
display: none;
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
}
@media (max-width: 500px) {
.controls {
flex-direction: column;
}
button {
width: 100%;
}
}
</style>
</head>
<body>
<div class="container">
<h1> 贪吃蛇游戏 </h1>
<div class="game-info">
<div class="score">得分: <span id="score">0</span></div>
<div class="high-score">最高分: <span id="high-score">0</span></div>
</div>
<div class="difficulty">
<label for="difficulty">难度:</label>
<select id="difficulty">
<option value="easy">简单</option>
<option value="medium" selected>中等</option>
<option value="hard">困难</option>
</select>
</div>
<div class="game-container">
<canvas id="game-canvas" width="400" height="400"></canvas>
<div id="game-over" class="game-over">
<h2>游戏结束!</h2>
<p>你的得分: <span id="final-score">0</span></p>
<p>按"重新开始"按钮再玩一次</p>
</div>
</div>
<div class="controls">
<button id="start-btn">开始游戏</button>
<button id="pause-btn">暂停</button>
<button id="restart-btn">重新开始</button>
</div>
<div class="instructions">
<h2>游戏说明:</h2>
<ul>
<li>使用键盘方向键或WASD控制蛇的移动</li>
<li>吃到红色食物可以得分并让蛇变长</li>
<li>撞到墙壁或自己的身体游戏结束</li>
<li>难度越高蛇移动速度越快</li>
</ul>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', () => {
// 获取DOM元素
const canvas = document.getElementById('game-canvas');
const ctx = canvas.getContext('2d');
const scoreElement = document.getElementById('score');
const highScoreElement = document.getElementById('high-score');
const finalScoreElement = document.getElementById('final-score');
const gameOverElement = document.getElementById('game-over');
const startBtn = document.getElementById('start-btn');
const pauseBtn = document.getElementById('pause-btn');
const restartBtn = document.getElementById('restart-btn');
const difficultySelect = document.getElementById('difficulty');
// 游戏配置
const gridSize = 20;
const gridWidth = canvas.width / gridSize;
const gridHeight = canvas.height / gridSize;
// 游戏状态
let snake = [];
let food = {};
let direction = 'right';
let nextDirection = 'right';
let score = 0;
let highScore = localStorage.getItem('snakeHighScore') || 0;
let gameSpeed = 150;
let gameRunning = false;
let gameLoop;
// 初始化最高分
highScoreElement.textContent = highScore;
// 初始化游戏
function initGame() {
snake = [
{x: 5, y: 10},
{x: 4, y: 10},
{x: 3, y: 10}
];
generateFood();
score = 0;
scoreElement.textContent = score;
direction = 'right';
nextDirection = 'right';
gameOverElement.style.display = 'none';
// 根据难度设置速度
switch(difficultySelect.value) {
case 'easy':
gameSpeed = 200;
break;
case 'medium':
gameSpeed = 150;
break;
case 'hard':
gameSpeed = 100;
break;
}
}
// 生成食物
function generateFood() {
food = {
x: Math.floor(Math.random() * gridWidth),
y: Math.floor(Math.random() * gridHeight)
};
// 确保食物不会出现在蛇身上
for (let part of snake) {
if (part.x === food.x && part.y === food.y) {
return generateFood();
}
}
}
// 绘制游戏
function draw() {
// 清空画布
ctx.fillStyle = '#ecf0f1';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// 绘制蛇
snake.forEach((part, index) => {
ctx.fillStyle = index === 0 ? '#2ecc71' : '#27ae60';
ctx.fillRect(part.x * gridSize, part.y * gridSize, gridSize - 1, gridSize - 1);
// 绘制蛇眼睛
if (index === 0) {
ctx.fillStyle = 'white';
// 根据方向绘制眼睛
if (direction === 'right') {
ctx.fillRect(part.x * gridSize + 13, part.y * gridSize + 5, 4, 4);
ctx.fillRect(part.x * gridSize + 13, part.y * gridSize + 11, 4, 4);
} else if (direction === 'left') {
ctx.fillRect(part.x * gridSize + 3, part.y * gridSize + 5, 4, 4);
ctx.fillRect(part.x * gridSize + 3, part.y * gridSize + 11, 4, 4);
} else if (direction === 'up') {
ctx.fillRect(part.x * gridSize + 5, part.y * gridSize + 3, 4, 4);
ctx.fillRect(part.x * gridSize + 11, part.y * gridSize + 3, 4, 4);
} else if (direction === 'down') {
ctx.fillRect(part.x * gridSize + 5, part.y * gridSize + 13, 4, 4);
ctx.fillRect(part.x * gridSize + 11, part.y * gridSize + 13, 4, 4);
}
}
});
// 绘制食物
ctx.fillStyle = '#e74c3c';
ctx.beginPath();
ctx.arc(food.x * gridSize + gridSize/2, food.y * gridSize + gridSize/2, gridSize/2 - 2, 0, Math.PI * 2);
ctx.fill();
}
// 移动蛇
function moveSnake() {
direction = nextDirection;
// 获取蛇头
const head = {...snake[0]};
// 根据方向移动蛇头
switch(direction) {
case 'right':
head.x++;
break;
case 'left':
head.x--;
break;
case 'up':
head.y--;
break;
case 'down':
head.y++;
break;
}
// 检查是否吃到食物
if (head.x === food.x && head.y === food.y) {
score++;
scoreElement.textContent = score;
if (score > highScore) {
highScore = score;
highScoreElement.textContent = highScore;
localStorage.setItem('snakeHighScore', highScore);
}
generateFood();
} else {
// 如果没吃到食物,移除蛇尾
snake.pop();
}
// 添加新的蛇头
snake.unshift(head);
// 检查游戏是否结束
if (checkCollision()) {
gameOver();
}
}
// 检查碰撞
function checkCollision() {
const head = snake[0];
// 检查是否撞墙
if (head.x < 0 || head.x >= gridWidth || head.y < 0 || head.y >= gridHeight) {
return true;
}
// 检查是否撞到自己
for (let i = 1; i < snake.length; i++) {
if (head.x === snake[i].x && head.y === snake[i].y) {
return true;
}
}
return false;
}
// 游戏结束
function gameOver() {
clearInterval(gameLoop);
gameRunning = false;
finalScoreElement.textContent = score;
gameOverElement.style.display = 'block';
}
// 游戏主循环
function runGame() {
moveSnake();
draw();
}
// 开始游戏
function startGame() {
if (!gameRunning) {
gameRunning = true;
gameLoop = setInterval(runGame, gameSpeed);
}
}
// 暂停游戏
function pauseGame() {
if (gameRunning) {
clearInterval(gameLoop);
gameRunning = false;
} else {
startGame();
}
}
// 重新开始游戏
function restartGame() {
clearInterval(gameLoop);
initGame();
draw();
gameRunning = false;
}
// 键盘控制
document.addEventListener('keydown', (e) => {
switch(e.key) {
case 'ArrowUp':
case 'w':
case 'W':
if (direction !== 'down') nextDirection = 'up';
break;
case 'ArrowDown':
case 's':
case 'S':
if (direction !== 'up') nextDirection = 'down';
break;
case 'ArrowLeft':
case 'a':
case 'A':
if (direction !== 'right') nextDirection = 'left';
break;
case 'ArrowRight':
case 'd':
case 'D':
if (direction !== 'left') nextDirection = 'right';
break;
case ' ':
if (gameRunning) {
pauseGame();
} else {
startGame();
}
break;
}
});
// 按钮事件监听
startBtn.addEventListener('click', startGame);
pauseBtn.addEventListener('click', pauseGame);
restartBtn.addEventListener('click', restartGame);
difficultySelect.addEventListener('change', restartGame);
// 初始化并绘制游戏
initGame();
draw();
});
</script>
</body>
</html>
猜你喜欢
- 2025-09-21 提升档次的CSS伪元素技巧!原来::before和::after还能这么玩
- 2025-09-21 深入理解CSS变量(Custom Properties)
- 2025-09-21 PLC 数据采集 + MySQL 存储 + Flask+ECharts 可视化系统
- 2025-09-21 CSS 电梯:纯 CSS 实现的状态机与楼层导航
- 2025-09-21 操作系统应用开发(四)压缩软件开发demo——东方仙盟筑基期
- 2025-09-21 前端学习核心_黑马程序员vue全套视频教程从vue2 0到vue3 0一套全覆盖前端学习核心框架教程
- 2025-09-21 操作系统应用开发(七)mac苹果模拟器——东方仙盟练气期
- 2025-09-21 uniapp里小程序自定义tabbar,实现中间item凸起效果
- 2025-09-21 档案系统(一)学员管理系统开发——东方仙盟筑基期
- 2024-08-05 用多了各种组件库的你还会用原生JS写轮播图吗?
- 最近发表
- 标签列表
-
- cmd/c (90)
- c++中::是什么意思 (84)
- 标签用于 (71)
- 主键只能有一个吗 (77)
- c#console.writeline不显示 (95)
- pythoncase语句 (88)
- es6includes (74)
- sqlset (76)
- apt-getinstall-y (100)
- node_modules怎么生成 (87)
- chromepost (71)
- flexdirection (73)
- c++int转char (80)
- mysqlany_value (79)
- static函数和普通函数 (84)
- el-date-picker开始日期早于结束日期 (76)
- js判断是否是json字符串 (75)
- c语言min函数头文件 (77)
- asynccallback (87)
- localstorage.removeitem (74)
- vector线程安全吗 (70)
- java (73)
- js数组插入 (83)
- mac安装java (72)
- 无效的列索引 (74)