小游戏
将小游戏集成到 Pixi’VN 中的指南,包括最佳实践、生命周期管理,以及使用 PixiJS 和 React 的示例实现。
AI
你可以使用上方的按钮,通过 AI 创建你自己的小游戏。
与普通文本相比,交互式故事的魅力在于,你可以稍作休息,与故事相关的小游戏进行互动。
视觉小说中的小游戏通常会在叙事过程中启动。为了在叙事 UI 与小游戏 UI 之间切换,建议将小游戏关联到一个路由(例如 "/minigame/snake"),并从故事中导航至该路由。更多信息请参见此处。
以下是一些提示:
- 直接使用 PixiJS——可以是
pixi.js包本身,也可以是重新导出它的@drincs/pixi-vn/pixi.js子模块——搭配Graphics、Sprite、Text等组件,并结合PixiJS 图层,为你的小游戏创建一个独立于主视觉小说界面进行管理的单独图层。 - 使用快捷键来处理小游戏控制的键盘输入。请参阅Hotkeys了解如何设置它们。
- 始终建议不要使用 PixiJS 来构建 UI(按钮、分数显示、游戏结束提示等);而应使用诸如React或Vue之类的框架。
- 保存和恢复小游戏的当前状态是开发者的责任。
- 由于小游戏本身就是一个路由,一个项目通常最终会在同一个
/minigame路径下拥有不止一个小游戏(例如/minigame/snake、/minigame/quiz);请使用TanStack Router的基于文件的路由机制,在它们之间共享逻辑,而不是在每个小游戏中重复编写(见下文)。 - 启动一个小游戏,无非就是从故事中导航到它的路由;如果它需要参数(例如难度、关卡 ID 等),则通过同一个路由传递该参数(见下文)。
由于小游戏运行在其自己的路由上(见上文),启动它只是一次导航——通常
从某个步骤触发,使用已经可用的 navigate 函数,该函数存在于
StepLabelProps(
已设置一次,用于每个
官方模板中):
export const startLabel = newLabel("start", [
({ navigate }) => {
navigate({ to: "/minigame/snake" });
},
]);当小游戏结束时,以同样的方式导航回叙事路由——通常从传递给
useMinigame 的 onExit 回调(见下文)中触发,或者从小游戏
游戏结束 UI 中的某个按钮触发。
小游戏通常可以通过故事进行配置——例如难度等级、关卡 ID、种子等……由于 它是通过导航到某个路由来访问的,因此这些参数的传递方式与其他任何路由参数完全相同, 即使用TanStack Router:对于可选/配置类的值,将其作为搜索参数(query string,查询字符串); 而当该值确实是路由标识本身的一部分时,则将其作为路径参数。
import { createFileRoute } from "@tanstack/react-router";
export const Route = createFileRoute("/minigame/snake")({
validateSearch: (search: Record<string, unknown>) => ({
difficulty:
search.difficulty === "easy" || search.difficulty === "hard"
? search.difficulty
: "normal",
}),
component: SnakeGame,
});
function SnakeGame() {
const { difficulty } = Route.useSearch();
// e.g. use `difficulty` to change `moveInterval` or scoring
return null;
}而从启动该小游戏的步骤开始,也以同样的方式传递该值:
export const startLabel = newLabel("start", [
({ navigate }) => {
navigate({ to: "/minigame/snake", search: { difficulty: "hard" } });
},
]);由于小游戏本身就是一个路由,一个项目通常最终会在同一个
/minigame 路径下拥有不止一个小游戏(例如 /minigame/snake、/minigame/quiz)。借助
TanStack Router的
基于文件的路由,你可以提取出每个小游戏共有的任何内容
(在小游戏打开期间暂停旁白/音频、通用快捷键、共享的 HUD 包装器等)整合为一个单一的无路径布局路由 src/routes/minigame.tsx,这与
官方模板对 /game 的处理方式相同(src/routes/game.tsx 会用
<Outlet /> 包裹每个 /game/* 屏幕):
import { createFileRoute, Outlet } from "@tanstack/react-router";
export const Route = createFileRoute("/minigame")({
component: MinigameLayout,
});
function MinigameLayout() {
// hooks/providers shared by every minigame go here (e.g. pause narration audio)
return <Outlet />;
}每个独立的小游戏此后只需要在 src/routes/minigame/ 下拥有自己的文件,而
TanStack Router 会将其转换为实际的路由:
import { createFileRoute } from "@tanstack/react-router";
import SnakeGame from "@/screens/minigames/SnakeGame";
export const Route = createFileRoute("/minigame/snake")({
component: SnakeGame,
});模板
useMinigame 是一个自定义 Hook,可帮助你管理小游戏的生命周期,包括启动、更新和清理资源。它包含在所有模板中。
例如:
import { Layer } from "@drincs/pixi-vn";
import { Graphics, Ticker } from "@drincs/pixi-vn/pixi.js";
import { createFileRoute } from "@tanstack/react-router";
import { useCallback, useMemo, useState } from "react";
import { useHotkey } from "@tanstack/react-hotkeys";
import useMinigame from "@/lib/hooks/minigame-hooks";
export const Route = createFileRoute("/minigame/example")({
component: MiniGame,
});
function MiniGame() {
const [displayScore, setDisplayScore] = useState(0);
const [gameOver, setGameOver] = useState(false);
const ticker = useMemo(() => {
const ticker = new Ticker();
const endGame = () => {
ticker.stop();
setGameOver(true);
};
ticker.add(({ deltaMS }) => {
// Update game logic here
});
return ticker;
}, []);
useHotkey(
"ArrowUp",
() => {
// Handle key down events for game controls
},
{ enabled: !gameOver },
);
const game = useCallback(
(layer: Layer) => {
ticker.start();
},
[ticker], // They must not be changed during the game otherwise the game will restart
);
const options = useMemo(
() => ({
onExit() {
ticker.stop();
ticker.destroy();
},
}),
[ticker], // They must not be changed during the game otherwise the game will restart
);
const { loading } = useMinigame(game, options);
return (
<>
<div
style={{
position: "absolute",
top: 10,
left: 10,
color: "white",
fontSize: "24px",
background: "rgba(0,0,0,0.5)",
padding: "5px 10px",
borderRadius: "5px",
}}
>
Score: {displayScore}
</div>
{gameOver && (
<div
style={{
position: "absolute",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
color: "red",
fontSize: "48px",
background: "rgba(0,0,0,0.7)",
padding: "20px 40px",
borderRadius: "10px",
}}
>
GAME OVER
</div>
)}
</>
);
}示例
Pixi’VN 团队欢迎大家提出新的建议并做出贡献,让这个库变得更加完善。欢迎在下方的聊天区分享或提出你的小游戏实现方案!
import { canvas, Layer } from "@drincs/pixi-vn";
import { Graphics, Ticker } from "pixi.js";
import { createFileRoute } from "@tanstack/react-router";
import { useCallback, useMemo, useRef, useState } from "react";
import { useHotkeys } from "@tanstack/react-hotkeys";
import useMinigame from "@/lib/hooks/minigame-hooks";
const gridSize = 20;
const moveInterval = 150;
export const Route = createFileRoute("/minigame/snake")({
component: SnakeGame,
});
function SnakeGame() {
const [displayScore, setDisplayScore] = useState(0);
const [gameOver, setGameOver] = useState(false);
const directionRef = useRef({ x: 1, y: 0 });
const setDirection = (x: number, y: number) => {
if (
(x !== 0 && directionRef.current.x === 0) ||
(y !== 0 && directionRef.current.y === 0)
) {
directionRef.current = { x, y };
}
};
useHotkeys([
{
hotkey: "ArrowUp",
callback: () => setDirection(0, -1),
options: { enabled: !gameOver },
},
{
hotkey: "ArrowDown",
callback: () => setDirection(0, 1),
options: { enabled: !gameOver },
},
{
hotkey: "ArrowLeft",
callback: () => setDirection(-1, 0),
options: { enabled: !gameOver },
},
{
hotkey: "ArrowRight",
callback: () => setDirection(1, 0),
options: { enabled: !gameOver },
},
]);
// Populated by `game(layer)` once the minigame layer is created
const layerRef = useRef<Layer>(null!);
const snakeRef = useRef<Graphics[]>([]);
const appleRef = useRef<Graphics>(null!);
const placeApple = useCallback(() => {
const apple = appleRef.current;
const cols = Math.floor(canvas.width / gridSize);
const rows = Math.floor(canvas.height / gridSize);
apple.x = Math.floor(Math.random() * cols) * gridSize;
apple.y = Math.floor(Math.random() * rows) * gridSize;
// Avoid placing the apple on top of the snake
for (let segment of snakeRef.current) {
if (segment.x === apple.x && segment.y === apple.y) {
placeApple();
return;
}
}
}, []);
const ticker = useMemo(() => {
const ticker = new Ticker();
let elapsed = 0;
const endGame = () => {
ticker.stop();
setGameOver(true);
};
ticker.add(({ deltaMS }) => {
const snake = snakeRef.current;
const apple = appleRef.current;
const head = snake[0];
elapsed += deltaMS;
if (elapsed < moveInterval) return;
elapsed = 0;
// Move the body
for (let i = snake.length - 1; i > 0; i--) {
snake[i].position.set(snake[i - 1].x, snake[i - 1].y);
}
// Move the head
head.x += directionRef.current.x * gridSize;
head.y += directionRef.current.y * gridSize;
// Collision with the wall
if (
head.x < 0 ||
head.y < 0 ||
head.x >= canvas.width ||
head.y >= canvas.height
) {
endGame();
return;
}
// Collision with the body
for (let i = 1; i < snake.length; i++) {
if (head.x === snake[i].x && head.y === snake[i].y) {
endGame();
return;
}
}
// Eat the apple
if (head.x === apple.x && head.y === apple.y) {
const newSegment = new Graphics();
newSegment
.rect(0, 0, gridSize, gridSize)
.fill({ color: 0x00ff00 });
newSegment.position.set(head.x, head.y);
layerRef.current.addChild(newSegment);
snake.push(newSegment);
setDisplayScore((prev) => prev + 1);
placeApple();
}
});
return ticker;
}, [placeApple]);
const game = useCallback(
(layer: Layer) => {
layerRef.current = layer;
const head = new Graphics();
head.rect(0, 0, gridSize, gridSize).fill({ color: 0x00ff00 });
head.x = 200;
head.y = 200;
layer.addChild(head);
snakeRef.current = [head];
const apple = new Graphics();
apple.rect(0, 0, gridSize, gridSize).fill({ color: 0xff0000 });
layer.addChild(apple);
appleRef.current = apple;
placeApple();
ticker.start();
},
[ticker, placeApple], // They must not be changed during the game otherwise the game will restart
);
const options = useMemo(
() => ({
onExit() {
ticker.stop();
ticker.destroy();
},
}),
[ticker],
);
useMinigame(game, options);
return (
<>
<div
style={{
position: "absolute",
top: 10,
left: 10,
color: "white",
fontSize: "24px",
background: "rgba(0,0,0,0.5)",
padding: "5px 10px",
borderRadius: "5px",
}}
>
Score: {displayScore}
</div>
{gameOver && (
<div
style={{
position: "absolute",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
color: "red",
fontSize: "48px",
background: "rgba(0,0,0,0.7)",
padding: "20px 40px",
borderRadius: "10px",
}}
>
GAME OVER
</div>
)}
{/* Direction buttons */}
<div
style={{
position: "absolute",
bottom: 0,
right: 0,
textAlign: "center",
pointerEvents: "auto",
}}
>
<div style={{ marginTop: "10px" }}>
<button
style={{ fontSize: "30px" }}
onClick={() => setDirection(0, -1)}
>
⬆️
</button>
</div>
<div>
<button
style={{ fontSize: "30px", marginRight: "50px" }}
onClick={() => setDirection(-1, 0)}
>
⬅️
</button>
<button
style={{ fontSize: "30px" }}
onClick={() => setDirection(1, 0)}
>
➡️
</button>
</div>
<div>
<button
style={{ fontSize: "30px" }}
onClick={() => setDirection(0, 1)}
>
⬇️
</button>
</div>
</div>
</>
);
}