How to create an event that randomly chooses from 100 vars with no repeat?

Here's a question I tried to solve myself in javascript but it's still a bit beyond me, so I'm hoping to get some help with it here, not just to solve the issue in my project, but also to learn from it for the future.

I have an event that chooses randomly from 100 consecutive variables. That's fine, but the player can activate this event over and over, and I'd like the previously chosen variables to be removed from the pool of available variables.

I know this is a pretty basic logic problem for coders, but I'm just not at the level yet to figure out how to do this within RPGMV.

Thanks all!!
It might be easier to have this be a single array and then remove entries at random than have 100 individual variables that all need to be tracked individually to see if they were used.
But if I were to use the 100 variables, id make it so that every time each one was used, id set its value to be undefined and make the event looking at the values to loop from the first to the last while skipping undefined ones
You'll put the IDs for the variables into an array, and then remove every element used from that array.

that way you don't have to mess with undefined variables or any other problem of rerolling, because once you have used 90 of the 100 cases rerollign after checking for undefined will take a lot of time.
My suggestion would be to use an array to store the variable IDs, and then use splice() to remove previously chosen variables.
Thanks all, will give this a shot. If it's okay I'd like to keep this thread active while I try to work it out!!
Also, just to put it out there, there have been several other threads about not repeating random values that included code. If you can't find them/figure it out, let us know.
Also, just to put it out there, there have been several other threads about not repeating random values that included code. If you can't find them/figure it out, let us know.

Reconnecting with this.

Searching for non-repeatable random variables, there are two threads I found that had what seemed like congruent requirements as mine, but one of them had no concrete solution other than to suggest that one ought to have intermediate knowledge of arrays, and another that worked fine because the set of variables was quite limited. And if I had only 5-6 variables to manage, I'd hold my nose and write a bunch of extremely ugly if statements which, while conceptually abhorrent, would nevertheless work.

I tried to wrangle GPT to produce a result that I could integrate into RPGMV but I quickly felt that, even with the master script call sheet, I was in over my head.

I'm not above conditionals!! But I have an event where the character will tell a random joke out of an array of about 140, and once told it can never be retold, and even though I would absolutely doom my soul to coding hell by making the worst series of conditionals known to man, I think people smarter than me have better solutions.

I understand arrays conceptually but have no experience, formal or otherwise, with implementing them, let alone in JS (my only experience is in C+, where all array problems required me seeking someone else's help 😉 @ATT_Turan if you do know of a thread where this is already covered please do let me know! No need to retread covered ground.

Otherwise, if it's within the bounds of what's appropriate to request, I'm hoping to solicit some more concrete help with this one.

Thank you!

-c
There are various options discussed here:
My suggestion would be something like this:

◆If:Script:!$gameVariables.value(123).length ◆Comment:No numbers remaining in list, or not initialised yet. ◆Control Variables:#0123 Jokes = Array.from(new Array(140), function(_, n) { return 1 + n; }) ◆ :End ◆Comment:Take a random number out of the array and store in variable 2. ◆Control Variables:#0002 JokeID = var a = $gameVariables.value(123); a.splice(Math.randomInt(a.length), 1)[0] ◆Text:None, Window, Bottom : :Selected joke \v[2]!
Easy-copy versions for the Script fields:
JavaScript:
!$gameVariables.value(123).length
JavaScript:
Array.from(new Array(140), function(_, n) { return 1 + n; })
JavaScript:
var a = $gameVariables.value(123); a.splice(Math.randomInt(a.length), 1)[0]
Substitutions:
  • Replace 123 with the ID of the variable where you want to store the list of remaining joke IDs.
  • Replace 140 with the total number of jokes you have.
  • Replace the Show Text at the end with 1 branch per joke ID, e.g.
    • If joke ID is 1: "Why did the chicken cross the road";
    • If joke ID is 2: "Knock knock";
    • Etc.
You got a good answer from caethyril, but I feel the need to comment on this:
I tried to wrangle GPT to produce a result that I could integrate into RPGMV

This is basically never a good idea. AI generators, by definition, make things up. I've never seen code come out of one that was longer than a line or two and actually functioned correctly, because it invents stuff that doesn't exist in the codebase.

If you don't know JavaScript well enough to recognize what's wrong and fix the problems in the generated code, you shouldn't be trusting AI to create for you. That's not what it's for.

Good luck with your project.
There are various options discussed here:
My suggestion would be something like this:

◆If:Script:!$gameVariables.value(123).length ◆Comment:No numbers remaining in list, or not initialised yet. ◆Control Variables:#0123 Jokes = Array.from(new Array(140), function(_, n) { return 1 + n; }) ◆ :End ◆Comment:Take a random number out of the array and store in variable 2. ◆Control Variables:#0002 JokeID = var a = $gameVariables.value(123); a.splice(Math.randomInt(a.length), 1)[0] ◆Text:None, Window, Bottom : :Selected joke \v[2]!

Easy-copy versions for the Script fields:
JavaScript:
!$gameVariables.value(123).length
JavaScript:
Array.from(new Array(140), function(_, n) { return 1 + n; })
JavaScript:
var a = $gameVariables.value(123); a.splice(Math.randomInt(a.length), 1)[0]
Substitutions:
  • Replace 123 with the ID of the variable where you want to store the list of remaining joke IDs.
  • Replace 140 with the total number of jokes you have.
  • Replace the Show Text at the end with 1 branch per joke ID, e.g.
    • If joke ID is 1: "Why did the chicken cross the road";
    • If joke ID is 2: "Knock knock";
    • Etc.

Thanks for this @caethyril, I hope you don't mind a follow-up on this. The solution in the thread you linked that I can actually wrap my brain around is different from the splice solution (which is my first time ever learning about this approach). I'm going to try your approach first, but I'm curious -- if I am setting a variable to an array, it would be

$gameVariables.setValue(42, [1,2,3,4,5,6])

If I were to go this route, could I set the array using a range, instead of typing out each variable ID individually?

As far as your solution, let me provide exact details specific to my project to make it easier for my own brain to follow, if that's okay with you 🙂

The way I have it set up currently is, variables 1501-1634 are reserved for the jokes. Each one is set to a string that has the joke text in it. I can always redo it but boy that took a while to set up and I'd love to work with the current setup.

◆If:Script:!$gameVariables.value(123).length ◆Comment:No numbers remaining in list, or not initialised yet. ◆Control Variables:#0123 Jokes = Array.from(new Array(140), function(_, n) { return 1 + n; })

So here, I would change the array length from 140 to 133 (or whatever the final number of jokes might be)?

I have other questions but for now I'm just gonna dive in and see what I can figure out on my own!

c

EDIT: So I began by trying the other approach, and while it's successfully choosing jokes at random, it's not removing those variables from the array.

Right now the test event looks like this:

$gameVariables.setValue(510, [1501,1502,1503,1504,1505,1506]) $gameVariables.setValue(511,$gameVariables.value(510).splice(Math.floor(Math.random()*$gameVariables.value(510).length),1)[0])

And then I'm just showing text with \v[\v[511]], and I get the joke that's already been initialized with the text when the game runs.

So I suppose the questions I have about this particular approach are, why would the chosen variable not be successfully removed from the array, and how can I set this array to a huge range rather than just individually typing it all out?

Still experimenting on my end, I know I'll figure this one out. There are jokes that need to be told!
You got a good answer from caethyril, but I feel the need to comment on this:


This is basically never a good idea. AI generators, by definition, make things up. I've never seen code come out of one that was longer than a line or two and actually functioned correctly, because it invents stuff that doesn't exist in the codebase.

If you don't know JavaScript well enough to recognize what's wrong and fix the problems in the generated code, you shouldn't be trusting AI to create for you. That's not what it's for.

Good luck with your project.

I agree with you 100%, the way I use GPT is as a learning tool. I would never, ever cut and paste AI code that I don't understand into a project, in fact I don't use ANY code I don't fully understand, even that provided by humans 🙂

But I've found it a pretty useful tool for learning about new functions I didn't previously know about, and in general it does tend to point me in a reasonably productive direction.

That said, your comments are super well taken.
But I've found it a pretty useful tool for learning about new functions I didn't previously know about
It can be. However, we have often seen in people's non-functioning code that the new functions you didn't know about are actually just made up 🤣
$gameVariables.setValue(42, [1,2,3,4,5,6])
Note that this has the same effect in-game as using Control Variables -> Script: [1,2,3,4,5,6], with the disadvantage that the editor's Event Searcher tool will not see that variable being used.

◆Control Variables:#0123 Jokes = Array.from(new Array(140), function(_, n) { return 1 + n; })
...
JavaScript:
Array.from(new Array(140), function(_, n) { return 1 + n; })
This Control Variables -> Script command sets the chosen variable to an array of numbers: [1, 2, 3, 4, ...etc..., 139, 140]. It does this by:
  • Starting with a new array of 140 blank entries (new Array(140)); then
  • Mapping each entry to the number 1 + n...
    • ...where n is the index of the entry (0 for first entry, 1 for second, etc)
Technical details here:
To generate an array of integers from 1501~1634 inclusive, you could use this instead:
JavaScript:
Array.from(new Array(1 + 1634 - 1501), function(_, n) { return 1501 + n; })
(The 1 + at the start is because we're including both 1501 and 1634.)

variables 1501-1634 are reserved for the jokes. Each one is set to a string that has the joke text in it. I can always redo it but boy that took a while to set up and I'd love to work with the current setup.
😅 Oof. Variables are typically for things that change during a playthrough, not static data. It's a waste to store the joke text like that, and it will bloat save files a bit, but like you say, it is workable.

why would the chosen variable not be successfully removed from the array
Perhaps you accidentally reset the array every time before picking a new value?

My example specifically checks the length of the array (i.e. the number of remaining entries in it) so the list only gets initialised if it's empty (or doesn't have a length property):
◆If:Script:!$gameVariables.value(123).length ◆Comment:No numbers remaining in list, or not initialised yet. ◆Control Variables:#0123 Jokes = Array.from(new Array(140), function(_, n) { return 1 + n; }) ◆ :End
You could reset it in a separate event (e.g. on new game) if you prefer that. In that case, though, you should still check to see if the array's length is more than 0 before splicing a value out of it.

I agree with you 100%, the way I use GPT is as a learning tool.
Like Turan says, don't take anything that ChatGPT says seriously. As its name suggests, it's a chat bot first and foremost: it cannot distinguish fact from fiction and is prone to making things up. Can be helpful for creative inspiration, but for reliable technical results, definitely look elsewhere.

I would never, ever cut and paste AI code that I don't understand into a project, in fact I don't use ANY code I don't fully understand, even that provided by humans
I was going to get all philosophical here, then thought better of it.
Note that this has the same effect in-game as using Control Variables -> Script: [1,2,3,4,5,6], with the disadvantage that the editor's Event Searcher tool will not see that variable being used.


This Control Variables -> Script command sets the chosen variable to an array of numbers: [1, 2, 3, 4, ...etc..., 139, 140]. It does this by:
  • Starting with a new array of 140 blank entries (new Array(140)); then
  • Mapping each entry to the number 1 + n...
    • ...where n is the index of the entry (0 for first entry, 1 for second, etc)
Technical details here:
To generate an array of integers from 1501~1634 inclusive, you could use this instead:
JavaScript:
Array.from(new Array(1 + 1634 - 1501), function(_, n) { return 1501 + n; })
(The 1 + at the start is because we're including both 1501 and 1634.)


😅 Oof. Variables are typically for things that change during a playthrough, not static data. It's a waste to store the joke text like that, and it will bloat save files a bit, but like you say, it is workable.


Perhaps you accidentally reset the array every time before picking a new value?

My example specifically checks the length of the array (i.e. the number of remaining entries in it) so the list only gets initialised if it's empty (or doesn't have a length property):

You could reset it in a separate event (e.g. on new game) if you prefer that. In that case, though, you should still check to see if the array's length is more than 0 before splicing a value out of it.


Like Turan says, don't take anything that ChatGPT says seriously. As its name suggests, it's a chat bot first and foremost: it cannot distinguish fact from fiction and is prone to making things up. Can be helpful for creative inspiration, but for reliable technical results, definitely look elsewhere.


I was going to get all philosophical here, then thought better of it.


@caethyril you have the patience of Buddha, thank you so much for helping guide me through this. We're almost there! :LZSgrin: And @ATT_Turan thank you so much for sticking around as well.

I've been working on this for a couple of hours and I have things mostly working, and I THINK I understand what's going on. But it's not quite working as intended yet, and I'm curious to understand what's going wrong. I've done everything I can do by way of troubleshooting.

For now, jokes are stored in variables 1801-1934 (I've moved them since last post since I realized there was a conflict). More on storing strings to vars later 😳

In my test event, this is what I have so far:

2023-12-12 02_09_08-Window.png


It's very inefficient, and I apologize for how bad I am at this, but I'm just trying to get things to function properly at this point! I have a switch that gets set if the array is empty. That part works fine.

For ease of testing I'm just choosing from the first few jokes.

I have the show text telling me both variable number and the string it's storing, and the reason I'm doing that is because no matter what I do, the lowest number variable I have stored always echoes as "0". So in the present case, if var 1801 is chosen, it produces a 0. This was the case also back when the variables were in a different range, so that suggests I don't have any other competing issues complicating the variable.

To be sure, variable 1801 is initiatlized with a joke string just like the others.

Otherwise it does work -- the other jokes print as intended, they don't repeat, and once they're exhausted, it says there's no more.

I've done a whole bunch of testing into what might be causing the lowest variable to produce 0, including the "I don't know what I'm doing but let's just change numbers and move things around" brute force method, which has its uses :LZScat:

On the subject of storing strings to variables tho -- I had NO IDEA that this created a bigger save file, or that variables were generally best reserved for non-static information, tho of course this all makes perfect sense when I think about it for a second lol. The thing is, it's not just 130 jokes that are stored to variables ... there's hundreds upon hundreds of non-changing strings stored to variables in my (gigantic, unwieldy) project, all of them initialized on a single autoload common event when the game begins. What might be the real-world hazards of this? Should I be concerned for real about bloated save files, or can I rest a bit easy knowing that I'm misusing variables with consequences that are confined to the realm of the theoretical?

And either way, I'm super curious to know what would be the optimal way to store tons and tons of static strings at a game's initialization. Back in the day when I coded for a MUD, people smarter than me advised me to set up all these strings at the very beginning, so I've sort of coasted on that general knowledge, but I have no idea how to best implement this sort of thing in RPGMV. Very much interested though, I'm happy to rearrange things if it means faster loads or smaller saves.

In any case, thanks to all for the guidance. To say it's appreciated would be an enormous understatement, and to call it an enormous understatement would be an incredible oversimplification!

-c :LZSsmile::LZScheeze::LZSsmile:
no matter what I do, the lowest number variable I have stored always echoes as "0".
I'm trying to figure out the point in what you've typed.

@caethyril gave you:
To generate an array of integers from 1501~1634 inclusive, you could use this instead:
JavaScript:
Array.from(new Array(1 + 1634 - 1501), function(_, n) { return 1501 + n; })

Then you say:
jokes are stored in variables 1801-1934

But your script says:
1702389186443.png


So the numbers plain and simple don't match up.

Should I be concerned for real about bloated save files
I mean, they'd be bloated compared to a save file of someone using RPG Maker in a more normal way. But on the scale of, like, kilobytes. Maybe a MB or something depending on exactly how much text you have in there. (caethyril may well know a more precise answer off the top of her head)

But not bloated, like, you're going to make your players run out of hard drive space, just bloated in terms of unnecessary.

I'm super curious to know what would be the optimal way to store tons and tons of static strings at a game's initialization. Back in the day when I coded for a MUD, people smarter than me advised me to set up all these strings at the very beginning
It doesn't have anything to do when when you're setting it up, it has to do with how you're storing it.

MUDs would either have this stuff declared directly in one of the code files (like you'd have a const array in interp.c with text strings of commands associated with the function they call) or in an external text file that you code a function to reference. That doesn't make its way into the player files at all.

You can do that here, and that would be the efficient thing to do - make a code file, a plugin, that has a function for retrieving strings that are defined in that code. Then you use the Script box in your event to call that function and put the returned string into one game variable.
For ease of testing I'm just choosing from the first few jokes.
OK, so the mismatched upper and lower bounds that Turan pointed out are just from you testing stuff, right?

Also:
  1. I have the show text telling me both variable number and the string it's storing, and the reason I'm doing that is because no matter what I do, the lowest number variable I have stored always echoes as "0". So in the present case, if var 1801 is chosen, it produces a 0.
    If the Show Text: \v[1499] \v[\v[1499]] message shows 1801 0, that means that variable 1801 has a value of 0, regardless of your intent. Choose New Game when testing, or enable the v1.7.0 editor's Game -> Skip Title Screen option.

    First, an easy test: turn off all plugins, save your project to apply Plugin Manager changes, then test from New Game. It probably won't change anything, but if it does, then you know one of those plugins is responsible.

    Otherwise, consider double-checking any place where that variable's value gets changed. Tools -> Event Searcher can be useful for this...but as mentioned earlier, that will not find changes made via script calls (or plugins). You can try putting that debug Show Text elsewhere, too, e.g. check the value of variable 1801 immediately after you assign it, then a few seconds later in case a Parallel event is doing something with that variable.

    Since you're assigning strings, also make sure you've remembered to put neutral quotes ("double" or 'single') around the text. Attempting to assign to an undeclared identifier will result in undefined, which will return 0 when you check that variable later on.

  2. When the jokes are all done you don't need to reinitialise the array, because (presumably) you'll never need to reference it again. Just turn on the "all done" switch and leave it at that. 👋

  3. I'm super curious to know what would be the optimal way to store tons and tons of static strings at a game's initialization.
    That's what the default database is: static data that doesn't change during a playthrough.

    There's a plugin that ships with MZ called UniqueDataLoader, by triacontane. I think it lets you manually write a custom database file, e.g. Jokes.json, then access it in-game like $dataJokes[jokeId]. I haven't tried it, personally. You can find it at:

    <RPG Maker MZ install folder>/dlc/BasicResources/plugins/official/UniqueDataLoader.js
    (This is for the Steam version, I imagine it's similar for standalone.)

  4. Should I be concerned for real about bloated save files
    Unless your jokes are novel-sized, the main problem with storing them all in their own variable is that the editor only lets you use a limited number of variables. As far as I'm aware, RMMZ stringifies save data to JSON, converts to base-64, then applies lossless compression. I imagine it'd end up as about +1 byte/char, considering the surrounding JSON and encoding/compression, maybe a little more if you use a lot of non-ASCII characters. Core MZ gives a console warning if a save's data exceeds 50000 chars after compression, but I don't think there's any hard limit in place. 😴
So the numbers plain and simple don't match up.

As @caethyril has clarified, I was limiting things for ease of testing, I just didn't want to have to click through 134 jokes to see if it was working as intended. I did mention that in my post but I could have made it more clear.

In any case I think it's 99% figured out -- I did the whole thing of turning off plugins, opening the event in a new project etc, nothing worked, variable 1801 kept returning 0, even though it was initialized quite clearly with a joke.

An hour of hair-pulling later I figured it out, and the clue was that the bug remained even when I moved that joke from variable 1501 to 1801. I was just missing a quotation mark at the end of the joke string :LZSskeptic: Well, now I know how that works!

Anyway, there's just one (very small) issue remaining. I changed the numbers to include all of the jokes (vars 1801-1934), and ran a full test, running through all the jokes and checking them off a little checklist I made.

Everything worked fine except it omitted one of the jokes. So, something's slightly off. Would that be an issue in setting up the array, or is it an issue of Array.from(new Array(134) somehow?

I would ordinarily just tackle this myself but each one of these full tests necessarily takes about 10 full minutes, so I think someone here would spot the error in just a few seconds instead. Here's the event as presently constituted:

2023-12-13 00_32_06-ID_006 - Event Editor.png


There's a plugin that ships with MZ called UniqueDataLoader, by triacontane.
This sounds perfect, is there a version of it that's compatible with MV?

Thank you so much -- almost there!!
is it an issue of Array.from(new Array(134) somehow?
When the jokes are all done you don't need to reinitialise the array, because (presumably) you'll never need to reference it again. Just turn on the "all done" switch and leave it at that.

What is the purpose of that script call?

To answer your question, that code shouldn't run unless all of the jokes have been read, so it couldn't have any effect on one being omitted.

What is the purpose of the \v[\v[1499]] syntax? Variable 1499 doesn't hold an array, it holds the single item removed from variable 1498's array.
You're checking to see if the jokes are all done before splicing one out, the numbers you're stating all seem to match up, and the script calls look OK. I'm not sure why it would skip one of them. Is it always the same one that gets skipped?

Like Turan says, the new Array(140) command should be removed. It does generate the wrong range of values (1~140 instead of 1801~1904), but that's irrelevant because you exit the event right afterwards. It's just unnecessary.

This sounds perfect, is there a version of it that's compatible with MV?
Oh. That's what I get for trying to keep track of too many threads at once! 😴

I did a quick search and didn't find an MV version of triacontane's plugin. It should be pretty simple, though.
Spoiler: plugin and walkthrough
Try saving this as a .js file, then import as a plugin:
JavaScript:
/*:
 * @target MV MZ
 * @plugindesc Load custom JSONs into global vars, for access via script call.
 * @author Caethyril
 * @url https://forums.rpgmakerweb.com/threads/163256/
 * @help Edit the plugin code to customise variable & file name pairs.
 *
 * Free to use and/or modify for any project, no credit required.
 */
DataManager._databaseFiles.push(
    // Load Stuff.json into $dataStuff on game boot
    { name: "$dataStuff", src: "Stuff.json" }
);
As noted in the plugin help, you can rename it to $dataJokes and Jokes.json or whatever you like by editing the code.

Then if the JSON file looks like this (save it as a .json file in your project's data folder):
JSON:
[
  "Index 0",
  "Index 1",
  "Index 2"
]
You should be able to access it in-game like this:
JavaScript:
$dataStuff[0]  // "Index 0"
You would still need an array to splice out of, though, because $dataStuff should remain constant during play. So, something like this:
  1. Control Variables 1498 -> Script (based on length of $dataStuff):
    JavaScript:
    Array.from($dataStuff, function(_, n) { return n; })
    This gets a list of array indices for each entry of $dataStuff. Checking for "all jokes done" will work the same as before.

  2. Splice out of variable 1498 just like before, into variable 1499.

  3. Get joke text for selected index:
    JavaScript:
    $dataStuff[$gameVariables.value(1499)]
    If you don't care about keeping hold of the joke index at this point then you could just store this text in variable 1499 (i.e. replace the joke index number with the respective text). Otherwise you'd want to store it in a third variable (1500?) so you can display it via the \v text code.

What is the purpose of the \v[\v[1499]] syntax?
It's a test message: it shows the selected joke ID (value of var 1499), followed by the respective joke's text (value of var with ID equal to value of var 1499).
It's a test message
Ah, gotcha.

Original thread: https://forums.rpgmakerweb.com/threads/how-to-create-an-event-that-randomly-chooses-from-100-vars-with-no-repeat.163256/