Created
October 1, 2015 22:05
-
-
Save jwthomp/64a2702d91f837378f48 to your computer and use it in GitHub Desktop.
Bacon.js component playground
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Bacon = require("./vendor/Bacon.min.js"); | |
var GameObject = function() { | |
this.bus = new Bacon.Bus(); | |
this.eventStreams = []; | |
this.eventHandlers = []; | |
this.data = {}; | |
} | |
GameObject.prototype.registerEventType = function(eventType) { | |
this.eventStreams[eventType] = this.bus.filter(function(e) { | |
return e.eventType === eventType; | |
}).map(function(e) { | |
return e.data; | |
}); | |
return this.eventStreams[eventType]; | |
} | |
GameObject.prototype.getEventStream = function(eventType) { | |
return this.eventStreams[eventType]; | |
} | |
GameObject.prototype.registerHandler = function(eventType, handler) { | |
return this.getEventStream(eventType).map(handler, this.data); | |
} | |
var shieldProcessor = function(objectData, damageEventData) { | |
damageEventData.electromagnetic = Math.floor(objectData.shieldStrength * damageEventData.electromagnetic / 100); | |
return damageEventData; | |
} | |
var armorProcessor = function(objectData, damageEventData) { | |
damageEventData.kinetic = Math.floor(objectData.armorStrength * damageEventData.kinetic / 100); | |
return damageEventData; | |
} | |
var damageProcessor = function(objectData, damageEventData) { | |
objectData.hull -= damageEventData.kinetic + damageEventData.electromagnetic; | |
return objectData; | |
}; | |
var applyDamageToObject = function(gobj, kinetic, electromagnetic) { | |
var e = { | |
eventType: "damage", | |
data: { | |
kinetic: kinetic, | |
electromagnetic: electromagnetic | |
} | |
}; | |
// Send the damage event onto the objects event bus | |
gobj.bus.push(e); | |
}; | |
var myObject = new GameObject(); | |
myObject.data = { | |
hull: 100, | |
armorStrength: 25, | |
shieldStrength: 25 | |
} | |
myObject.registerEventType("damage") | |
.map(shieldProcessor, myObject.data) | |
.map(armorProcessor, myObject.data) | |
.map(damageProcessor, myObject.data) | |
.onValue(function(v) { | |
// Need to do this to make this stream not lazy | |
}); | |
console.log("Game Object State: ", myObject.data); | |
console.log("Apply Damage!"); | |
applyDamageToObject(myObject, 50, 50); | |
console.log("Game Object State: ", myObject.data); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment