跳转到内容

构建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

在浏览器中打开本地网站,系统将提示登录并按照提示创建新用户。完成后,您将看到基础网站界面:

baseline-website.png

让我们通过创建类型安全路由来展示 @tanstack/react-router 的功能。 为此,在以下位置创建一个空文件:packages/game-ui/src/routes/game/index.tsx。您会注意到文件立即被更新。

@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 文件以默认加载新的 /game 路由。当您更新 to 字段时,系统会提供类型安全的路由选项列表。

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 进行以下修改:

export default {
applicationName: 'Dungeon Adventure',
};

删除未使用的 packages/game-ui/src/hooks/useAppLayout.tsx 文件。

让我们创建一个钩子来初始化与故事代理交互的客户端。

import { useAuth } from 'react-oidc-context';
import { useRuntimeConfig } from './useRuntimeConfig';
import { useMemo } from 'react';
export interface GenerateStoryInput {
playerName: string;
genre: string;
actions: { role: string; content: string }[];
}
export const useStoryAgent = () => {
const { agentArn } = useRuntimeConfig();
const region = agentArn.split(':')[3];
const url = `https://bedrock-agentcore.${region}.amazonaws.com/runtimes/${encodeURIComponent(agentArn)}/invocations?qualifier=DEFAULT`;
const { user } = useAuth();
return useMemo(
() => ({
generateStory: async function* (
opts: GenerateStoryInput,
): AsyncIterableIterator<string> {
const response = await fetch(url, {
headers: {
Authorization: `Bearer ${user?.id_token}`,
'Content-Type': 'application/json',
},
method: 'POST',
body: JSON.stringify(opts),
});
const reader = response.body
?.pipeThrough(new TextDecoderStream())
.getReader();
if (!reader) return;
while (true) {
const { value, done } = await reader.read();
if (done) return;
yield value;
}
},
}),
[url, user?.id_token],
);
};

该钩子:

  • runtime-config.json 获取代理 ARN,
  • 根据 ARN 构建 AgentCore Runtime 调用 URL,
  • 使用已登录用户的 JWT 令牌和随机会话 ID 调用代理,并
  • 返回用于处理流式代理消息块的异步迭代器。

要创建调用 API 并完成游戏实现的游戏页面,请更新 packages/game-ui/src/routes/game 中的以下文件:

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';
type IGameState = Omit<IGame, 'lastUpdated'> & { actions: IAction[] };
export const Route = createFileRoute('/game/')({
component: RouteComponent,
});
// hook to check if a ref is visible on the screen
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]);
// Fetch more games if the last game is visible and there are more games
useEffect(() => {
if (isLastGameVisible && hasNextPage && !isFetchingNextPage) {
fetchNextPage();
}
}, [isFetchingNextPage, hasNextPage, fetchNextPage, isLastGameVisible]);
const playerAlreadyExists = (playerName?: string) => {
return !!games?.find((s) => s.playerName === playerName);
};
// create a new game
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('Failed to start game:', error);
}
};
// load an existing game
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 Dungeon Adventure</h1>
</header>
{/* New Game Section */}
<div className="new-game">
<h2>Start New Game</h2>
<div className="game-setup">
<FormField
errorText={
playerAlreadyExists(playerName)
? `${playerName} already exists`
: undefined
}
>
<input
type="text"
placeholder="Enter your name"
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>
{/* Saved Games Section */}
{games && games.length > 0 && (
<div className="saved-games">
<h2>Continue Game</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

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