Salta ai contenuti

Gioco di Dungeon con IA

Modulo 4: Implementazione dell’interfaccia utente

Per iniziare a costruire l’interfaccia utente, configuriamo il server di sviluppo locale per puntare alla sandbox distribuita. Esegui il seguente comando:

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

Questo comando scaricherà il file runtime-config.json distribuito e lo salverà localmente nella cartella packages/game-ui/public.

Ora avvia il server di sviluppo con:

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

Apri il sito locale nel browser e segui le istruzioni per accedere e creare un nuovo utente. Al termine vedrai il sito base:

baseline-website.png

Crea una nuova route ‘/game’

Mostriamo le capacità di @tanstack/react-router creando una route tipizzata. Crea un file vuoto in packages/game-ui/src/routes/game/index.tsx. Monitora i log del server:

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

Il router ha configurato automaticamente la nuova route. Nota che il file viene popolato con il percorso:

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

Navigando su http://localhost:4200/game vedrai la nuova pagina!

baseline-game.png

Aggiorniamo index.tsx per caricare la route /game di default. Nota come il campo to offra route tipizzate:

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

Elimina la cartella packages/game-ui/src/routes/welcome/ non più necessaria.

Aggiornamenti al layout

Il layout predefinito è più adatto ad applicazioni SaaS che a un gioco. Riconfiguriamolo con un tema dungeon.

Apporta queste modifiche in packages/game-ui/src:

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

Elimina i file packages/game-ui/src/components/AppLayout/navitems.ts e packages/game-ui/src/hooks/useAppLayout.tsx non più utilizzati.

Pagine di gioco

Creiamo le pagine che richiameranno le API e completeranno il gioco:

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 per verificare la visibilità di un elemento
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]);
// Carica più partite se visibili
useEffect(() => {
if (isLastGameVisible && hasNextPage && !isFetchingNextPage) {
fetchNextPage();
}
}, [isFetchingNextPage, hasNextPage, fetchNextPage, isLastGameVisible]);
const playerAlreadyExists = (playerName?: string) => {
return !!games?.find((s) => s.playerName === playerName);
};
// Crea nuova partita
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('Errore creazione partita:', error);
}
};
// Carica partita esistente
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>
{/* Sezione nuova partita */}
<div className="new-game">
<h2>Nuova Partita</h2>
<div className="game-setup">
<FormField
errorText={
playerAlreadyExists(playerName)
? `${playerName} già esistente`
: undefined
}
>
<input
type="text"
placeholder="Inserisci nome"
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>
{/* Partite salvate */}
{games && games.length > 0 && (
<div className="saved-games">
<h2>Continua Partita</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>
);
}

Ora il server locale (http://localhost:4200/) è pronto per giocare!

Puoi anche compilare e distribuire su Cloudfront
game-select.png
game-conversation.png

Complimenti. Hai creato e distribuito il tuo Dungeon Adventure Game! 🎉🎉🎉