Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Tweak this RPG Combat Loop?

Tweak this RPG Combat Loop?

Problem

Client + Server are both written in Javascript. I don't have a master game Loop because combat occurs sparingly and there is nothing else in the game that requires a loop. When two players initiate combat, they go into an auto-attack loop like this:

if ( combat key is pressed ) {

    check a bunch of stuff;
    setTimeout( combatLoop(); 5000 );

}

combatLoop = function() {

    attack(player1,player2);

    var loop = setTimeout( combatLoop(); 5000 );

    if ( skill variable == 1 ) { clearTimeout(loop); skill(); }

}

So, the combatLoop function gets called over and over again every 5 secs. The attack function handles what happens when the two input players attack each other. If players uses a Skill, clearTimeout is used to get out of the loop, and the relevant skill() function is called. The skill function may or may not call combatLoop again.

Question 1

I am very new to Javascript, and I was wondering if you guys see any major flaw with doing it this way?

Question 2

I haven't seen any similar examples of what I am trying to do, so I kinda hack the skill button part together. Is it "wrong" to make the combat loop "listen" to skill button presses this way (skill button press => set skill variable = 1) and clear the main loop using a clearTimeout? So, skill gets execute during the next attack (not in between attacks), which is fine by me. No idea what the industrial standard is. :p

Problem courtesy of: Legendre

Solution

You could do this, although I'm not a big fan of setInterval():

if (keypressed) { //change this to a proper event handler ;)
  Engine.combatStart();
}

var Engine = {
  combatTimer: null, //timer var
  combatStart: function() {
    Engine.combatTimer = setTimeout(Engine.combatLogic, 5000);
  },
  combatLogic: function() {
    //calculate attacks etc...

    if (skill === 1) {
      clearTimeout(Engine.combatTimer);
      skill();
    }

    Engine.combatTimer = setTimeout(Engine.combatLogic, 5000);
  }
};

You can also:

document.addEventListener("keypress", function(e) {
    if (e.keyCode === XX) {
         clearTimeout(Engine.combatTimer);
         skill()            
    }        
});

So you listen for a keypress, replace XX with the keycode for the skill key - then clear the timeout loop... :/

Solution courtesy of: Barrie Reader

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Tweak this RPG Combat Loop?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×