Skip to content

Instantly share code, notes, and snippets.

@clooth
Created August 28, 2012 10:57
Show Gist options
  • Save clooth/3497201 to your computer and use it in GitHub Desktop.
Save clooth/3497201 to your computer and use it in GitHub Desktop.
Tile engine draft
clone = (obj) ->
if not obj? or typeof obj isnt 'object'
return obj
if obj instanceof Date
return new Date(obj.getTime())
if obj instanceof RegExp
flags = ''
flags += 'g' if obj.global?
flags += 'i' if obj.ignoreCase?
flags += 'm' if obj.multiline?
flags += 'y' if obj.sticky?
return new RegExp(obj.source, flags)
newInstance = new obj.constructor()
for key of obj
newInstance[key] = clone obj[key]
return newInstance
class Point
constructor: (@x, @y) ->
class Vector
constructor: (@x = 0, @y = 0, @z = 0) ->
class Rectangle
constructor: (@x = 0, @y = 0, @width = 0, @height = 0) ->
class TileEngine
class TileEngine.Engine
@tileWidth
@tileHeight
constructor: (width, height) ->
Engine.tileWidth = width
Engine.tileHeight = height
@vectorToCell: (position) ->
new Point position.x / @tileWidth, position.y / @tileHeight
class Tileset
constructor: (@image, @tilesWide, @tilesHigh, @tileWidth, @tileHeight) ->
@tileRectangles = []
tileCount = tilesWide * tilesHigh
tileIndex = 0
for y in [0..@tilesHigh]
for x in [0..@tilesWide]
tileRectangles[tileIndex] = new Rectangle(
x * @tileWidth,
y * @tileHeight,
@tileWidth,
@tileHeight
)
tileIndex++
class Tile
constructor: (@tileIndex, @tileset) ->
class MapLayer
constructor: (width, height) ->
if typeof width is "object"
@map = []
for y in [0...height]
for x in [0...width]
@map[y][x] = new Tile 0, 0
else
@map = width
width: () -> @map[1].length
height: () -> @map[0].length
getTile: (x, y) ->
@map[x][y]
setTile: (x, y, tile, tileset) ->
@map[x][y] = if tileset then new Tile(tile, tileset) else tile
class TileMap
constructor: (tilesets, layers) ->
@tilesets = if typeof tilesets.length is "undefined" then [tilesets] else tilesets
@mapLayers = if typeof layers.length is "undefined" then [layers] else layers
render: (canvas) ->
@canvas = canvas
@context = canvas.getContext '2d'
destination = new Rectangle 0, 0, Engine.tileWidth, Engine.tileHeight
for layer in @mapLayers
for y in [0..layer.height()]
destination.y = y * Engine.tileHeight
for x in [0..layer.width()]
tile = layer.getTile x, y
tileset = @tilesets[tile.tileset]
rectangle = tileset.tileRectangles[tile.tileIndex]
destination.x = x * Engine.tileWidth
canvas.drawImage(
tileset.image,
rectangle.x,
rectangle.y,
rectangle.width,
rectangle.height,
destination.x,
destination.y,
destination.width,
destination.height
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment