跳转到内容

AI地牢游戏

模块4:UI实现

要开始构建UI,我们需要将本地开发服务器配置为指向已部署的沙箱环境。运行以下命令:

Terminal window
pnpm nx run @dungeon-adventure/game-ui:load:runtime-config

该命令将拉取已部署的runtime-config.json文件,并将其存储在本地packages/game-ui/public目录中。

现在可以通过以下命令启动开发服务器:

Terminal window
pnpm nx run @dungeon-adventure/game-ui:serve

在浏览器中打开本地网站(http://localhost:4200/)后,系统会提示登录并创建新用户。完成操作后即可看到基础网站:

baseline-website.png

创建新的’/game’路由

通过创建类型安全路由来展示@tanstack/react-router的能力。在指定位置创建空文件:packages/game-ui/src/routes/game/index.tsx,并观察开发服务器日志:

Terminal window
♻️ Regenerating routes...
🟡 Updating /Users/dimecha/dungeon-adventure/packages/game-ui/src/routes/game/index.tsx
🟡 Updating /Users/dimecha/dungeon-adventure/packages/game-ui/src/routeTree.gen.ts
Processed routes in 27ms

@tanstack/react-router已自动配置新路由,创建的文件将包含路由路径:

import { createFileRoute } from '@tanstack/react-router'
export const Route = createFileRoute('/game/')({
component: RouteComponent,
})
function RouteComponent() {
return <div>Hello "/game/"!</div>
}

访问http://localhost:4200/game即可看到新页面已渲染:

baseline-game.png

更新index.tsx文件以默认加载新路由。注意更新to字段时,可选择类型安全路由列表:

packages/game-ui/src/routes/index.tsx
import { createFileRoute, Navigate } from '@tanstack/react-router';
export const Route = createFileRoute('/')({
component: () => <Navigate to="/game" />,
});

最后删除不再需要的packages/game-ui/src/routes/welcome/目录。

布局更新

默认布局更适用于SaaS风格商业应用。我们将重新配置布局和主题,使其符合地牢游戏风格。

packages/game-ui/src进行以下修改:

packages/game-ui/src/config.ts
export default {
applicationName: 'Dungeon Adventure',
};

删除不再使用的packages/game-ui/src/components/AppLayout/navitems.tspackages/game-ui/src/hooks/useAppLayout.tsx文件。

游戏页面

创建调用API的游戏页面以完成游戏实现:

packages/game-ui/src/routes/game/index.tsx
import { FormField, Spinner } from '@cloudscape-design/components';
import { useInfiniteQuery, useMutation } from '@tanstack/react-query';
import { createFileRoute, useNavigate } from '@tanstack/react-router';
import {
createRef,
LegacyRef,
MutableRefObject,
useEffect,
useMemo,
useState,
} from 'react';
import { useGameApi } from '../../hooks/useGameApi';
import { IAction, IGame } from ':dungeon-adventure/game-api-schema';
type IGameState = Omit<IGame, 'lastUpdated'> & { actions: IAction[] };
export const Route = createFileRoute('/game/')({
component: RouteComponent,
});
// 检查元素是否可见的hook
export function useIsVisible(ref: MutableRefObject<any>) {
const [isIntersecting, setIntersecting] = useState(false);
useEffect(() => {
const observer = new IntersectionObserver(([entry]) =>
setIntersecting(entry.isIntersecting),
);
ref.current && observer.observe(ref.current);
return () => {
observer.disconnect();
};
}, [ref]);
return isIntersecting;
}
function RouteComponent() {
const [playerName, setPlayerName] = useState('');
const navigate = useNavigate();
const ref = createRef();
const isLastGameVisible = useIsVisible(ref);
const gameApi = useGameApi();
const saveGameMutation = useMutation(gameApi.games.save.mutationOptions());
const {
data: gamesPages,
fetchNextPage,
hasNextPage,
isFetchingNextPage,
} = useInfiniteQuery(
gameApi.games.query.infiniteQueryOptions(
{ limit: 10 },
{ getNextPageParam: ({ cursor }) => cursor },
),
);
const games = useMemo(() => {
return gamesPages?.pages.flatMap((page) => page.items) || [];
}, [gamesPages]);
// 当最后一个游戏可见时加载更多
useEffect(() => {
if (isLastGameVisible && hasNextPage && !isFetchingNextPage) {
fetchNextPage();
}
}, [isFetchingNextPage, hasNextPage, fetchNextPage, isLastGameVisible]);
const playerAlreadyExists = (playerName?: string) => {
return !!games?.find((s) => s.playerName === playerName);
};
// 创建新游戏
const handleStartGame = async (
playerName: string,
genre: IGameState['genre'],
) => {
if (playerAlreadyExists(playerName)) {
return;
}
try {
await saveGameMutation.mutateAsync({
playerName,
genre,
});
await handleLoadGame(playerName, genre);
} catch (error) {
console.error('创建游戏失败:', error);
}
};
// 加载已有游戏
const handleLoadGame = async (
playerName: string,
genre: IGameState['genre'],
) => {
await navigate({
to: '/game/$playerName',
params: { playerName },
search: { genre },
});
};
return (
<div className="game-interface">
<header className="game-header">
<h1>AI地牢冒险</h1>
</header>
{/* 新游戏区域 */}
<div className="new-game">
<h2>开始新游戏</h2>
<div className="game-setup">
<FormField
errorText={
playerAlreadyExists(playerName)
? `${playerName} 已存在`
: undefined
}
>
<input
type="text"
placeholder="输入角色名称"
className="name-input"
onChange={(e) => setPlayerName(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
const input = e.currentTarget;
handleStartGame(input.value, 'medieval');
}
}}
/>
</FormField>
<div className="genre-grid">
{(['zombie', 'superhero', 'medieval'] as const).map((genre) => (
<button
key={genre}
className="genre-button"
onClick={() => {
const playerName = document.querySelector('input')?.value;
if (playerName) {
handleStartGame(playerName, genre);
}
}}
>
{genre.charAt(0).toUpperCase() + genre.slice(1)}
</button>
))}
</div>
</div>
</div>
{/* 已保存游戏区域 */}
{games && games.length > 0 && (
<div className="saved-games">
<h2>继续游戏</h2>
<div className="game-list">
{games.map((game, idx) => (
<button
key={game.playerName}
ref={
idx === games.length - 1
? (ref as LegacyRef<HTMLButtonElement>)
: undefined
}
onClick={() => handleLoadGame(game.playerName, game.genre)}
className="game-session"
>
<div className="player-name">{game.playerName}</div>
<div className="genre-name">
{game.genre.charAt(0).toUpperCase() + game.genre.slice(1)}
</div>
</button>
))}
{isFetchingNextPage && <Spinner data-style="generating" size="big" />}
</div>
</div>
)}
</div>
);
}

完成修改后,本地开发服务器(http://localhost:4200/)即可运行完整游戏!

也可选择构建并部署代码至Cloudfront
game-select.png
game-conversation.png

恭喜!您已成功构建并部署地牢冒险游戏!🎉🎉🎉