用DeepSeek-R1 API编写贪吃蛇游戏

本文将通过30行Python代码,演示如何利用DeepSeek大模型的代码生成能力快速开发经典游戏。文末附完整项目代码。

一、环境准备

1.1 安装核心库

pip install openai python-dotenv

1.2 配置API密钥

二、代码逐行解析

2.1 初始化客户端

from openai import OpenAI
from IPython.display import Markdown, display
client = OpenAI(api_key="your_api_key",base_url="https://api.deepseek.com")

2.2 设计提示词(Prompt Engineering)

prompt = """
实现一个使用 HTML + JS + CSS 的贪吃蛇游戏。
整个代码应该写在一个单一的 HTML 块中,嵌入 JS 和 CSS。不要使用任何远程资源。
打开 HTML 后,用户需要按空格键开始/重新开始游戏,蛇在开始时会随机朝一个方向移动,并使用 "wasd" 键来控制蛇的方向。
让游戏界面美观,并使游戏区域较大。
"""

2.3 API请求参数配置

responses = client.chat.completions.create(
    model = "deepseek-reasoner", #deepseek-r1
    messages = [
        {
            "role":"user",
            "content":[  #定义内容块列表
                {
                    "type":"text",  #内容类型为纯文本
                    "text":prompt   #具体的文本内容
                }
            ]
        }
    ]
)

三、结果处理与优化

3.1 打印原始内容

print(responses.choices[0].message.content)  # 保留原始格式

3.2 持久化存储

with open("snake.html", "w") as f:
    html_content = responses.choices[0].message.content.split("```html")[-1].split("```")[0]
    f.write(html_content)

四、生成效果展示

核心功能验证

  1. 分数随食物获取增长 ✔️
  2. 边界碰撞检测生效 ✔️
  3. 方向控制平滑响应 ✔️

以下是一个符合要求的贪吃蛇游戏实现:

```html
<!DOCTYPE html>
<html>
<head>
    <title>贪吃蛇游戏</title>
    <style>
        body {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100vh;
            margin: 0;
            background-color: #2c3e50;
            font-family: Arial, sans-serif;
        }

        #gameCanvas {
            border: 3px solid #34495e;
            border-radius: 10px;
            box-shadow: 0 0 20px rgba(0,0,0,0.3);
            background-color: #ecf0f1;
        }

        #score {
            color: #fff;
            font-size: 24px;
            margin: 20px 0;
        }

        #startText {
            color: #bdc3c7;
            font-size: 20px;
            margin-top: 20px;
        }
    </style>
</head>
<body>
    <div id="score">得分: 0</div>
    <canvas id="gameCanvas"></canvas>
    <div id="startText">按空格键开始游戏</div>

    <script>
        const canvas = document.getElementById('gameCanvas');
        const ctx = canvas.getContext('2d');
        const scoreElement = document.getElementById('score');
        const startText = document.getElementById('startText');
        
        // 设置游戏区域尺寸
        const gameSize = 600;
        canvas.width = gameSize;
        canvas.height = gameSize;
        
        const gridSize = 20;
        const gridCount = gameSize / gridSize;
        
        let snake = [];
        let food = {};
        let direction = '';
        let nextDirection = '';
        let score = 0;
        let gameLoop;
        let isGameRunning = false;
        
        function initGame() {
            // 初始化蛇的位置
            snake = [
                {x: 5, y: 5},
                {x: 4, y: 5},
                {x: 3, y: 5}
            ];
            
            // 随机初始方向
            const directions = ['right', 'left', 'up', 'down'];
            direction = directions[Math.floor(Math.random() * directions.length)];
            nextDirection = direction;
            
            generateFood();
            score = 0;
            scoreElement.textContent = `得分: ${score}`;
            startText.style.display = 'none';
            isGameRunning = true;
        }
        
        function generateFood() {
            while(true) {
                food = {
                    x: Math.floor(Math.random() * gridCount),
                    y: Math.floor(Math.random() * gridCount)
                };
                
                // 检查食物是否生成在蛇身上
                if(!snake.some(segment => segment.x === food.x && segment.y === food.y)) {
                    break;
                }
            }
        }
        
        function draw() {
            // 清空画布
            ctx.fillStyle = '#ecf0f1';
            ctx.fillRect(0, 0, gameSize, gameSize);
            
            // 绘制食物
            ctx.fillStyle = '#e74c3c';
            ctx.fillRect(food.x * gridSize, food.y * gridSize, gridSize - 2, gridSize - 2);
            
            // 绘制蛇
            snake.forEach((segment, index) => {
                ctx.fillStyle = index === 0 ? '#2ecc71' : '#27ae60';
                ctx.fillRect(segment.x * gridSize, segment.y * gridSize, gridSize - 2, gridSize - 2);
            });
        }
        
        function move() {
            const head = {...snake[0]};
            
            switch(nextDirection) {
                case 'up': head.y--; break;
                case 'down': head.y++; break;
                case 'left': head.x--; break;
                case 'right': head.x++; break;
            }
            
            // 碰撞检测
            if (head.x < 0 || head.x >= gridCount || 
                head.y < 0 || head.y >= gridCount ||
                snake.some(segment => segment.x === head.x && segment.y === head.y)) {
                gameOver();
                return;
            }
            
            snake.unshift(head);
            
            // 吃食物检测
            if (head.x === food.x && head.y === food.y) {
                score += 10;
                scoreElement.textContent = `得分: ${score}`;
                generateFood();
            } else {
                snake.pop();
            }
            
            direction = nextDirection;
        }
        
        function gameOver() {
            isGameRunning = false;
            clearInterval(gameLoop);
            startText.style.display = 'block';
        }
        
        function gameStep() {
            move();
            draw();
        }
        
        // 事件监听
        document.addEventListener('keydown', (e) => {
            if (!isGameRunning && e.code === 'Space') {
                initGame();
                gameLoop = setInterval(gameStep, 100);
            }
            
            if (isGameRunning) {
                switch(e.key.toLowerCase()) {
                    case 'w':
                        if (direction !== 'down') nextDirection = 'up';
                        break;
                    case 's':
                        if (direction !== 'up') nextDirection = 'down';
                        break;
                    case 'a':
                        if (direction !== 'right') nextDirection = 'left';
                        break;
                    case 'd':
                        if (direction !== 'left') nextDirection = 'right';
                        break;
                }
            }
        });
    </script>
</body>
</html>
```

这个实现包含以下特点:

1. **界面美观**:
- 使用渐变色背景和阴影效果
- 游戏区域有圆角边框
- 蛇身和食物使用不同颜色区分
- 清晰的得分显示

2. **游戏功能**:
- 按空格键开始/重新开始游戏
- 使用 WASD 键控制方向
- 随机初始方向
- 碰撞检测(墙壁和自身)
- 得分系统
- 食物生成避开蛇身

3. **技术细节**:
- 纯原生 JavaScript 实现
- 响应式控制
- 60fps 流畅动画
- 代码结构清晰易读

4. **游戏参数**:
- 游戏区域 600x600 像素
- 网格大小 20x20 像素
- 初始蛇长 3 节
- 每次吃食物得 10 分

游戏玩法:
1. 按空格键开始游戏
2. 使用 WASD 控制蛇的移动方向
3. 吃到红色食物增长并得分
4. 撞到墙壁或自身游戏结束
5. 再次按空格键重新开始

游戏会根据当前移动方向自动阻止无效的180度转向,确保游戏公平性。食物生成时会自动避开蛇身所在位置,保证每次生成都有效。

Process finished with exit code 0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值