第一次使用Trae AI生成贪食蛇游戏的学思笔记2.webp

试用时间:2025年3月12日

什么是Trae AI

Trae 是字节跳动推出的免费 AI IDE,你可以理解为AI程序员。你提开发需求,它来帮助你从 0 到 1 开发项目。

目前国内已经可以体验了,官网传送门:https://www.trae.com.cn/home

国内支持3个模型:Doubao-1.5-pro、DeepSeek-R1、DeepSeek-V3

试用记录

第1轮对话

我:使用 web 技术栈生成一个贪吃蛇游戏

Trae AI:使用HTML5 Canvas和JavaScript来实现一个经典的贪吃蛇游戏。主要实现以下核心功能:1) 使用Canvas绘制游戏区域和蛇体 2) 通过键盘事件控制蛇的移动方向 3) 随机生成食物并实现碰撞检测 4) 蛇身长度增长机制 5) 得分统计和游戏结束判定。游戏将包含基本的开始/暂停功能,并采用面向对象的方式组织代码结构以提高可维护性。

创建一个基本的index.html文件作为游戏入口,包含Canvas元素和必要的结构。

创建样式文件来美化游戏界面style.css,设置画布和按钮的布局样式。

创建游戏主逻辑文件game.js,实现蛇的移动控制、食物生成和碰撞检测等核心功能。

告诉我执行以下命令,启动本地服务器来运行游戏,方便测试和预览效果。
python -m http.server 8000

第1轮测试结果

蛇的初始速度太快了,瞬间撞墙,游戏结束!

第2轮对话

我:蛇的初始速度太快了

Trae AI:需要调整贪吃蛇的移动速度。当前游戏使用requestAnimationFrame实现连续动画,可以通过添加速度控制变量并改用setTimeout来降低刷新频率。建议在SnakeGame类中增加gameSpeed属性,并在update方法中设置合理的延迟时间。

现在需要在SnakeGame类中添加游戏速度控制参数,并将requestAnimationFrame改为setTimeout来实现速度调节。

第2轮测试结果

点击开始游戏按钮,游戏不会开始。(连蛇和食物都看不到了)

第3轮对话

Trae AI:需要修复开始游戏按钮的点击事件绑定问题。检查SnakeGame类的初始化过程,发现构造函数中缺少对按钮的事件绑定。应该在构造函数中添加document.getElementById('startBtn').addEventListener('click', () => this.toggleGame())来建立按钮与游戏控制逻辑的连接。

在SnakeGame构造函数中添加开始按钮的事件监听器,修复点击事件绑定问题。

第3轮测试结果

可以开始游戏,但是无法使用方向键控制蛇的移动……

第4轮对话

Trae AI:需要修复键盘事件监听缺失问题。检查SnakeGame类构造函数发现未添加键盘事件监听器,应该在初始化时绑定keydown事件到handleKeyPress方法。同时需要确认事件处理函数中的方向键检测逻辑是否被正确执行。

需要在SnakeGame构造函数中添加键盘事件监听器,绑定到handleKeyPress方法。

第4轮测试结果

游戏可以正常运行。

整体使用感受

国内首个 AI IDE,而且现阶段是免费的,必须支持!

但在刚才试用的过程中个人觉得:
1、Trae AI会犯迷糊,比如它第一次生成的代码是可以开始游戏的,但是经过修改后反而不能开始游戏了。
2、Trae AI对需求分析挺到位的,但是在功能实现时感觉缺乏系统性,丢三落四的。

所以,我们一边用一边等着它进化吧!


第一次使用Trae AI生成贪食蛇游戏的学思笔记.jpg

附代码:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>经典贪吃蛇游戏</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="game-container">
        <div class="score-board">得分: <span id="score">0</span></div>
        <canvas id="gameCanvas" width="400" height="400"></canvas>
        <div class="controls">
            <button id="startBtn">开始游戏</button>
            <div class="instructions">使用方向键控制蛇的移动</div>
        </div>
    </div>
    <script src="game.js"></script>
</body>
</html>
body {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    margin: 0;
    background-color: #f0f0f0;
}

.game-container {
    text-align: center;
}

#gameCanvas {
    border: 2px solid #333;
    background-color: #fff;
}

.controls {
    margin-top: 20px;
}

#startBtn {
    padding: 10px 20px;
    font-size: 16px;
    cursor: pointer;
    background-color: #4CAF50;
    color: white;
    border: none;
    border-radius: 5px;
    transition: background-color 0.3s;
}

#startBtn:hover {
    background-color: #45a049;
}

.score-board {
    font-size: 24px;
    margin-bottom: 10px;
    color: #333;
}

.instructions {
    margin-top: 10px;
    color: #666;
}
class SnakeGame {
  constructor() {
    this.canvas = document.getElementById('gameCanvas');
    this.ctx = this.canvas.getContext('2d');
    this.gridSize = 20;
    this.tileCount = this.canvas.width / this.gridSize;
    
    this.snake = {
      x: 10,
      y: 10,
      dx: 1,
      dy: 0,
      cells: [],
      maxCells: 4
    };

    this.food = {
      x: 15,
      y: 15
    };

    this.score = 0;
    this.gameRunning = false;
    this.gameSpeed = 200;
    this.timeoutID = null;

    // 添加开始按钮事件监听
    document.getElementById('startBtn').addEventListener('click', () => this.toggleGame());

    // 添加键盘事件监听
    document.addEventListener('keydown', (e) => this.handleKeyPress(e));
  }

  toggleGame() {
    this.gameRunning = !this.gameRunning;
    if (this.gameRunning) {
      this.timeoutID = setTimeout(() => this.update(), this.gameSpeed);
      document.getElementById('startBtn').textContent = '暂停游戏';
    } else {
      clearTimeout(this.timeoutID);
      document.getElementById('startBtn').textContent = '继续游戏';
    }
  }

  handleKeyPress(e) {
    switch(e.key) {
      case 'ArrowLeft': if (this.snake.dx !== 1) { this.snake.dx = -1; this.snake.dy = 0; } break;
      case 'ArrowRight': if (this.snake.dx !== -1) { this.snake.dx = 1; this.snake.dy = 0; } break;
      case 'ArrowUp': if (this.snake.dy !== 1) { this.snake.dx = 0; this.snake.dy = -1; } break;
      case 'ArrowDown': if (this.snake.dy !== -1) { this.snake.dx = 0; this.snake.dy = 1; } break;
    }
  }

  update() {
    // 移动蛇头
    this.snake.x += this.snake.dx;
    this.snake.y += this.snake.dy;

    // 边界检测
    if (this.snake.x < 0 || this.snake.x >= this.tileCount || 
        this.snake.y < 0 || this.snake.y >= this.tileCount) {
      this.gameOver();
      return;
    }

    // 更新蛇身
    this.snake.cells.unshift({x: this.snake.x, y: this.snake.y});
    if (this.snake.cells.length > this.snake.maxCells) {
      this.snake.cells.pop();
    }

    // 食物碰撞检测
    if (this.snake.x === this.food.x && this.snake.y === this.food.y) {
      this.snake.maxCells++;
      this.score++;
      document.getElementById('score').textContent = this.score;
      this.generateFood();
    }

    // 自碰撞检测
    for (let i = 1; i < this.snake.cells.length; i++) {
      if (this.snake.x === this.snake.cells[i].x && 
          this.snake.y === this.snake.cells[i].y) {
        this.gameOver();
        return;
      }
    }

    // 重绘
    this.ctx.fillStyle = 'white';
    this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);

    // 绘制蛇
    this.ctx.fillStyle = 'green';
    this.snake.cells.forEach((cell, index) => {
      this.ctx.fillRect(
        cell.x * this.gridSize,
        cell.y * this.gridSize,
        this.gridSize - 1,
        this.gridSize - 1
      );
    });

    // 绘制食物
    this.ctx.fillStyle = 'red';
    this.ctx.fillRect(
      this.food.x * this.gridSize,
      this.food.y * this.gridSize,
      this.gridSize - 1,
      this.gridSize - 1
    );

    // 替换最后的requestAnimationFrame
    this.timeoutID = setTimeout(() => this.update(), this.gameSpeed);
  }

  generateFood() {
    this.food.x = Math.floor(Math.random() * this.tileCount);
    this.food.y = Math.floor(Math.random() * this.tileCount);
    // 确保食物不在蛇身上
    this.snake.cells.forEach(cell => {
      if (cell.x === this.food.x && cell.y === this.food.y) {
        this.generateFood();
      }
    });
  }

  gameOver() {
    this.gameRunning = false;
    clearTimeout(this.timeoutID);
    document.getElementById('startBtn').textContent = '重新开始';
    alert(`游戏结束!得分:${this.score}`);
    // 重置游戏状态
    this.snake = {
      x: 10,
      y: 10,
      dx: 1,
      dy: 0,
      cells: [],
      maxCells: 4
    };
    this.score = 0;
    document.getElementById('score').textContent = '0';
    this.ctx.fillStyle = 'white';
    this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
  }
}

// 启动游戏
new SnakeGame();![第一次使用Trae AI生成贪食蛇游戏的学思笔记2.webp](https://darksheep.vip/usr/uploads/2025/03/3175955144.webp)