MV Can I save data in a file?

I'm running in a problem, quite a large one...

For a football manager I generate many, many football players. Actually thousands of them. And generating them goes so fast, you won't even notice.

All that info is saved in one large array, which is stored in a variable.

All good so far, but... When I save the game, it takes seconds. The file is over 700kb, and then I didn't even store all the other info yet.

My main concern in the seconds delay when saving.

Is there a way I can save those arrays in an extern file? Like the actor data and weapon data is stored in a .json file? And if so, can I read and overwrite those arrays halfway the game?
depends how exactly the array is created.
it shouldn't take that long to save long, but 700k kb is not that big
if you ask me if you save the array.

maybe you should just save the teams currently selected to keep
it lower instead of using everything in 1 array.

example would be, 1 array per team,
and another that hold the setup, and this array would be saved into
the savefile.
Some ideas:
  1. If it's meant to be the same for all playthroughs, then saving/loading it to/from a new "global" file would make sense.

  2. If it's initialised on a per-playthrough basis, but remains (almost) constant throughout a playthrough, then saving it to a new "per-slot" file could help. If it changes frequently, though, then I doubt that approach would help much.

  3. If only specific values change during a playthrough, then you may be able to minimise the representation in save data. For example, the party inventory saves as pairs of integers, representing item ID and quantity of that item; the actual item properties etc (constant) are read from the database.
depends how exactly the array is created.
it shouldn't take that long to save long, but 700k kb is not that big
if you ask me if you save the array.

maybe you should just save the teams currently selected to keep
it lower instead of using everything in 1 array.

example would be, 1 array per team,
and another that hold the setup, and this array would be saved into
the savefile.
Actually I have arrays per team, they are collected in a larger array. So when I need the name of player 3 in team 7, I can do: playerArray[7][3].name where playerArray is the game variable.

You say 700kb is not much? I believe you if you say so, but if I compare to my other games, they are somewhere between 30kb and 70kb. I don't know if that is normal for games.

Some ideas:
  1. If it's meant to be the same for all playthroughs, then saving/loading it to/from a new "global" file would make sense.

  2. If it's initialised on a per-playthrough basis, but remains (almost) constant throughout a playthrough, then saving it to a new "per-slot" file could help. If it changes frequently, though, then I doubt that approach would help much.

  3. If only specific values change during a playthrough, then you may be able to minimise the representation in save data. For example, the party inventory saves as pairs of integers, representing item ID and quantity of that item; the actual item properties etc (constant) are read from the database.

Hmmm... Actually, all values are being altered trough-out the game. Only names stay the same.

Stats can be improved by training, or lose some level because of age or injury. The count of goals, red-card, yellow-cards, penalties etc. are also part of this. This is about 30 stats per player, if I count skills, traits, positions, statistics and basic info.

So, pretty much everything is liquid. Everything potentially changes after a team plays a match. So I'm afraid I will need to keep saving it in a variable.

I have also stats that change only once per season, for which that "saving it to a new per-slot file" sounds useful. Is that easy to create? I did a quick google search (real quick) but doubt I can figure that one out in a single sit with the modzilla page. 😛 (Which is normally my first go to when I want to try something new.)



Anyhow, I just realized something... When my players are generated, they get a level for all the skills, traits, and positions. And for each skill value, there is a translation, like '\\c[01]disastrous' and '\\c[09]amazing'

Those translations are also saved into that array, so when I need it, I could just use 'playerArray[1][3].tackle' and I get the word that fits the tackle level of player 3 in team 1, color code included.

I can take that out of the array, and instead generate the names for the levels when needed.
This should save at least half the size of the save file.

It is going to take some time to adjust the plugin, but I see this is something I have to do, no matter if I save it in an extra file or in a variable.
Maybe it is because the game compresses the save file so it needs some time to do.
There are lots of games that take time to save so I dont think that is a big problem.
Maybe it is because the game compresses the save file so it needs some time to do.
There are lots of games that take time to save so I dont think that is a big problem.
Yeah, that is true. I just hoped to sneakily save after each move without the player noticing. 😛 I've dont that with pretty much every game, even where you catch many chick per second and it saves per caught chick, running in a browser, smooth as a criminal. 😛

But, yeah, I am afraid I have to accept the fact saving takes up a moment or two. I'd just have to limit autosaving to once per match or something.

The thing is, I want to avoid players pressing F5, in the 89th minute, when then are about to lose the game. Everyone can be a champion if you can just replay your games till you win. 😛
Just an idea, but in my opinion those players have static and dynamic data... just like actors, right?
So why don't you make a "Player.json" file that would be read in a $dataPlayers variable and that contains all the static data (what will not change between two playthrough), and a $gamePlayers variable with their dynamic data - the consequences of the player's choices and random events - and only a reference to their static data structure.

You would have to replicate a bit of the Actor classes logic.
For example the name of the player could be $gamePlayers[x].player().name

The $dataPlayers array would be the biggest one and has no need to be saved, only $gamePlayers should be added to saves - if it is done correctly.

Just my 2 cents.
Actually it is a very good idea I think.
Just let the generated data piggyback another json so you don't have to write another function to load them.
But you need to be caureful if you open it in the editor the data maybe changed due to the size limit of the textbox.
Or you can save the json string inside a common event and load it by running the event, which looks more natural.
Edit* Though it can only work on pc, not web browsers.
ou say 700kb is not much? I believe you if you say so, but if I compare to my other games, they are somewhere between 30kb and 70kb. I don't know if that is normal for games.
some games I do has file size of 30kb-60kb but goes up to 4MB the further
you go in the game of the items you collect, so it can increase slowly of all
the data.

it's also part of "what data" is being saved, as if you don't save anything, the
size are relative small most of the time.

but there are options to save and extract data when required and possible to
keep the save file lower and call them on loading the save file.

I don't mind if loading takes 5-10 seconds, as some games it's more than that
because of the big size map, so it's worth the wait if it does what it needs to do.
Just an idea, but in my opinion those players have static and dynamic data... just like actors, right?
So why don't you make a "Player.json" file that would be read in a $dataPlayers variable and that contains all the static data (what will not change between two playthrough), and a $gamePlayers variable with their dynamic data - the consequences of the player's choices and random events - and only a reference to their static data structure.

You would have to replicate a bit of the Actor classes logic.
For example the name of the player could be $gamePlayers[x].player().name

The $dataPlayers array would be the biggest one and has no need to be saved, only $gamePlayers should be added to saves - if it is done correctly.

Just my 2 cents.
The name is the only data that will never change. A skills can be trained, al traits can be learned and statistics change all the time as well.

I would love to know how to make a json file for static data, but there is hardly no static data in my game. Even the starter data isn't pre-programmed, but generated at the start of the game.

I've been thinking about making player data variable and opponent data static, but that would take away 90% of the dynamics of the game. The weakest opponent will always be the weakest and the strongest will always be the strongest. It would make it impossible to have red-cards and injuries for opponent teams, or to improve them by training, or lose stats because of age.

So, yeah, I'd love to learn how to use a Json fine the way you described, but but for this problem, I need to be able to edit the files.
What you describe sounds like what I am looking for, if it means I can (occasionally) save data in there.

Then the game can be saved normally on action, to keep the actions played, but it doesn't need to save the whole database over and over again. I'd still have to save the database after each match, but that is acceptable. At least if it is possible.

Actually it is a very good idea I think.
Just let the generated data piggyback another json so you don't have to write another function to load them.
But you need to be caureful if you open it in the editor the data maybe changed due to the size limit of the textbox.
Or you can save the json string inside a common event and load it by running the event, which looks more natural.
Edit* Though it can only work on pc, not web browsers.
No, I save and generate the array in the plugin itself, outside RPGmaker. The plugin generates a large array, with all that data in there, and then that whole array is loaded into the gameVariable. I don't use a common event or anything, just a single plugin command.
I don't have to worry about textbox sizes. The generation and storage of the arrays don't use any textboxes at all.

Mayb I don't understand you right... What do you mean by saving the json string in a common event?

some games I do has file size of 30kb-60kb but goes up to 4MB the further
you go in the game of the items you collect, so it can increase slowly of all
the data.

it's also part of "what data" is being saved, as if you don't save anything, the
size are relative small most of the time.

but there are options to save and extract data when required and possible to
keep the save file lower and call them on loading the save file.

I don't mind if loading takes 5-10 seconds, as some games it's more than that
because of the big size map, so it's worth the wait if it does what it needs to do.
5 to 10 seconds? Yikes! And I was worried about 1 or 2 seconds! 😛 hahaha. Well, a few seconds saving time isn't a problem, but then saves have to be timed when possible, like on a transfer, or after a battle. If I want to generate +/- 30~45 action per match, and it needs to save for seconds after every action, it gets a bet more annoying.

