Skip to content

Instantly share code, notes, and snippets.

@Akjosch
Created October 29, 2019 14:55
Show Gist options
  • Save Akjosch/230e29c1add7c02d275632b09b778b12 to your computer and use it in GitHub Desktop.
Save Akjosch/230e29c1add7c02d275632b09b778b12 to your computer and use it in GitHub Desktop.
Setting up events from event-tagged passages in SugarCube, simple version
class GameEvent {
/**
* @param {string} target
* @param {string} trigger
* @param {string} weight
* @param {string} priority
*/
constructor(target, trigger, weight, priority) {
this.target = String(target);
this.trigger = trigger;
this.weight = weight;
this.priority = priority;
if(trigger) {
this.triggerFunc = new Function("c", "return !!(" + trigger + ")");
}
if(weight) {
this.weightFunc = new Function("c", "return Number(" + weight + ")");
}
if(priority) {
this.priorityFunc = new Function("c", "return Math.round(" + priority + ")");
}
}
/**
* @param {any=} context
* @returns {boolean}
*/
isPossible(context) {
try {
return this.triggerFunc ? this.triggerFunc(context || {}) : true;
} catch(ex) {
console.log(ex);
return false;
}
}
/**
* @param {any=} context
* @returns {number}
*/
calcWeight(context) {
try {
return this.weightFunc ? this.weightFunc(context || {}) : 1.0;
} catch(ex) {
console.log(ex);
return 0.0;
}
}
/**
* @param {any=} context
* @returns {number}
*/
calcPriority(context) {
try {
return this.priorityFunc ? this.priorityFunc(context || {}) : 0;
} catch(ex) {
console.log(ex);
return Number.MIN_SAFE_INTEGER;
}
}
}
setup.GameEvent = GameEvent;
setup.events = Story.lookup("tags", "event")
.map(function(p) {
var triggersRE = /^TRIGGER:\s*(\S.*?)$/m;
var weightsSE = /^WEIGHT:\s*(\S.*?)$/m;
var prioritiesSE = /^PRIORITY:\s*(\S.*?)$/m;
var trigger = triggersRE.exec(p.text);
var weight = weightsSE.exec(p.text);
var priority = prioritiesSE.exec(p.text);
return new setup.GameEvent(p.title, trigger ? trigger[1] : "", weight ? weight[1] : "", priority ? priority[1] : "");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment