Minigiochi
Guida all'integrazione dei minigiochi in Pixi’VN, che include best practice, gestione del ciclo di vita e implementazioni di esempio utilizzando PixiJS e React.
IA
Puoi usare il pulsante sopra per creare il tuo minigioco, con l'AI.
Il bello di una storia interattiva rispetto al testo normale è che puoi prenderti una pausa e interagire con minigiochi legati alla storia.
I minigiochi nelle visual novel vengono generalmente avviati durante la narrazione. Per passare dall'UI narrativa all'UI del minigioco, si consiglia di collegare il minigioco a una route (ad es., "/minigame/snake") e navigare verso di essa dalla storia. Maggiori informazioni sono disponibili qui.
Ecco alcuni consigli:
- Usa PixiJS direttamente — sia il pacchetto
pixi.jsstesso, sia il sottomodulo@drincs/pixi-vn/pixi.jsche lo ri-esporta — con componenti comeGraphics,SpriteeText, combinati con Livelli PixiJS per creare un livello separato per il tuo minigioco, gestito in modo indipendente dall'interfaccia principale della visual novel. - Usa gli hotkeys per gestire l'input da tastiera per i controlli del tuo minigioco. Consulta Hotkeys per scoprire come configurarli.
- Si consiglia sempre di non usare PixiJS per costruire l'UI (pulsanti, visualizzazioni del punteggio, messaggi di game over, ...); usa invece un framework come React o Vue.
- Salvare e ripristinare lo stato attuale del minigioco è responsabilità dello sviluppatore.
- Dato che un minigioco è una route a sé stante, un progetto di solito finisce per averne più di uno sotto lo stesso percorso
/minigame(ad es./minigame/snake,/minigame/quiz); usa il routing basato su file di TanStack Router per condividere la logica tra di essi invece di duplicarla in ogni minigioco (vedi sotto). - Avviare un minigioco non è altro che navigare verso la sua route dalla storia; se necessita di un parametro (una difficoltà, un ID livello, ...), passalo tramite la stessa route (vedi sotto).
Dato che un minigioco vive sulla propria route (vedi sopra), avviarlo è semplicemente una navigazione — normalmente
attivata da uno step, usando la funzione navigate già disponibile su
StepLabelProps(
configurato una volta in ogni
template ufficiale):
export const startLabel = newLabel("start", [
({ navigate }) => {
navigate({ to: "/minigame/snake" });
},
]);Quando il minigioco termina, naviga di nuovo verso la route narrativa allo stesso modo — tipicamente dalla
callback onExit passata a useMinigame (vedi sotto), oppure da un pulsante nell'UI di game-over
del minigioco.
Un minigioco è spesso configurabile dalla storia — un livello di difficoltà, un ID livello, un seed, ... Dato che vi si accede navigando verso una route, questi vengono passati esattamente come qualsiasi altro parametro di route, usando TanStack Router: come parametro di ricerca (query string) per valori opzionali/di configurazione, oppure come parametro di percorso quando il valore fa davvero parte dell'identità della route.
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;
}E dallo step che avvia il minigioco, passa il valore allo stesso modo:
export const startLabel = newLabel("start", [
({ navigate }) => {
navigate({ to: "/minigame/snake", search: { difficulty: "hard" } });
},
]);Dato che un minigioco è una route a sé stante, un progetto di solito finisce per averne più di uno sotto lo
stesso percorso /minigame (ad es. /minigame/snake, /minigame/quiz). Con
TanStack Router e il suo
routing basato su file, puoi estrapolare tutto ciò che è condiviso da ogni minigioco
(mettere in pausa la narrazione/audio mentre è aperto, hotkeys comuni, un wrapper HUD condiviso,
...) in un'unica route di layout senza percorso proprio (pathless), src/routes/minigame.tsx, allo stesso
modo in cui i template ufficiali già fanno per /game (src/routes/game.tsx avvolge
ogni schermata /game/* con <Outlet /> ):
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 />;
}Ogni singolo minigioco ha bisogno solo del proprio file sotto src/routes/minigame/, che
TanStack Router trasforma nella route effettiva:
import { createFileRoute } from "@tanstack/react-router";
import SnakeGame from "@/screens/minigames/SnakeGame";
export const Route = createFileRoute("/minigame/snake")({
component: SnakeGame,
});Modelli
useMinigame è un hook personalizzato che ti aiuta a gestire il ciclo di vita di un minigioco, incluso l'avvio, l'aggiornamento e la pulizia delle risorse. È presente in tutti i template.
Ad esempio:
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>
)}
</>
);
}Esempi
Il team di Pixi’VN accoglie con favore nuove proposte e contributi per rendere questa libreria ancora più completa. Sentiti libero di condividere o proporre le tue implementazioni di minigiochi nella chat qui sotto!
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>
</>
);
}