So what I basically would want, is a quick save and a full save, or something. 😛 But that seems way out of my league. But that is what I try to achieve with saving the large array outside the actual saving file. 😛
I don't mind it its 1-2 seconds, to load, as long it doesn't mess the game up while saving 😛
so don't worry to much for now 🙂

if it's become way to much, there is always room to improve it when required ^^
The name is the only data that will never change. A skills can be trained, al traits can be learned and statistics change all the time as well.

I would love to know how to make a json file for static data, but there is hardly no static data in my game. Even the starter data isn't pre-programmed, but generated at the start of the game.

I've been thinking about making player data variable and opponent data static, but that would take away 90% of the dynamics of the game. The weakest opponent will always be the weakest and the strongest will always be the strongest. It would make it impossible to have red-cards and injuries for opponent teams, or to improve them by training, or lose stats because of age.

So, yeah, I'd love to learn how to use a Json fine the way you described, but but for this problem, I need to be able to edit the files.
What you describe sounds like what I am looking for, if it means I can (occasionally) save data in there.

Then the game can be saved normally on action, to keep the actions played, but it doesn't need to save the whole database over and over again. I'd still have to save the database after each match, but that is acceptable. At least if it is possible.

If everything is dynamic then my idea cannot be applied indeed.
By the way, json is a format useful to read/import data into a game, but I would not use it so save anything.
To save any data externally from a save file I'd use something like "StorageManager.saveObject" (at least this is the name of the method I use in MZ, I don't know if it is the same in MV ).
It adds a layer of compression.

From what I read about your project, it's just like having a game with a couple thousand actors.
I don't think it's enough to justify breaking the save into two pieces (which would also make the players curious to see what happens if they manually put this file from a "successful save" into this new save).
I don't mind it its 1-2 seconds, to load, as long it doesn't mess the game up while saving 😛
so don't worry to much for now 🙂

if it's become way to much, there is always room to improve it when required ^^
I think you misunderstood the problem...

What I want to do, is make an autosave, when a player scores, or passes, or kicks the ball out, or get a red card. So, the player of my game can't press F5, as soon some something bad happens.
Those actions in between, to save, are actually during an active moment of the game, when a lot is going on. So, if I want to indeed save in between actions, then it is required already. 😛 See, when the match is simulated, it will show action, after action, after action. It would be super annoying if there was a 2 second delay after every action.

The easiest and safest way for me, would be to only do a full safe after the match. That would work, but players would be able to reload constantly just to get the best possible result. A method that will 100% work, but also ruins the whole game. So to prevent people glitching trough the game, ass if it was fallout, I would love to see if I can get one of the previous methods to work.

I'm going to need a bit more help to do that though. I have no idea where to start, what to do in the middle and how to finalize it. (So basically I have no clue at all). 😛

My nephew actually went to school to be a programmer. He might be able to teach me this when he comes over. That is probably easier when we're physically on the same computer and he can exactly show me what he does and how he does it. 😛

If everything is dynamic then my idea cannot be applied indeed.
By the way, json is a format useful to read/import data into a game, but I would not use it so save anything.
To save any data externally from a save file I'd use something like "StorageManager.saveObject" (at least this is the name of the method I use in MZ, I don't know if it is the same in MV ).
It adds a layer of compression.
Just assume I never actually learned javascript... 😛 Could you show me how that works, maybe with an example?

From what I read about your project, it's just like having a game with a couple thousand actors.
I don't think it's enough to justify breaking the save into two pieces (which would also make the players curious to see what happens if they manually put this file from a "successful save" into this new save).
I didn't think breaking it into 2 saves would even be a possibility. I just hoped I could make something just like actors.json, but then while I was able to change the input.
Just assume I never actually learned javascript... 😛 Could you show me how that works, maybe with an example?

Something you can do in MZ:

You can save an object using something like this :

Code:
let data = { "randomArray" : [1,2,3,4,5,6,7] };
StorageManager.saveObject("Test",data);

It will create a file called "Test.rmmzsave" containing this data.

You can read it back with this:

Code:
let temp = StorageManager.loadObject("Test");
temp.then(function(data_loaded)
{
    console.log(data_loaded.randomArray);
}).catch(function(e){});

This code is untested (I'm at work with no acess to MZ here ^^) but that's the idea.

Remember that as I said, I don't think it's a good idea to cut a save file into different parts. I would only externalize data that is relevant for all the saves (such as unlocked achievements).
@TG22 - MV's save/load operations are synchronous/blocking. Save data is stringified to JSON, compressed to base 64, then written to file. (Similar in MZ, except it's async and the result is also zipped before being written to file.)

I have also stats that change only once per season, for which that "saving it to a new per-slot file" sounds useful. Is that easy to create?
For MV, I think you could do something like this (untested):
Spoiler: plugin code
JavaScript:
;void (function() {
'use strict';

  /** Regular expression to extract slot ID from `savefileId`. */
  const RX = /JDN_(\d+)/;  // e.g. "JDN_1" for slot 1.

  /** New save file name. `%1` = slot ID. */
  const SAVE_NAME = "jdn_data%1.rpgsave";

  /**
   * @param {any} value Input value.
   * @returns {?number} Corresponding slot ID, or `null` if not one of these "extra" files.
   */
  const extractId = function(value) {
    if (typeof value === "string") {
      const match = RX.exec(value);
      if (match)
        return parseInt(match[1], 10);
    }
    return null;
  };

  // Patch - map custom ID (`"JDN_%1"`) to custom file name.
  void (function() {
    const alias = StorageManager.localFilePath;
    StorageManager.localFilePath = function(savefileId) {
      const id = extractId(savefileId);
      if (id)
        return SAVE_NAME.format(id);
      return alias.apply(this, arguments);
    };
  })();

})();
Then to save/load, use the usual script calls but with a string "save ID" instead of an integer. E.g.
JavaScript:
$gameSystem.onBeforeSave();
if (DataManager.save("JDN_1")) {
  DataManager.cleanBackup("JDN_1");
}

[Edit: oh wow I made a lot of mistakes here! 😅 See my follow-up post.]​

@TG22 - MV's save/load operations are synchronous/blocking. Save data is stringified to JSON, compressed to base 64, then written to file. (Similar in MZ, except it's async and the result is also zipped before being written to file.)

The changes between MV and MZ are quite impressive, but I feel that these synchronous methods would have made my life easier with my game 😅
I have an option to disable F5, the same thing you could do with X so only menu => end game
could work.

outside those, with some HTML knowledge, you could disable context menu from the window
icon to exit it there, but processing part is abort program.

saving by goal is easy way to continue, but you could save this else way, so whenever
you load the game, that data is fetched, see it as a global variable that are pesistent.

even if they close the game, the data is still there, but in a different save, delete those
and the save data would be corrupt 😛
This is way above my pay grade. 😛

@TG22 - MV's save/load operations are synchronous/blocking. Save data is stringified to JSON, compressed to base 64, then written to file. (Similar in MZ, except it's async and the result is also zipped before being written to file.)


For MV, I think you could do something like this (untested):
Spoiler: plugin code
JavaScript:
;void (function() {
'use strict';

  /** Regular expression to extract slot ID from `savefileId`. */
  const RX = /JDN_(\d+)/;  // e.g. "JDN_1" for slot 1.

  /** New save file name. `%1` = slot ID. */
  const SAVE_NAME = "jdn_data%1.rpgsave";

  /**
   * @param {any} value Input value.
   * @returns {?number} Corresponding slot ID, or `null` if not one of these "extra" files.
   */
  const extractId = function(value) {
    if (typeof value === "string") {
      const match = RX.exec(value);
      if (match)
        return parseInt(match[1], 10);
    }
    return null;
  };

  // Patch - map custom ID (`"JDN_%1"`) to custom file name.
  void (function() {
    const alias = StorageManager.localFilePath;
    StorageManager.localFilePath = function(savefileId) {
      const id = extractId(savefileId);
      if (id)
        return SAVE_NAME.format(id);
      return alias.apply(this, arguments);
    };
  })();

})();
Then to save/load, use the usual script calls but with a string "save ID" instead of an integer. E.g.
JavaScript:
$gameSystem.onBeforeSave();
if (DataManager.save("JDN_1")) {
  DataManager.cleanBackup("JDN_1");
}
I really need to take the weekend to study this before I understand any of it. 😛 I kinda understand the little script call in the end, which seems to make a save file under a new name. But I fail to understand where I can decide what to store there and how to read it out. 😛

I'll have a good look at the whole script in the weekend, when I can take my time to look things up and experiment.
Thanks so far, though. I might not understand it yet, but I am confident this is going to work. 🙂

Uhm... Did you just say save files in MZ auto zipped before written? That's annoying. 😛

Something you can do in MZ:

You can save an object using something like this :

Code:
let data = { "randomArray" : [1,2,3,4,5,6,7] };
StorageManager.saveObject("Test",data);

It will create a file called "Test.rmmzsave" containing this data.

You can read it back with this:

Code:
let temp = StorageManager.loadObject("Test");
temp.then(function(data_loaded)
{
    console.log(data_loaded.randomArray);
}).catch(function(e){});

This code is untested (I'm at work with no acess to MZ here ^^) but that's the idea.

Remember that as I said, I don't think it's a good idea to cut a save file into different parts. I would only externalize data that is relevant for all the saves (such as unlocked achievements).

Thanks. This I kinda understand. I am not sure if this will work in MV as well, but there is a way to find that out. I'm going to experiment with this in the weekend too.

I have an option to disable F5, the same thing you could do with X so only menu => end game
could work.

outside those, with some HTML knowledge, you could disable context menu from the window
icon to exit it there, but processing part is abort program.

saving by goal is easy way to continue, but you could save this else way, so whenever
you load the game, that data is fetched, see it as a global variable that are pesistent.

even if they close the game, the data is still there, but in a different save, delete those
and the save data would be corrupt 😛
I'm not sure I understand how you'd do that. You make it sound to simple. 😛



I have re-arranged the info is stored and shown in the plugin commands.

pId = Player ID
tId = Team ID
playerArray = $gameVariable.value(x)

Before:
The database would have 2 entries for all kills: The numeric value with a bunch of decimals, + the text, which is a copy of an element from an another array and includes color code, like this: '\\c[5]average' for a skill with level 5.0000 ~ 5.9999. When using the skill in text, I only needed to do playerArray[tId][pId].tackle to get the right text and color code for their tackle level. And I would use playerArray[tId][pId].tackleLvl if I want to get the numeric value.

After:
The database only have the numeric values, so everytime the plugin writes a message, instead of playerArray[tId][pId].tackle, I now need to use
arrLvl[Math.floor(playerArray[tId][pId].tackleLvl)]

So, all the written levels are taken out of the save file, and called upon when the game actually needs it. It isn't necessarily more difficult, and it saves a lot of space (i think... I havn't tried to save it yet.)
JavaScript:
    if (baseParams["Disable F5"]) {
        SDJB_Base._SM_onKeyDown = SceneManager.onKeyDown;
            SceneManager.onKeyDown = function(event) {
                if (event.code !== "F5") SDJB_Base._SM_onKeyDown.call(this, event);
            }
    };
I use this to disable F5 key, you can do the same for F4 or any key for that matter.
for the X that is a different story, for context, there is a way too, but not sure outside the window,
but it's doable if you have some knowledge to disable the option.

but you can do at least a bit of anti F5 and anti X and anti alt+F4 😛

abort process is something you can't avoid so far I know off.
I use this to disable F5 key, you can do the same for F4 or any key for that matter.
for the X that is a different story, for context, there is a way too, but not sure outside the window,
but it's doable if you have some knowledge to disable the option.

but you can do at least a bit of anti F5 and anti X and anti alt+F4 😛

abort process is something you can't avoid so far I know off.

Well, I think I have a solution for the mid-game saving... Here is what I have in mind:

I was planning on generating an action (based on the player skills and positions), save the outcome, show a part of the report, then generate the next action, and repeat, till the 90 minutes (in game) are over.

Instead, I might generate all actions before the first report is shown, save the outcome of the match, then show the reports one by one. For the gameplay it wouldn't matter that the outcome of the match is decided before the reports show up. The player can't do anything during the matches to change the outcome anyway.

Although, I might only generate 45 minutes at once, then at half time generate the second half. This leaves an opening to add half-time options later. Maybe change tactics, or something.

Anyhow, by generating and saving the full match (or half the match) at once, before the match starts for the player, I eliminate the ability to refresh and restart the match. You can still restart the match, but the results won't change.

Original thread: https://forums.rpgmakerweb.com/threads/can-i-save-data-in-a-file.171276/