MV Non-Repeating Variables

Hello! I am in need of a plugin for RMMV that makes it so that variables will not repeat the same result back to back. For example, if I roll a variable and it lands on 4, and I roll it again immediately after, it will avoid a 4.

I had a script for RMVX Ace that did the same, but I've recently switched to RMMV. In the script for Ace, it was setup so that I could choose the number of rolls for which it would not result in the same roll. (For instance, looking back to the previous example, I could make it not roll a 4 again for six rolls.) I would like the plugin to have that freedom of choice.

It would be greatly appreciated if anyone could do this, as I require this for a gamejam project I am working on right now, and it'd be of use in some other projects of mine.
How are you trying to determine the roll, or what are you rolling. Dice? Stats?
Based on what you have given in your post You could try this.
Code:
/*:
 * @plugindesc Prevents a specific variable from repeating the same result back to back.
 * @author Digital Religioin
 *
 * @param Variable ID
 * @desc The ID of the variable you want to apply this behavior to.
 * @default 1
 *
 * @help
 * This plugin prevents a specific variable from getting the same value
 * consecutively. To use, simply specify the Variable ID in the plugin's parameters.
 */
(function() {
    var parameters = PluginManager.parameters('NonRepeatingVariable');
    var variableId = parseInt(parameters['Variable ID']);
    var previousValue = null;
    var _Game_Variables_setValue = Game_Variables.prototype.setValue;
    Game_Variables.prototype.setValue = function(variableId, value) {
        if (variableId === this._variableId) {
            while (value === previousValue) {
                value = this.rollValue(); // You'll need to define how the value is rolled.
            }
        }
        previousValue = value;
        _Game_Variables_setValue.call(this, variableId, value);
    };
    Game_Variables.prototype.rollValue = function() {
        // Define how you want to "roll" or determine the value here.
        // For example, if you want a random number between 1 and 10:
        return Math.floor(Math.random() * 10) + 1;
    };
})();

  1. Copy the code above and save it as NonRepeatingVariable.js in your project's js/plugins directory.
  2. Open your RMMV project and go to the Plugin Manager.
  3. Add the NonRepeatingVariable.js plugin to your list of active plugins.
  4. Set the "Variable ID" parameter to the ID of the variable you want this behavior applied to.
  5. Make sure to define how the variable gets its value in the rollValue function. The example provided rolls a random number between 1 and 10.
    Important. Read the comments cause you will have to make changes based on how you want to implement it.

    If you give me a better example of what you are tying to do I may be able to help out more.
How are you trying to determine the roll, or what are you rolling. Dice? Stats?
Based on what you have given in your post You could try this.
Code:
/*:
 * @plugindesc Prevents a specific variable from repeating the same result back to back.
 * @author Digital Religioin
 *
 * @param Variable ID
 * @desc The ID of the variable you want to apply this behavior to.
 * @default 1
 *
 * @help
 * This plugin prevents a specific variable from getting the same value
 * consecutively. To use, simply specify the Variable ID in the plugin's parameters.
 */
(function() {
    var parameters = PluginManager.parameters('NonRepeatingVariable');
    var variableId = parseInt(parameters['Variable ID']);
    var previousValue = null;
    var _Game_Variables_setValue = Game_Variables.prototype.setValue;
    Game_Variables.prototype.setValue = function(variableId, value) {
        if (variableId === this._variableId) {
            while (value === previousValue) {
                value = this.rollValue(); // You'll need to define how the value is rolled.
            }
        }
        previousValue = value;
        _Game_Variables_setValue.call(this, variableId, value);
    };
    Game_Variables.prototype.rollValue = function() {
        // Define how you want to "roll" or determine the value here.
        // For example, if you want a random number between 1 and 10:
        return Math.floor(Math.random() * 10) + 1;
    };
})();

  1. Copy the code above and save it as NonRepeatingVariable.js in your project's js/plugins directory.
  2. Open your RMMV project and go to the Plugin Manager.
  3. Add the NonRepeatingVariable.js plugin to your list of active plugins.
  4. Set the "Variable ID" parameter to the ID of the variable you want this behavior applied to.
  5. Make sure to define how the variable gets its value in the rollValue function. The example provided rolls a random number between 1 and 10.
    Important. Read the comments cause you will have to make changes based on how you want to implement it.

    If you give me a better example of what you are tying to do I may be able to help out more.
I will give this a try! But, to answer your question:

Basically, this is for an Oregon Trail inspired game where random events occur, and I roll a random variable to determine which events happen. Like, let's say I roll a variable for 1-20 , and it lands on 15, then the character may get, I dunno, attacked by a wolf or something. I don't want that same outcome to be able to happen on the next roll. I also want control over the frequency, like so that I can setup 15 to not show up again for a customizable amount of rolls, for instance.
Ok cool. It seems there will be several other systems you are making that will tie to this. But this should get you pointed in the right direction then.
You can do this through eventing
In theory you could build this behaviour with events too, although it would probably a bit more work:
- Roll a value with the random range reduced by one (for example instead of 1-6 you could roll 2-6)
- Compare the rolled value to your variables old value
- If the values are different set your variable to the rolled value
- If the values are the same set your variable to the number you left out (1 in this example)

Edit: A bit slow, AquaEchos method works too

Edit3: Forget Edit2, I cannot read, also I messed up the names, Sorry Digital Religion
This actually might be an easier approach for sure.
You can just do +1 if the current roll is more than the previous one, e.g.
  • On new game:

    ◆Comment:Initialise "previous" roll on new game. ◆Control Variables:#0022 Prev Roll = Random 1..10
  • Per roll:

    ◆Comment:Each time, roll 1~9 instead of 1~10... ◆Control Variables:#0023 New Roll = Random 1..9 ◆Comment:...+1 if the roll is >= the previous roll ◆If:New Roll ≥ Prev Roll ◆Control Variables:#0023 New Roll += 1 ◆ :End ◆Control Variables:#0022 Prev Roll = New Roll
[Edit: "Next Number" -> "New Roll".]
Ok cool. It seems there will be several other systems you are making that will tie to this. But this should get you pointed in the right direction then.
I tested it and it'll do, although, it'd be preferable if I could make any variable do it incase I need to use it for multiple variables for some reason (This circumstance did actually pop up before when I used it in Ace, but I cannot recall the context.)

If it helps, here is the coding for the Ace version that I have:

Code:
class Memory_dice


  attr_accessor :dice

  attr_accessor :mem


  def initialize(num_sides, memory_size)

    @dice = num_sides

    @mem = Array.new(memory_size, -1)

  end


 


  def roll

    result = @mem[0]

    while @mem.include?(result)

      result = rand(@dice)

    end

    @mem.unshift(result)

    @mem.pop

    return p(result)

  end

end


$cookie_dice = Memory_dice.new(57, 4)


# change the values to fit your needs

# as is now it will roll random number 0-9

# and won't yield the last 4 values

 

# script call => $cookie_dice.roll
I tested it and it'll do, although, it'd be preferable if I could make any variable do it incase I need to use it for multiple variables for some reason (This circumstance did actually pop up before when I used it in Ace, but I cannot recall the context.)

If it helps, here is the coding for the Ace version that I have:

Code:
class Memory_dice


  attr_accessor :dice

  attr_accessor :mem


  def initialize(num_sides, memory_size)

    @dice = num_sides

    @mem = Array.new(memory_size, -1)

  end


 


  def roll

    result = @mem[0]

    while @mem.include?(result)

      result = rand(@dice)

    end

    @mem.unshift(result)

    @mem.pop

    return p(result)

  end

end


$cookie_dice = Memory_dice.new(57, 4)


# change the values to fit your needs

# as is now it will roll random number 0-9

# and won't yield the last 4 values

 

