컨텐츠로 건너뛰기

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

기본적으로 새 /game 경로를 로드하도록 index.tsx 파일을 업데이트해 보겠습니다. 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/components/AppLayout/navitems.tspackages/game-ui/src/hooks/useAppLayout.tsx 파일을 삭제합니다.

게임 페이지

API를 호출하고 게임 구현을 완성할 게임 페이지를 생성해 보겠습니다:

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

축하합니다. 던전 어드벤처 게임을 구축하고 배포했습니다! 🎉🎉🎉