Created
May 7, 2014 21:56
-
-
Save frostney/b179a80bfea5d19f50e7 to your computer and use it in GitHub Desktop.
Prototyping GameObjects with fluent APIs and tagged behaviors in a group
This file contains hidden or 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
class GameObject | |
constructor: -> | |
@x = 0 | |
@y = 0 | |
@behaviors = {} | |
andObject = @ | |
@move = (x, y) => | |
@x += x | |
@y += y | |
andObject | |
@move.to = (@x, @y) => @move | |
@move.and = @move.to.and = @ | |
@addBehavior = (behavior) -> | |
toString: -> | |
JSON.stringify {@x, @y} | |
g = new GameObject() | |
g.move(4, 5) | |
alert g.toString() | |
g | |
.move.to 10, 20 | |
.and.move 10, 10 | |
alert g.toString() | |
class BehaviorGroup | |
constructor: -> | |
@length = 0 | |
@tags = {} | |
@names = {} | |
push: (behavior, tags = behavior.tags) -> | |
return if Object.hasOwnProperty.call @names, behavior.name | |
@[@length] = behavior | |
for tag in tags | |
@tags[tag] = @tags[tag] or [] | |
@tags[tag].push @length | |
@names[behavior.name] = @length | |
++@length | |
pop: -> @[length - 1] | |
splice: -> | |
forEach: (callback) -> | |
for i in [0 .. @length - 1] | |
callback @[i] | |
null | |
byName: (name) -> @[@names[name]] | |
byTag: (tag) -> @tags[tag].map (index) => @[index] | |
bh = new BehaviorGroup() | |
bh.push | |
name: 'abc' | |
tags: ['a', 'b', 'c'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment