使用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;
相关推荐
|晴 天|2 小时前
Vue 3 + TypeScript + Element Plus 博客系统开发总结与思考
前端·vue.js·typescript
猫3283 小时前
v-cloak
前端·javascript·vue.js
旷世奇才李先生3 小时前
Vue 3\+Vite\+Pinia实战:企业级前端项目架构设计
前端·javascript·vue.js
SoaringHeart4 小时前
Flutter进阶:用OverlayEntry 实现所有弹窗效果
前端·flutter
IT_陈寒6 小时前
Vite静态资源加载把我坑惨了
前端·人工智能·后端
herinspace6 小时前
管家婆实用贴-如何分离和附加数据库
开发语言·前端·javascript·数据库·语音识别
小码哥_常7 小时前
从MVC到MVI:一文吃透架构模式进化史
前端
嗷o嗷o7 小时前
Android BLE 的 notify 和 indicate 到底有什么区别
前端
豹哥学前端7 小时前
别再背“var 提升,let/const 不提升”了:揭开暂时性死区的真实面目
前端·面试
lar_slw7 小时前
k8s部署前端项目
前端·容器·kubernetes