Pular para o conteúdo

Construir a UI

Tarefa 1: Configurar o servidor de desenvolvimento local

Seção intitulada “Tarefa 1: Configurar o servidor de desenvolvimento local”

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

Terminal window
pnpm nx run 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.

Para iniciar o servidor de desenvolvimento, execute o seguinte comando:

Terminal window
pnpm nx serve game-ui

Abra seu site local em um navegador, onde você será solicitado a fazer login e seguir as instruções para criar um novo usuário. Após concluir, você deverá ver o site base:

baseline-website.png

Vamos demonstrar as capacidades do @tanstack/react-router criando uma nova rota tipada. Para fazer isso, crie 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 configura automaticamente sua nova rota e o arquivo que você acabou de criar 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>
}

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

baseline-game.png

Atualize o arquivo index.tsx para carregar nossa nova rota /game por padrão. Quando você atualizar o campo to, terá uma lista de rotas tipadas para escolher.

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

O layout padrão configurado é mais similar a um aplicativo empresarial no estilo SaaS do que a um jogo. Para reconfigurar o layout e retematizá-lo para se parecer mais com um jogo de masmorra, faça as seguintes alterações em packages/game-ui/src:

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

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

Lembre-se que no Módulo 1, usamos o gerador connection para conectar nossa Game UI ao Story Agent. Isso configurou um cliente OpenAPI tipado para interagir com o agente, juntamente com hooks e providers.

O gerador de conexão criou o seguinte para nós:

  • Um componente StoryAgentProvider envolvendo nosso app em main.tsx
  • Um hook useStoryAgent para integração com TanStack Query
  • Um hook useStoryAgentClient para acesso direto ao cliente
  • Tipos TypeScript gerados a partir da especificação OpenAPI do agente

Usaremos o hook useStoryAgentClient em nosso componente de jogo para transmitir respostas de história do agente.

Para 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 fazer 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! 🎉🎉🎉