Skip to content

Instantly share code, notes, and snippets.

@frostney
Created May 7, 2014 21:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save frostney/b179a80bfea5d19f50e7 to your computer and use it in GitHub Desktop.
Save frostney/b179a80bfea5d19f50e7 to your computer and use it in GitHub Desktop.
Prototyping GameObjects with fluent APIs and tagged behaviors in a group
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