使用Trae 生成的React版的贪吃蛇

使用Trae 生成的React版的贪吃蛇

首先你想用这个贪吃蛇,你需要先安装Trae

Trae 官方地址

他有两种模式 chat builder

我使用的是builder模式,虽然是Alpha.还是可以用。

接下来就是按着需求傻瓜式的操作生成代码

他生成的代码不完全正确,比如没有引入Game.jsx文件,需要详细的描述,他在根据描述修改代码。

最后的效果

下面就是游戏核心Game.jsx文件的内容

js 复制代码
import React, { useState, useEffect, useCallback } from 'react';

const Game = () => {
  // 使用useState Hook定义游戏状态
  // useState返回一个数组,第一个元素是当前状态值,第二个元素是更新状态的函数
  const [snake, setSnake] = useState([{ x: 10, y: 10 }]); // 蛇的初始位置和身体
  const [food, setFood] = useState({ x: 5, y: 5 }); // 食物的初始位置
  const [direction, setDirection] = useState('RIGHT'); // 初始移动方向
  const [score, setScore] = useState(0); // 初始分数

  // 使用useCallback Hook生成新食物的位置
  // useCallback用于缓存函数,避免在每次渲染时都创建新的函数实例
  const generateFood = useCallback(() => {
    const newFood = {
      x: Math.floor(Math.random() * 20),
      y: Math.floor(Math.random() * 20)
    };
    setFood(newFood);
  }, []);

  // 使用useCallback Hook检查碰撞
  const checkCollision = useCallback((head) => {
    // 检查是否撞墙
    if (head.x >= 20 || head.x < 0 || head.y >= 20 || head.y < 0) {
      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;
  }, [snake]);

  // 使用useCallback Hook移动蛇
  const moveSnake = useCallback(() => {
    const newSnake = [...snake];
    const head = { ...newSnake[0] };

    // 根据当前方向移动蛇头
    switch (direction) {
      case 'RIGHT':
        head.x += 1;
        break;
      case 'LEFT':
        head.x -= 1;
        break;
      case 'UP':
        head.y -= 1;
        break;
      case 'DOWN':
        head.y += 1;
        break;
      default:
        break;
    }

    // 检查是否发生碰撞
    if (checkCollision(head)) {
      // 游戏结束逻辑
      return;
    }

    newSnake.unshift(head);

    // 检查是否吃到食物
    if (head.x === food.x && head.y === food.y) {
      setScore(score + 1);
      generateFood();
    } else {
      newSnake.pop();
    }

    setSnake(newSnake);
  }, [snake, direction, food, score, checkCollision, generateFood]);

  // 使用useEffect Hook监听键盘事件
  // useEffect用于处理副作用,如添加事件监听器
  useEffect(() => {
    const handleKeyDown = (e) => {
      switch (e.key) {
        case 'ArrowUp':
          if (direction !== 'DOWN') setDirection('UP');
          break;
        case 'ArrowDown':
          if (direction !== 'UP') setDirection('DOWN');
          break;
        case 'ArrowLeft':
          if (direction !== 'RIGHT') setDirection('LEFT');
          break;
        case 'ArrowRight':
          if (direction !== 'LEFT') setDirection('RIGHT');
          break;
        default:
          break;
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [direction]);

  // 使用useEffect Hook实现游戏主循环
  useEffect(() => {
    const gameLoop = setInterval(moveSnake, 200);
    return () => clearInterval(gameLoop);
  }, [moveSnake]);

  // JSX语法:用于描述UI的结构
  return (
    <div>
      <div>Score: {score}</div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(20, 20px)' }}>
        {Array.from({ length: 20 * 20 }).map((_, index) => {
          const x = index % 20;
          const y = Math.floor(index / 20);
          const isSnake = snake.some(segment => segment.x === x && segment.y === y);
          const isFood = food.x === x && food.y === y;

          return (
            <div
              key={index}
              style={{
                width: '20px',
                height: '20px',
                backgroundColor: isSnake ? 'green' : isFood ? 'red' : 'lightgray',
                border: '1px solid gray'
              }}
            />
          );
        })}
      </div>
    </div>
  );
};

export default Game;
相关推荐
万少3 小时前
HarmonyOS 开发必会 5 种 Builder 详解
前端·harmonyos
橙序员小站5 小时前
Agent Skill 是什么?一文讲透 Agent Skill 的设计与实现
前端·后端
炫饭第一名7 小时前
速通Canvas指北🦮——基础入门篇
前端·javascript·程序员
王晓枫8 小时前
flutter接入三方库运行报错:Error running pod install
前端·flutter
符方昊8 小时前
React 19 对比 React 16 新特性解析
前端·react.js
ssshooter8 小时前
又被 Safari 差异坑了:textContent 拿到的值居然没换行?
前端
曲折8 小时前
Cesium-气象要素PNG色斑图叠加
前端·cesium
Forever7_8 小时前
Electron 淘汰!新的桌面端框架 更强大、更轻量化
前端·vue.js
不会敲代码18 小时前
前端组件化样式隔离实战:React CSS Modules、styled-components 与 Vue scoped 对比
css·vue.js·react.js
Angelial8 小时前
Vue3 嵌套路由 KeepAlive:动态缓存与反向配置方案
前端·vue.js