使用Trae 生成的React版的贪吃蛇
首先你想用这个贪吃蛇,你需要先安装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;