Skip to content

Instantly share code, notes, and snippets.

@reinh
Last active December 15, 2015 08:19
Show Gist options
  • Save reinh/5229849 to your computer and use it in GitHub Desktop.
Save reinh/5229849 to your computer and use it in GitHub Desktop.
class @Engine
constructor: (@world, @context) ->
{height: height, width: width} = @world.dimensions
Backbone.on 'move', (args...) => @move args...
@player = @world.player
@display = new Display(rows: height, columns: width)
actors = [@player, new Random(10,10, @)]
@scheduler = new Scheduler(actors)
actor.draw() for actor in actors
run: =>
@display.render()
new Turn(@, @scheduler.next()).run()
move: (actor, dx, dy) =>
[x,y] = [actor.x+dx, actor.y+dy]
unless @world.isBlocked x, y
@display.set x, y, actor.char
@world.redraw actor.x, actor.y
actor.x = x
actor.y = y
class @Player extends Actor
char: '@'
act: (turn) ->
super
turn.context.one 'keyup', (e) =>
dir = switch e.which
when Keys.H then [-1, 0]
when Keys.J then [ 0, 1]
when Keys.K then [ 0, -1]
when Keys.L then [ 1, 0]
else null
if dir?
Backbone.trigger 'move', @, dir...
turn.end()
else
turn.redo()
class @Scheduler
constructor: (@items) -> @index = 0
next: ->
item = @items[@index]
@index++
@index = 0 if @index >= @items.length
return item
class @Turn
constructor: (@engine, @actor) ->
@context = $(window)
@promise = $.Deferred()
@promise.fail @retry
@promise.done @finish
end: -> @promise.resolve()
redo: -> @promise.reject()
run: => @actor.act @
retry: => new Turn(@engine, @actor).run()
finish: =>
@actor.draw()
@engine.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment