当前位置: 首页 > news >正文

AI4CODE】3 Trae 锤一个贪吃蛇的小游戏

【AI4CODE】目录

【AI4CODE】1 Trae CN 锥安装配置与迁移

【AI4CODE】2 Trae 锤一个 To-Do-List


这次还是采用 HTML/CSS/JAVASCRIPT 技术栈 Trae 锤一个贪吃蛇的小游戏。
在这里插入图片描述

1 环境准备

创建一个 Snake 的子文件夹,清除以前的会话记录。
在这里插入图片描述

2 开始构建

2.1 输入会话提词

比如:

用html/css/javascript技术栈构建一个简洁美观的贪吃蛇小游戏,要求有开始游戏按钮,保存最高得分记录到本地

2.2 思考过程

在这里插入图片描述

2.3 构建过程

在这里插入图片描述
在这里插入图片描述

2.4 Live Server 启动服务试试

画面出来了,开始游戏发现,蛇的移动数据太快了,修改一下移动速度。
在这里插入图片描述
输入提词:蛇的移动数据太快了

了解您希望调整贪吃蛇的移动速度。当前游戏逻辑使用requestAnimationFrame实现循环,可以通过添加移动间隔控制机制来调节速度。建议在update函数中增加时间间隔判断,例如每200毫秒更新一次蛇的位置。同时保留原有动画帧调用以保证画面流畅。这样既能保持画面渲染流畅度,又能独立控制蛇的移动速度。

现在为贪吃蛇游戏添加移动间隔控制机制来降低移动速度。将在game.js中新增lastMoveTime变量和时间间隔判断逻辑,保持画面流畅的同时实现速度控制。

2.5 OK 可以玩了

在这里插入图片描述
蛇的移动移动速度,也可以自己修改 game.js的

const moveInterval = 300;

这里的单位是毫秒。

3 代码贴出来

所有的代码都 Trae 自动锤出来的,我没有写一行代码,共三个代码文件:index.html/game.js/style.css

3.1 Index.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>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <div class="game-container">
    <canvas id="gameCanvas" width="400" height="400"></canvas>
    <div class="control-panel">
      <button id="startBtn" class="game-btn">开始游戏</button>
      <div class="score-board">
        <span>当前得分:<span id="currentScore">0</span></span>
        <span>最高得分:<span id="highScore">0</span></span>
      </div>
    </div>
  </div>
  <script src="game.js"></script>
</body>
</html>

3.2 Style.css

body {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  margin: 0;
  background: #2c3e50;
  font-family: Arial, sans-serif;
}

.game-container {
  position: relative;
  background: #ecf0f1;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 0 20px rgba(0,0,0,0.3);
}

#gameCanvas {
  border: 2px solid #34495e;
}

.control-panel {
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.game-btn {
  padding: 12px 30px;
  font-size: 18px;
  background: #27ae60;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background 0.3s;
}

.game-btn:hover {
  background: #219a52;
}

.score-board {
  margin-top: 15px;
  font-size: 16px;
  color: #2c3e50;
  display: flex;
  gap: 20px;
}

@media (max-width: 480px) {
  #gameCanvas {
    width: 300px;
    height: 300px;
  }
}

3.3 Game.js

const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const startBtn = document.getElementById('startBtn');
const currentScoreSpan = document.getElementById('currentScore');
const highScoreSpan = document.getElementById('highScore');

const gridSize = 20;
let snake = [];
let food = {};
let direction = 'right';
let nextDirection = 'right';
let gameLoop;
let score = 0;
let highScore = localStorage.getItem('snakeHighScore') || 0;

highScoreSpan.textContent = highScore;

function initGame() {
  snake = [{x: 5, y: 5}];
  score = 0;
  currentScoreSpan.textContent = score;
  direction = 'right';
  nextDirection = 'right';
  generateFood();
}

function generateFood() {
  food = {
    x: Math.floor(Math.random() * (canvas.width/gridSize)),
    y: Math.floor(Math.random() * (canvas.height/gridSize))
  };
  // 防止食物生成在蛇身上
  while(snake.some(segment => segment.x === food.x && segment.y === food.y)) {
    food = {
      x: Math.floor(Math.random() * (canvas.width/gridSize)),
      y: Math.floor(Math.random() * (canvas.height/gridSize))
    };
  }
}

function update() {
  const head = {...snake[0]};
  direction = nextDirection;

  switch(direction) {
    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 >= canvas.width/gridSize || 
      head.y < 0 || head.y >= canvas.height/gridSize ||
      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;
    currentScoreSpan.textContent = score;
    generateFood();
  } else {
    snake.pop();
  }
}

function draw() {
  // 清空画布
  ctx.fillStyle = '#ecf0f1';
  ctx.fillRect(0, 0, canvas.width, canvas.height);

  // 绘制蛇
  ctx.fillStyle = '#27ae60';
  snake.forEach(segment => {
    ctx.fillRect(segment.x*gridSize, segment.y*gridSize, gridSize-2, gridSize-2);
  });

  // 绘制食物
  ctx.fillStyle = '#e74c3c';
  ctx.fillRect(food.x*gridSize, food.y*gridSize, gridSize-2, gridSize-2);
}

function gameOver() {
  cancelAnimationFrame(gameLoop);
  startBtn.textContent = '开始游戏';
  if (score > highScore) {
    highScore = score;
    localStorage.setItem('snakeHighScore', highScore);
    highScoreSpan.textContent = highScore;
  }
}

// 事件监听
let lastMoveTime = 0;
const moveInterval = 300;

function animate(timestamp) {
  if (!lastMoveTime) {
    lastMoveTime = timestamp;
  }
  
  const elapsed = timestamp - lastMoveTime;
  
  if (elapsed >= moveInterval) {
    update();
    lastMoveTime = timestamp;
  }
  
  draw();
  gameLoop = requestAnimationFrame(animate);
}

// 修改游戏启动逻辑
startBtn.addEventListener('click', () => {
  if (!gameLoop) {
    initGame();
    startBtn.textContent = '暂停游戏';
    lastMoveTime = 0; // 重置计时器
    gameLoop = requestAnimationFrame(animate);
  } else {
    cancelAnimationFrame(gameLoop);
    gameLoop = null;
    startBtn.textContent = '继续游戏';
  }
});

// 键盘控制
document.addEventListener('keydown', (e) => {
  switch(e.key.toLowerCase()) {
    case 'arrowup':
    case 'w':
      if (direction !== 'down') nextDirection = 'up';
      break;
    case 'arrowdown':
    case 's':
      if (direction !== 'up') nextDirection = 'down';
      break;
    case 'arrowleft':
    case 'a':
      if (direction !== 'right') nextDirection = 'left';
      break;
    case 'arrowright':
    case 'd':
      if (direction !== 'left') nextDirection = 'right';
      break;
  }
});

本文完

相关文章:

  • 三分钟掌握音视频处理 | 在 Rust 中优雅地集成 FFmpeg
  • JavaScript(Web APIs)
  • 插入排序算法
  • SpringBoot整合SpringSecurity实现多表登录
  • tcc编译器教程7 为编译gmake编写Makefile文件
  • Docker基础入门
  • 从百度百科,探秘树莓集团的数字产业版图​
  • 使用SSH密钥连接本地git 和 github
  • 知识库全链路交互逻辑
  • go mod文件 项目版本管理
  • 项目管理软件分类有哪些
  • playWright学习总结
  • 基于django+pytorch(Faster R-CNN)的钢材缺陷识别系统
  • 【机械视觉】C#+VisionPro联合编程———【三、C#操作VisionPro中的工具详解(CogToolBlock ),以及实例】
  • Websocket的基本使用
  • SpringBoot整合Kafka
  • 【一句话经验】ubuntu vi/vim 模式自动设置为paste
  • 网络安全之tcpdump工具
  • Spring Boot3整合Knife4j(4.5.0)
  • 一、docker的安装
  • 邓州网站建设/公司推广
  • 黄色视频做爰网站安全/aso安卓优化
  • 网站建设基础课件/广告推送平台
  • 微信网站可以免费做么/广州百度关键词排名
  • 西安模板建站定制/百度爱采购关键词优化
  • 橙色网站模板/十堰seo排名公司