简体   繁体   English

如何在JavaFX中保存和加载游戏

[英]How to save and load game in javafx

I'm programming an easy version of blackjack without bets in javafx, and I'm almost done with every part but now I want to be able to save and load my BlackJack game but i have no idea how to do it. 我正在用javafx编程一个简单版本的二十一点而不打赌,我几乎已经完成了每个部分,但是现在我希望能够保存和加载我的BlackJack游戏,但是我不知道该怎么做。 Can I save everything as txt file and then load it or is there any easy way of doing it? 我可以将所有内容另存为txt文件然后加载,还是有任何简便的方法? my game layout 我的游戏布局

Consider a json serializer/deserializer like Google GSON . 考虑一个像Google GSON这样的json序列化器/反序列化器。

Define json structure according to your data model and just serialize and deserialize your game objects to/from json file. 根据您的数据模型定义json结构 ,然后仅将游戏对象序列化和反序列化到json文件或从json文件反序列化。

Example: 例:

class BagOfPrimitives {
  private int value1 = 1;
  private String value2 = "abc";
  private transient int value3 = 3;
  BagOfPrimitives() {
    // no-args constructor
  }
}

// Serialization
BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj);  

// ==> json is {"value1":1,"value2":"abc"}

// Deserialization
BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);
// ==> obj2 is just like obj

You can write to a file using FileOutputStream and read from a file using FileInputStream . 您可以使用FileOutputStream写入文件,并使用FileInputStream从文件读取。 I would use json format and have Jackson do all serialization but that's just me. 我将使用json格式并让Jackson进行所有序列化,但这就是我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM