Skip to content

Instantly share code, notes, and snippets.

@sapslaj
Created February 2, 2015 21:50
Show Gist options
  • Select an option

  • Save sapslaj/8ad7e6a2708080eb28ff to your computer and use it in GitHub Desktop.

Select an option

Save sapslaj/8ad7e6a2708080eb28ff to your computer and use it in GitHub Desktop.
Basic interface with ROT
require 'map'
class DiggerMap extends Map
_generate: ->
@_create new ROT.Map.Digger()
require 'player'
require 'digger_map'
class @Game
constructor: ->
@display = new ROT.Display()
@map = new DiggerMap(@)
document.body.appendChild @display.getContainer()
@map.draw()
@player = new Player(@, @map)
scheduler = new ROT.Scheduler.Simple()
scheduler.add(@player, true)
@engine = new ROT.Engine(scheduler)
@engine.start()
self = @
@tickInterval = setInterval( () ->
Game.tick(self)
, 100)
@tick: (game) ->
game.map.draw()
class MapCell
constructor: (@x, @y, @type) ->
@_coerceCellContent()
setType: (type) ->
@type = type
@_coerceCellContent()
isFree: ->
true unless @type == 'wall'
_coerceCellContent: ->
@content = switch @type
when 'wall' then ' '
when 'free' then '.'
when 'player' then '@'
class Map
constructor: (@game) ->
@cells = []
@_generate()
indexOf: (x, y) ->
@cells.indexOf(@at(x, y))
at: (x, y) ->
for cell in @cells
if cell.x == x and cell.y == y
return cell
draw: ->
for cell in @cells
@game.display.draw(cell.x, cell.y, cell.content)
findOpenCell: ->
min = 0
max = @cells.length
freeCell = {}
freeCell = @cells[Math.floor(Math.random() * (max - min) + min)] while freeCell.type != 'free'
freeCell
addCell: (x, y, type) ->
if y == undefined
@cells.push x
else
@cells.push(new MapCell(x, y, type))
_generate: ->
@_create(ROT.Map.Arena(ROT.DEFAULT_WIDTH, ROT.DEFAULT_HEIGHT))
_create: (mapGen, callback) ->
self = @
callback = @_generateCallback if callback == undefined
mapGen.create (x, y, wall) -> callback(self, x, y, wall)
_generateCallback: (map, x, y, wall) ->
type =
if wall
'wall'
else
'free'
map.addCell(x, y, type)
require 'map'
class Player
constructor: (@game, @map) ->
freeCell = @map.findOpenCell()
@x = freeCell.x
@y = freeCell.y
@oldtype = @map.at(@x, @y).type
@map.at(@x, @y).setType('player')
act: ->
@game.engine.lock()
window.addEventListener('keydown', @)
handleEvent: (e) ->
keymap = {
37: 3, # Left
38: 0, # Up
39: 1, # Right
40: 2 # Down
}
code = e.keyCode
diff = ROT.DIRS[4][keymap[code]]
newX = @x + diff[0]
newY = @y + diff[1]
if @_canMove(newX, newY)
@updatePosition(newX, newY)
window.removeEventListener('keydown')
updatePosition: (newX, newY) ->
@map.at(@x, @y).setType(@oldtype)
@x = newX
@y = newY
@oldtype = @map.at(newX, newY).type
@map.at(newX, newY).setType('player')
@map.draw()
_canMove: (newX, newY) ->
@map.at(newX, newY).type == 'free'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment