Indie Dev

Hello Guest!. Register a free account today to become a member! Once signed in, you'll be able to participate on this site by adding your own topics and posts, sell your games, upload content, as well as connect with other members through your own private inbox!

Simulate time passed while game is off to gain lives while not playing

CT_Bolt

Global Moderator
Staff member
Resource Team
Xy$
0.02
Ok soo this one is a bit complicated...
I have a time system working in the game (using Orange Time System by Hudell).
The time system doesn't use real time and is more like a counter that counts seconds, minutes, etc.

I use this to determine when to give the player a life. (Similar to basically every phone game lol, ex. candy crush, pokemon shuffle, etc.)

Sooo I've got it all working perfect while the game is running, however I am now attempting to determine the lives gained while the game is off.

My current situation is this:
I auto-save the game ever time a map is loaded (ideally would also like to save when the game exits... WIP)
The save stores the "getTime" from the date object into a game variable.
(number in milliseconds since midnight of January 1, 1970)
Reference found here: http://www.w3schools.com/jsref/jsref_gettime.asp

When the game is loaded it checks for saves and loads the auto-save if there is.

Then I run a function to calculate how many lives should be given.

Currently I do attempt this by comparing the oldTimeVariable with the current time. (again in milliseconds)
I can basically get how many lives should be earned by the following:
JavaScript:
var oldMinutes = (oldMilliseconds / 1000) / 60;
var newMinutes = (newMilliseconds / 1000) / 60;
livesGained = Math.floor((newMinutes - oldMinutes)/minutesBeforeNewLife);
However I have a serious problem with that... I need to remove what has passed from the time variables and determine whether or not they have earned lives. Sooo I've kind of hit a wall & need help.

This is the function mentioned (although I've altered it to many times to even make much since of it myself now lol):
JavaScript:
var calculateAddedHearts = function(){
//  $gameVariables.setValue(21, $gameVariables.value(23));
  if ($gameVariables.value(21) < $gameVariables.value(23)){
    var oldTime = $gameVariables.value(151);
    var dateObj = new Date();
   
    var oldMilliseconds = oldTime;
    var newMilliseconds = dateObj.getTime();
    var millisecondsLeftOnClockWhenSaved = (((($gameVariables.value(22)-1)-$gameVariables.value(2))*60)+(60-$gameVariables.value(1)))*1000

    if ((newMilliseconds-oldMilliseconds) > millisecondsLeftOnClockWhenSaved){
      newMilliseconds = newMilliseconds - millisecondsLeftOnClockWhenSaved;
      $gameVariables.setValue(1, 0);
      $gameVariables.setValue(2, 0);

      var oldMinutes = (oldMilliseconds / 1000) / 60;
      var newMinutes = (newMilliseconds / 1000) / 60;

      if (($gameVariables.value(21) + Math.floor(((newMinutes - oldMinutes)/5))) < $gameVariables.value(23)){
        $gameVariables.setValue(21, $gameVariables.value(21) + (newMinutes - oldMinutes));
      }else{
        $gameVariables.setValue(21, $gameVariables.value(23));
      }
    }else{
      millisecondsLeftOnClockWhenSaved = millisecondsLeftOnClockWhenSaved - (newMilliseconds-oldMilliseconds);
      if ((millisecondsLeftOnClockWhenSaved*1000) > 60){

        var minutesAfterLoaded = (millisecondsLeftOnClockWhenSaved*1000) / 60;
        var secondsAfterLoaded = (millisecondsLeftOnClockWhenSaved*1000) % 60;

        $gameVariables.setValue(1, secondsAfterLoaded);
 
        $gameVariables.setValue(2, minutesAfterLoaded);

      }
    }
    console.log("Lives Gained: " + Math.floor((newMinutes - oldMinutes)/5));
    console.log("Minutes Passed: " + Math.floor(newMinutes - oldMinutes));
  }
}

Summary:
I need to have time pass when the game is off to gain lives.
Most likely this will have to be simulated since the game is completely off.

Thank you for reading. (cheeky) I hope someone can help me.
 

LTN Games

Master Mind
Resource Team
Xy$
0.01
Yikes! If I learned one thing from my Time Engine plugin, is how annoying and tough it can be to calculate time and get things running correctly. I may be able to help, my timers mechanic in Time Engine is pretty similar in terms of calculations. With my timers I have it so if you skip 18 hours into the future, I still calculate which timers should have been activated within that 18 hours and I activate them. With that basic logic it should be similar to what you're thinking.

So this is the logic I have for determining the elapsed time and calculating what's been missed and remove it or in your case add to it.
  • Record stop time and start time - In this case, record the time when game exits or it's last save and the time when the game has started.
  • Convert values to milliseconds, for easier calculation.
  • Calculate elapsed time (stopTimeInMs - startTimeInMs)
  • Calculate how many hearts are possible to add according to elapsed time
Now obviously you don't want to use Orange Time system for recording the stop and start time values, instead use the new Date() method. I assume this is the part where you hit a wall . So logically, you want to save the current time on save game, so you will need to tap into the save function and record the time into a variable(globally) which will be saved into the save contents. Are you familiar with saving data to MV's game file?
Then when the game loads you store a new date and follow the logic as above and because the stop time has been saved into MV's save file you can now compare that value with the value of the time on game load.

Where have you written this code you have above ? Seeing a little more of how this plugin looks may be useful in me helping you out some more. I could probably help write some of it if I knew a little more of what you have and where things are etc. Hopefully the little bit of logic I went over helps you some, either way let me know a bit more details and I'll see what I can do.
 

CT_Bolt

Global Moderator
Staff member
Resource Team
Xy$
0.02
Thanks for the reply, it was helpful to get your perspective on this. (cheeky)
I believe I did manage to solve this. I re-wrote the function and came up with the following:
JavaScript:
var calculateAddedHearts = function(){
  var howManyMinutesForHeart = 2;

  // If Hearts < Max Hearts From Timer
  if ($gameVariables.value(21) < $gameVariables.value(23)){

    // Declare new Date Object
    var dateObj = new Date();

    // Store the Saved Time and The Current Time in Variables
    var savedMs = $gameVariables.value(151);
    var newMs = dateObj.getTime();

    // Calculate the remaining time left on the clock
    var savedClockMs = (((($gameVariables.value(22)-1)-$gameVariables.value(2))*60)+(60-$gameVariables.value(1)))*1000

    // Calculate the amount of time that has passed (Ms);
    var timePassedMs = newMs - savedMs;

    // If the amount of time passed is greater than the remaining of time on the saved clock time...
    if (timePassedMs > savedClockMs){
      // Reset the Time Clock
      $gameVariables.setValue(1, 0); // (Seconds)
      $gameVariables.setValue(2, 0); // (Minutes)
      console.log("Clock Set to 0");

      // Subtract the saved amount of time from the amount of time passed for later use.
      timePassedMs = timePassedMs - savedClockMs;

      // Add a heart
      $gameVariables.setValue(21, $gameVariables.value(21) + 1);
      console.log("1 Heart Gained from Remaining Time");

      // Calculate how many minutes have passed after subtracted the remaining
      var minutesPassed = ((timePassedMs / 1000) / 60);
      console.log("Minutes Passed: " + minutesPassed);

      // Add hearts from minutes passed
      var heartsGained = Math.floor(minutesPassed / howManyMinutesForHeart);
      $gameVariables.setValue(21, $gameVariables.value(21) + heartsGained);
      console.log("Added hearts from time passed: " + heartsGained);
   
      // If hearts are greater than max hearts from Timer...
      if ($gameVariables.value(21) > $gameVariables.value(23)) {

        // Set hearts to max hearts from timer
        $gameVariables.setValue(21, $gameVariables.value(23));
      }
    }else{
      // New Time Remaining in Milliseconds
      var newTimeForClockMs = savedClockMs - timePassedMs;

      // Calculate minutes remaining
      var clockMin = parseInt((savedClockMs / 1000) / 60);

      // Calculate seconds remaining
      var clockSec = (savedClockMs / 1000) % 60;

      // Set the Time Clock to the Correct Time
      $gameVariables.setValue(1, clockSec); // (Seconds)
      $gameVariables.setValue(2, clockMin); // (Minutes)
    }
  }
}
Mind if I message you a copy of my project so you can BETA test?
 
Last edited:

CT_Bolt

Global Moderator
Staff member
Resource Team
Xy$
0.02
You bet, send it my way and I'll test it out when I get some free time today. I'm glad my perspective helped you out some and your new function looks much better.
Sorry for the delayed reply, I've decided to add just a few more tweaks before I send it along. (puppy eyes)(cute)

Currently I'm really struggling to find when the program is terminated though. (ex. Red "X", Alt + F4, ↰ on Phone).
Any idea how this could be accomplished... I've tried the following:
JavaScript:
window.onbeforeunload = function(e){
  return "Are you sure?"
};

$(document).ready(function()
{
  $(window).bind("beforeunload", function(){
   return confirm("Do you really want to exit?");
  });
});

SceneManager.terminate = function() {
    var dateObj = new Date();
    $gameVariables.setValue(151, dateObj.getTime());
    $gameSystem.onBeforeSave();
    DataManager.saveGame(1);
    window.close();
};

SceneManager.exit = function() {
    var dateObj = new Date();
    $gameVariables.setValue(151, dateObj.getTime());
    $gameSystem.onBeforeSave();
    DataManager.saveGame(1);

    this.goto(null);
    this._exiting = true;
};
Afterthought... perhaps this is something achieved using IntelXDK after exporting?
 
Last edited:

LTN Games

Master Mind
Resource Team
Xy$
0.01
SceneManager terminate or exit should work fine, are you running into problems with saving the values? If you are, it may be due to saving on exit and it is closing before finishing the save.
 

CT_Bolt

Global Moderator
Staff member
Resource Team
Xy$
0.02
SceneManager terminate or exit should work fine, are you running into problems with saving the values? If you are, it may be due to saving on exit and it is closing before finishing the save.
I had the same thoughts...
however it doesn't even appear to be catching I have an alert command in the function now, but nothing pops up.
I would have thought that it should pop up right before exiting but it doesn't.

JavaScript:
SceneManager.terminate = function() {
    var dateObj = new Date();
    $gameVariables.setValue(151, dateObj.getTime());
    console.log("Saving Game, Time = " + $gameVariables.value(151));
    alert("Saving Game, Time = " + $gameVariables.value(151));

    $gameSystem.onBeforeSave();
    DataManager.saveGame(1);
    window.close();
};

SceneManager.exit = function() {
    var dateObj = new Date();
    $gameVariables.setValue(151, dateObj.getTime());
    console.log("Saving Game, Time = " + $gameVariables.value(151));
    alert("Saving Game, Time = " + $gameVariables.value(151));

    $gameSystem.onBeforeSave();
    DataManager.saveGame(1);

    this.goto(null);
    this._exiting = true;
};
 
Top