Tiny Turn-based

A hopefully tiny turn-based system.

by Sam Fereday

HTML

<button id="start">
  Start
</button>

JavaScript

/*

What it does so far:
- Takes turn between each target, singular or multiple
- Plug in events so you know whos turn it is
- Manages any entities that are dead and skips over them
- Simple chance mechanism to determine first players go

What it's going to have later:
- Weight for each turn (slow state, petrify, etc)
- Plug in other functions to intercept how first choice is decided
- Personal timer for each entity (so can be effected by stats or weight)

*/

// For each thing in battle, there must be a battle Actor
var BattleActor = function(id, tiq) {

  // Specifying an id can be helpful, otherwise one will just be created.
  if(!id) id = 'ba-' + Date.now() + tiq;

	this.id = id;
  this.idx = tiq;
  
};

// The controller for the battle
var BattleController = function() {
  this.callbacks = {
    onActorReady: null,
    onBattleStarted: null,
    onBattleEnded: null
  }
  this.allowFlow = false;
  return this;
};

BattleController.prototype.init = function(actors, events) {

  // Bind callbacks - this is a massive wip.
  if (events) {

    if (typeof events.onActorReady === 'function')
      this.callbacks.onActorReady = events.onActorReady;

    if (typeof events.onBattleStarted === 'function')
      this.callbacks.onBattleStarted = events.onBattleStarted;

    if (typeof events.onBattleEnded === 'function')
      this.callbacks.onBattleEnded = events.onBattleEnded;

  }

  // Bind actors
  if (actors.length < 2) {
    throw "You can't fight with yourself, add more actors.";
  }

  this.battleActors = actors.map(function(act, i) {
    return new BattleActor(act.id, i);
  });

  var firstIndex = this.chooseFirst();
  this.assignCurrentActor(firstIndex);
  this.queueStep = firstIndex;

  return this;

}

/// Before turn taken methods
// Informs external user that actor with said ID can take their action
BattleController.prototype.triggerOnReady = function() {

  if (typeof this.callbacks.onActorReady === 'function')
    this.callbacks.onActorReady.call(this,...