用 DeepSeek API 生成贪吃蛇游戏与扩展
想弄个贪吃蛇玩玩,正好手头有 DeepSeek API,试试让它生成代码。效果还不错,基本能跑。记录一下过程。
准备工作
注册 DeepSeek 拿到 API Key。编辑器 VSCode,浏览器 Chrome,Node.js 16+,项目里装个 axios 用来调 API。
调用 API 生成贪吃蛇代码
一个简单的 POST 请求,prompt 直接告诉它要什么。
const axios = require('axios');
const apiKey = 'your_deepseek_api_key';
const prompt = '使用 HTML5 Canvas 生成一个完整的贪吃蛇游戏网页版,包含键盘控制、食物、碰撞检测、分数显示,所有代码在一个 HTML 文件中。';
axios.post('https://api.deepseek.com/v1/generate', {
prompt: prompt
}, {
headers: {
'Authorization': `Bearer ${apiKey}`
}
}).then(response => {
const gameCode = response.data.choices[0].text; // 假设返回结构
// 将 gameCode 写入文件或直接使用
}).catch(error => {
console.error(error);
});
DeepSeek 会返回一段包含了 HTML、CSS 和 JS 的完整代码。直接保存成 .html 就可以在浏览器打开。
如果自己写,大概会是这样的:
class SnakeGame {
constructor(canvasId) {
this.canvas = document.getElementById(canvasId);
this.ctx = ..();
. = [{ : , : }];
. = .();
}
}