# script call => $cookie_dice.roll
Since you said it worked for you, you could also (depending on where you got it) share the old script and see if someone would recreate it as a plugin.
The logic shouldn't be that hard to pull for plugin authors and you'll likely get exactly what you'd like.
You can just do +1 if the current roll is more than the previous one, e.g.
  • On new game:

    ◆Comment:Initialise "previous" roll on new game. ◆Control Variables:#0022 Prev Roll = Random 1..10

  • Per roll:

    ◆Comment:Each time, roll 1~9 instead of 1~10... ◆Control Variables:#0023 New Roll = Random 1..9 ◆Comment:...+1 if the roll is >= the previous roll ◆If:New Roll ≥ Prev Roll ◆Control Variables:#0023 New Roll += 1 ◆ :End ◆Control Variables:#0022 Prev Roll = New Roll

[Edit: "Next Number" -> "New Roll".]
I considered this approach, but then the issue came up of if it landed on the final value. Granted, that could be handled with a conditional branch without too much hassle.

Since you said it worked for you, you could also (depending on where you got it) share the old script and see if someone would recreate it as a plugin.
The logic shouldn't be that hard to pull for plugin authors and you'll likely get exactly what you'd like.
I just shared the original code in a reply.
I considered this approach, but then the issue came up of if it landed on the final value.
That's why for a range of 1~10 you roll (as shown in my example) from 1~9 each time, because there are only 9 "valid" values from which to select. The +1 simply jumps over the invalid value where appropriate. Feel free to use whatever approach you like, though~
Not sure if this is still relevant, forgot about this thread:

If you need your results to not repeat for longer than a single roll, you could try using this (it is not a faithful port of the script and got a bit out of hand, but it should work hopefully):
Spoiler
Code:
/*:
 * @plugindesc A set of dice with a lockout period for each rolled number
 *
 * @param Default Sides
 * @desc Sides of the dice (from 0 to [sides - 1])
 * @type Number
 * @min 1
 * @default 100
 *
 * @param Default Lockout
 * @desc Minimum number of rolls between two identical outcomes
 * @type Number
 * @min 0
 * @default 0
 *
 * @help
 * To generate a number, use this in the script field of "Control Variables":
 * The results range from 0 (inclusive) to the number of sides (exclusive).
 * - tag : Dice identifier: Can be any number or string ("undefined" if left out).
 *
 *   $gameSystem.rollDice(tag);
 *
 * To change the configuration of a dice, use this script command:
 * - tag     : Dice identifier
 * - sides   : New sides of the dice
 * - lockout : New lockout period
 * Sides and lockout can be left out to use the plugins default settings instead.
 * This will reset any current lockouts of the dice:
 *
 *   $gameSystem.setupDice(tag, sides, lockout);
 *
 *   $gameSystem.setupDice(tag);
 */

function NonRepeatingDice() {
    this.initialize.apply(this, arguments);
}

NonRepeatingDice.DEFAULT_SETTINGS = (function() {
    let url = document.currentScript._url;
    let name = url.slice(PluginManager._path.length, -3);
    let parameters = PluginManager.parameters(name);
    return {
        sides   : Number(parameters["Default Sides"]),
        lockout : Number(parameters["Default Lockout"])
    };
})();

NonRepeatingDice.prototype.initialize = function(sides, lockout) {
    let defaultSettings = NonRepeatingDice.DEFAULT_SETTINGS;
    sides   = (sides   !== undefined ? sides   : defaultSettings.sides);
    lockout = (lockout !== undefined ? lockout : defaultSettings.lockout);
    if (sides < 1 || lockout > sides - 1) {
        throw "Invalid dice parameters: " + [sides, lockout];
    }
    this._sides = sides;  // Sides of the dice
    this._lockoutLength = lockout;  // Lockout period
    this._lockoutQueue = [];  // List of locked values (in order of their lockouts)
    this._substitutes = {};  // Replacements for each locked value within roll limit
};

NonRepeatingDice.prototype.next = function() {
    let rollLimit = this._sides - this._lockoutQueue.length;
    let firstRoll = Math.randomInt(rollLimit);
    let firstSub  = this._substitutes[firstRoll];
    let finalRoll = (firstSub !== undefined ? firstSub : firstRoll);
    if (this._lockoutLength > 0) {
        // FirstRoll now needs a (new) substitute;
        // One index gets freed up (either bc. it is reinstated or bc. it is now out
        // of range for future first rolls if the lockout queue is still expanding).
        let queueFull = (this._lockoutQueue.length >= this._lockoutLength);
        let freedIndex = queueFull ? this._lockoutQueue.shift() : (rollLimit - 1);
        if (firstRoll !== freedIndex) {
            let freedSub = this._substitutes[freedIndex];
            let newFirstSub = (freedSub !== undefined ? freedSub : freedIndex);
            this._substitutes[firstRoll] = newFirstSub;
        }
        delete this._substitutes[freedIndex];
        this._lockoutQueue.push(finalRoll);
    }
    return finalRoll;
};

Game_System.prototype.setupDice = function(tag, sides, lockout) {
    this._nonRepeatingDiceTable = this._nonRepeatingDiceTable || {};
    this._nonRepeatingDiceTable[tag] = new NonRepeatingDice(sides, lockout);
};

Game_System.prototype.rollDice = function(tag) {
    if (!this._nonRepeatingDiceTable || !this._nonRepeatingDiceTable[tag]) {
        this.setupDice(tag);
    }
    return this._nonRepeatingDiceTable[tag].next();
};
Not sure if this is still relevant, forgot about this thread:

If you need your results to not repeat for longer than a single roll, you could try using this (it is not a faithful port of the script and got a bit out of hand, but it should work hopefully):
Spoiler
Code:
/*:
 * @plugindesc A set of dice with a lockout period for each rolled number
 *
 * @param Default Sides
 * @desc Sides of the dice (from 0 to [sides - 1])
 * @type Number
 * @min 1
 * @default 100
 *
 * @param Default Lockout
 * @desc Minimum number of rolls between two identical outcomes
 * @type Number
 * @min 0
 * @default 0
 *
 * @help
 * To generate a number, use this in the script field of "Control Variables":
 * The results range from 0 (inclusive) to the number of sides (exclusive).
 * - tag : Dice identifier: Can be any number or string ("undefined" if left out).
 *
 *   $gameSystem.rollDice(tag);
 *
 * To change the configuration of a dice, use this script command:
 * - tag     : Dice identifier
 * - sides   : New sides of the dice
 * - lockout : New lockout period
 * Sides and lockout can be left out to use the plugins default settings instead.
 * This will reset any current lockouts of the dice:
 *
 *   $gameSystem.setupDice(tag, sides, lockout);
 *
 *   $gameSystem.setupDice(tag);
 */

function NonRepeatingDice() {
    this.initialize.apply(this, arguments);
}

NonRepeatingDice.DEFAULT_SETTINGS = (function() {
    let url = document.currentScript._url;
    let name = url.slice(PluginManager._path.length, -3);
    let parameters = PluginManager.parameters(name);
    return {
        sides   : Number(parameters["Default Sides"]),
        lockout : Number(parameters["Default Lockout"])
    };
})();

NonRepeatingDice.prototype.initialize = function(sides, lockout) {
    let defaultSettings = NonRepeatingDice.DEFAULT_SETTINGS;
    sides   = (sides   !== undefined ? sides   : defaultSettings.sides);
    lockout = (lockout !== undefined ? lockout : defaultSettings.lockout);
    if (sides < 1 || lockout > sides - 1) {
        throw "Invalid dice parameters: " + [sides, lockout];
    }
    this._sides = sides;  // Sides of the dice
    this._lockoutLength = lockout;  // Lockout period
    this._lockoutQueue = [];  // List of locked values (in order of their lockouts)
    this._substitutes = {};  // Replacements for each locked value within roll limit
};

NonRepeatingDice.prototype.next = function() {
    let rollLimit = this._sides - this._lockoutQueue.length;
    let firstRoll = Math.randomInt(rollLimit);
    let firstSub  = this._substitutes[firstRoll];
    let finalRoll = (firstSub !== undefined ? firstSub : firstRoll);
    if (this._lockoutLength > 0) {
        // FirstRoll now needs a (new) substitute;
        // One index gets freed up (either bc. it is reinstated or bc. it is now out
        // of range for future first rolls if the lockout queue is still expanding).
        let queueFull = (this._lockoutQueue.length >= this._lockoutLength);
        let freedIndex = queueFull ? this._lockoutQueue.shift() : (rollLimit - 1);
        if (firstRoll !== freedIndex) {
            let freedSub = this._substitutes[freedIndex];
            let newFirstSub = (freedSub !== undefined ? freedSub : freedIndex);
            this._substitutes[firstRoll] = newFirstSub;
        }
        delete this._substitutes[freedIndex];
        this._lockoutQueue.push(finalRoll);
    }
    return finalRoll;
};

Game_System.prototype.setupDice = function(tag, sides, lockout) {
    this._nonRepeatingDiceTable = this._nonRepeatingDiceTable || {};
    this._nonRepeatingDiceTable[tag] = new NonRepeatingDice(sides, lockout);
};

Game_System.prototype.rollDice = function(tag) {
    if (!this._nonRepeatingDiceTable || !this._nonRepeatingDiceTable[tag]) {
        this.setupDice(tag);
    }
    return this._nonRepeatingDiceTable[tag].next();
};
This seems like exactly what I want, but I tested it out, and it doesn't seem to work.

Strangely, neither does Digital Religion's, which seemed to work before in a brief test. I even tried both out in a new project with no existing plugins, and both are repeating values.
Can you show what exactly you tried maybe?
If you used the second plugin make sure to customize the plugin parameters, the "Default Lockout" determines how many rolls need to pass before your first roll can repeat, which is left at 0 by default.

It seems to work fine for me (in a test setup with a 20 sided dice and the maximum of 19 rolls in between repeats):
Can you show what exactly you tried maybe?
If you used the second plugin make sure to customize the plugin parameters, the "Default Lockout" determines how many rolls need to pass before your first roll can repeat, which is left at 0 by default.

It seems to work fine for me (in a test setup with a 20 sided dice and the maximum of 19 rolls in between repeats):
Hey. My apologies for the late response. I got caught up in dev and forgot to check for responses here. I temporarily used an event solution, but if your code does what I seek, then that would be the better option.

Before I post an example -- I must ask, does your code work with only one variable? Because, each variable I use has it's own task. I use a single variable to roll for the outcome, and that single variable should not roll the same outcome more than a designated number of times. I ask because you used 20 variables in your example.

Also, can you make other variables with their own parameters? There are a number of dice that check things. For example, there is a mechanic where entities can appear that threaten the player, and I want it so that it won't repeat said entity. That only really needs a parameter of not rolling the very last roll, whereas others may need a parameter of not rolling the last four or so rolls.
Hey,

I must ask, does your code work with only one variable?
Right now the code works through the script command. Each time you run the script command you will get the next number in the series. You can put them all in one variable or spread them out like in the example.

Also, can you make other variables with their own parameters?
You can use different dice. Each dice has its own (case sensitive) tag, so you can use for example
$gameSystem.rollDice("Entity")
$gameSystem.rollDice("Path")

to roll two different dice for entities and paths. By default all dice use the settings from the plugin parameters, but you can set them up individually by using
$gameSystem.setupDice("Entity", 6, 1)
at the beginning of the game or before first using the dice (like in the example).
(Might move that into the plugin parameters)
It is functioning now! I must have been doing something wrong, lol. This is perfect~ Thanks!

Original thread: https://forums.rpgmakerweb.com/threads/non-repeating-variables.160051/