在libGDX中保存带有首选项的数据 [英] save data with preferences in libGDX

查看:79
本文介绍了在libGDX中保存带有首选项的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的游戏项目中,我想使用首选项界面保存一些硬币,游戏,...等关卡数据.

In My game project, I want to save some data of levels like coins, gams, ... etc with preferences interface.

我想在这里的我的问题"中,数据仅是级别号. ................................................... ......................

I supposed In My Question here the data is the level number only. ........................................................................

1)如果玩家完成了level_1,则调用此代码来保存LEVEL_NUM_.

1) If the player finish the level_1, this code called to save LEVEL_NUM_.

preferences.putInteger("LEVEL_NUM_", getLevelNum());
preferences.flush();

.prefs的文件:

    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
    <properties>
    <entry key="LEVEL_NUM_">1</entry>
    <entry key="SCORE_">3225</entry>
    </properties>

2)如果玩家完成了level_2,则再次调用此代码以保存LEVEL_NUM_.

2) If the player finish the level_2, this code called again to save LEVEL_NUM_.

preferences.putInteger("LEVEL_NUM_", getLevelNum());
preferences.flush();

首选项会更新数据,即用新的LEVEL_NUM_数据替换LEVEL_NUM_的数据.

The preferences update the data i.e. replace the LEVEL_NUM_'s data with a new LEVEL_NUM_'s data.

新的.prefs文件:

    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
    <properties>
    <entry key="LEVEL_NUM_">2</entry>
    <entry key="SCORE_">5995</entry>
    </properties>

我想添加数据(如堆栈),而不是替换数据.我该怎么办?

I want to add the data (like stack) NOT replace the data. What I do ?

推荐答案

您所需要做的就是将关卡保存在某个集合中(例如Array<>),然后将该集合保存到首选项"中.您将需要将此集合转换为String(没有 putArray()函数或类似的东西),最好的办法是将其JSON化.

all you need is to keep your levels in some collection (like Array<>) and then save this collection to Preferences. You will need to cast this collection to String (there's no putArray() function or something like this) and the best idea is to jsonify it.

JSON 是一种文件格式(类似于xml,但更轻巧),并在libgdx方面提供了良好的支持.实现目标的代码如下:

JSON is a file format (something like xml but much lighter) with good support from libgdx side. The code to achieve your goal is something like:

    FloatArray levels = new FloatArray();
    levels.add(5993);
    levels.add(5995);

    ...

    Preferences p = Gdx.app.getPreferences("SETTINGS");

    Json json = new Json();

    String levelsJson = json.toJson(FloatArray.class, levels);

    p.putString("levels", levelsJson);

现在您已经保存了关卡收藏,而要做的所有事情就是:

now you've got you levels collection saved and all you have to do to get it back is:

    FloatArray levels = json.fromJson(FloatArray.class, p.getString("levels");

关于, Michał

这篇关于在libGDX中保存带有首选项的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