普特莫斯维基 (Purtmars Wikipedia 📖)

Chemdah 开发者文档:数据持久化与生命周期

来自Purtmars Wikipedia —— 普特莫斯维基

目录

数据持久化

很多地方都应用了 DataContainer 容器,但只有 PlayerProfile、Quest 经过数据库,所以需要在存入数据时考量数据类型是否支持持久化储存,例如 ItemStack、Location 便不支持。

persistentDataContainer["item"] = itemStack
persistentDataContainer["location"] = Location(world, 0.0, 0.0, 0.0)

这种写法是完全错误的,尽管它能够通过编译,但是在数据写入数据库时便会发生错误。而我们在开发的过程中,应当使用最保守的基本数据类型。例如整型、浮点数、字符串等。

1 persistentDataContainer["level"] = 10
2 persistentDataContainer["experience"] = Data(15.6)

假如你因操作失误存入了 ink.ptms.chemdah.core.Data 类型,Chemdah 也会为你自动转换,这点不用担心。

数据转换

ink.ptms.chemdah.core.Data 中我们提供了以下开放方法用于转换存入的数据类型。

 1 /**
 2  * 转换为 Integer 基本类型
 3  */
 4 fun toInt(): Int
 5 
 6 /**
 7  * 转换为 Float 基本类型
 8  */
 9 fun toFloat(): Float
10 
11 /**
12  * 转换为 Double 基本类型
13  */
14 fun toDouble(): Double
15 
16 /**
17  * 转换为 Long 基本类型
18  */
19 fun toLong(): Long
20 
21 /**
22  * 转换为 Short 基本类型
23  */
24 fun toShort(): Short
25 
26 /**
27  * 转换为 Byte 基本类型
28  */
29 fun toByte(): Byte
30 
31 /**
32  * 转换为 Boolean 基本类型
33  */
34 fun toBoolean(): Boolean
35 
36 /**
37  * 转换为文本并识别为 InferArea 类型,识别后缓存
38  * 书写格式为 InferArea 无世界单坐标格式(详见区域选择器)
39  */
40 fun toVector(): InferArea
41 
42 /**
43  * 转换为文本并识别为 InferArea 类型,识别后缓存
44  * 书写格式为 InferArea 任何格式(详见区域选择器)
45  */
46 fun toPosition(): InferArea
47 
48 /**
49  * 转换为文本并识别为 InferEntity 类型,识别后缓存
50  * 书写格式为 InferEntity 任何格式(详见实体选择器)
51  */
52 fun toInferEntity(): InferEntity
53 
54 /**
55  * 转换为文本并识别为 InferBlock 类型,识别后缓存
56  * 书写格式为 InferBlock 任何格式(详见实体选择器)
57  */
58 fun toInferBlock(): InferBlock
59 
60 /**
61  * 转换为文本并识别为 InferItem 类型,识别后缓存
62  * 书写格式为 InferItem 任何格式(详见物品选择器)
63  */
64 fun toInferItem(): InferItem

数据生命周期

当 DataContainer 中的数据发生变动时,会被标记为已修改并等待写入数据库。每 100 游戏刻(5000 毫秒)或玩家退出游戏时进行数据检查,将所有已修改的数据写入数据库,并唤起 PlayerEvents.Updated 事件。

为了保证数据同步的有效性,玩家加入游戏时的数据载入默认会延迟 20 游戏刻(1000 毫秒)虽然这个方法已经被证实不安全。