Pular para o conteúdo

Jogo de Dungeons de IA Agêntica

Para começar a construir a UI, precisamos configurar nosso servidor de desenvolvimento local para apontar para o sandbox implantado. Execute o seguinte comando:

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

Este comando irá baixar o runtime-config.json que está implantado e armazená-lo localmente na pasta packages/game-ui/public.

Agora podemos iniciar o servidor de desenvolvimento com o seguinte comando:

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

Você pode então abrir o site local em um navegador, onde será solicitado que faça login e siga as instruções para criar um novo usuário. Após concluir, você deve ver o site base:

baseline-website.png

Você pode executar

Terminal window
pnpm nx run @dungeon-adventure/game-ui:serve-local
para iniciar também quaisquer servidores de API locais conectados, permitindo que você itere tanto na sua API tRPC quanto no site simultaneamente.

Vamos demonstrar as capacidades do @tanstack/react-router criando uma nova rota tipada. Para isso, basta criar um arquivo vazio no seguinte local: packages/game-ui/src/routes/game/index.tsx. Você notará que o arquivo é atualizado imediatamente.

O @tanstack/react-router já configurou automaticamente sua nova rota e você observará que o arquivo criado já está populado com o caminho da rota:

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

Agora, se você navegar para http://localhost:4200/game, verá que sua nova página foi renderizada!

baseline-game.png

Vamos também atualizar o arquivo index.tsx para carregar nossa nova rota /game por padrão. Observe como, ao atualizar o campo to, você tem uma lista de rotas tipadas para escolher.

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

Finalmente, podemos excluir a pasta packages/game-ui/src/routes/welcome/ pois não é mais necessária.

O layout padrão configurado é mais adequado para aplicativos empresariais no estilo SaaS do que para um jogo. Vamos reconfigurar o layout e retematizá-lo para se assemelhar mais a um jogo de masmorra.

Faça as seguintes alterações em packages/game-ui/src:

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

Agora vamos excluir o arquivo packages/game-ui/src/hooks/useAppLayout.tsx pois não está sendo usado.

Em seguida, criaremos um hook para inicializar um cliente de interação com nosso Agente de História.

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 }[];
}
const generateSessionId = (playerName: string): string => {
const targetLength = 34;
const uuidLength = targetLength - playerName.length;
const randomSegment = crypto
.randomUUID()
.replace(/-/g, '')
.substring(0, uuidLength);
return `${playerName}${randomSegment}`;
};
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',
'X-Amzn-Bedrock-AgentCore-Runtime-Session-Id': generateSessionId(
opts.playerName,
),
},
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;
// Parse SSE format - each chunk may contain multiple events
const lines = value.split('\n');
for (const line of lines) {
// SSE events start with "data: "
if (line.startsWith('data: ')) {
const data = line.slice(6); // Remove "data: " prefix
try {
const parsed = JSON.parse(data);
// Extract text from contentBlockDelta events
if (parsed.event?.contentBlockDelta?.delta?.text) {
yield parsed.event.contentBlockDelta.delta.text;
}
if (parsed.event?.messageStop) {
yield '\n';
}
} catch (e) {
// Skip lines that aren't valid JSON (like Python debug output)
continue;
}
}
}
}
},
}),
[url, user?.id_token],
);
};

Isso faz o seguinte:

  • Recupera o ARN do Agente do runtime-config.json
  • Constrói a URL de invocação do AgentCore Runtime a partir do ARN
  • Invoca o Agente com o token JWT do usuário autenticado e um ID de sessão aleatório
  • Retorna um iterador assíncrono para consumo de chunks de mensagens transmitidas

Você notará que a integração com nossa Game API já está configurada - não precisamos fazer nada manualmente pois usamos o gerador api-connection. Por favor, dê +1 nesta issue do GitHub se desejar uma experiência similar para agentes.

Vamos criar as páginas do jogo que chamarão nossas APIs e finalizarão a implementação do jogo. Atualize os seguintes arquivos em 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>
);
}

Após essas alterações, seu servidor de desenvolvimento local (http://localhost:4200/) deve ter seu jogo pronto para jogar!

Você também pode compilar e implantar seu código no Cloudfront se preferir.
game-select.png
game-conversation.png

Parabéns. Você construiu e implantou seu Jogo de Aventura em Masmorra com Agentes! 🎉🎉🎉