优秀的编程知识分享平台

网站首页 > 技术文章 正文

使用deepSeek生成一个贪吃蛇游戏_canvas 贪吃蛇

nanyue 2025-09-21 20:05:36 技术文章 2 ℃

效果

源文件

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>

Tags:

最近发表
标签列表