Gallery
Gallery 是一个专门用于视觉小说游戏画廊(图集)的内置服务。它允许您添加、删除和检查项目,并支持序列化/反序列化功能。
Gallery 适合用于管理游戏中的图片收集系统,比如角色立绘、CG图片、背景图片等。
import {Gallery} from "narraleaf-react";
基本用法
创建 Gallery
const gallery = new Gallery<{timestamp: number}>();
scene.action([
gallery.add("item", () => ({
timestamp: Date.now(),
}))
]);
注册服务
要使用 Gallery,您需要在故事中注册它:
story.registerService("gallery", gallery);
注册后,您可以使用游戏上下文访问 Gallery:
const liveGame = useLiveGame();
const gallery = liveGame.story?.getService<Gallery<{timestamp: number}>>("gallery");
if (gallery) {
console.log("图库中的所有项目:", gallery.$getAll());
}
完整示例
const gallery = new Gallery<{timestamp: number, description: string}>();
scene.action([
gallery.add("item1", {
timestamp: Date.now(),
description: "第一个项目"
}),
gallery.add("item2", (ctx) => ({
timestamp: Date.now(),
description: "动态创建的项目"
})),
Condition.If(gallery.has("item1"), [
"项目1已解锁!",
]),
gallery.remove("item1"),
gallery.clear()
]);
链式方法
这些方法需要在 scene.action
中使用,它们会返回操作对象,可以被链式调用。
add
向图库添加一个项目
scene.action([
gallery.add("item", {
timestamp: Date.now(),
description: "项目描述"
})
]);
// 或者使用函数
scene.action([
gallery.add("item", (ctx) => {
return {
timestamp: Date.now(),
description: "动态项目"
};
})
]);
name: string
- 要添加的项目名称metadata: Metadata | ((ctx: ScriptCtx) => Metadata)
- 项目的元数据,可以是对象或返回元数据的函数
remove
从图库中移除一个项目
scene.action([
gallery
.remove("item")
.remove("item2"),
]);
name: string
- 要移除的项目名称
clear
清空图库
scene.action([
gallery.clear()
]);
公共方法
这些以 $
开头的方法会立即执行,不需要在 scene.action
中使用。它们专门用于在游戏运行时直接操作图库数据。
has
检查图库中是否存在某个项目
Condition.If(gallery.has("item"), [
"项目已解锁!",
// ...
])
name: string
- 要检查的项目名称- 返回
Lambda<boolean>
- 返回 true 如果项目存在,否则返回 false
$add
立即向图库添加一个项目
gallery.$add("item", {
timestamp: Date.now(),
description: "立即添加的项目"
});
name: string
- 要添加的项目名称metadata: Metadata
- 项目的元数据
$remove
立即从图库中移除一个项目
gallery.$remove("item");
name: string
- 要移除的项目名称
$clear
立即清空图库
gallery.$clear();
调用此方法后,图库将立即变为空。
$get
获取项目的元数据
const metadata = gallery.$get("item");
console.log(metadata?.timestamp);
name: string
- 要获取元数据的项目名称- 返回
Metadata | undefined
- 项目的元数据
$set
设置项目的元数据
gallery.$set("item", {
timestamp: Date.now(),
description: "更新的描述"
});
name: string
- 要设置元数据的项目名称metadata: Metadata
- 要设置的元数据
$getAll
获取图库中的所有项目
const allItems = gallery.$getAll();
console.log("所有项目:", allItems);
- 返回
Record<string, Metadata>
- 图库中的所有项目
$has
检查图库中是否存在某个项目
if (gallery.$has("item")) {
console.log("项目存在");
}
name: string
- 要检查的项目名称- 返回
boolean
- 如果项目存在返回 true,否则返回 false
类型参数
Metadata
Gallery 接受一个泛型参数 Metadata
,用于定义项目元数据的类型:
// 定义元数据类型
type ItemMetadata = {
timestamp: number;
description: string;
unlocked: boolean;
};
// 创建带有类型约束的 Gallery
const gallery = new Gallery<ItemMetadata>();
// 现在所有方法都会有类型检查
gallery.add("item", {
timestamp: Date.now(),
description: "描述",
unlocked: true
});