Skip to content

Instantly share code, notes, and snippets.

@levicole
Created July 13, 2011 19:15
Show Gist options
  • Save levicole/1081087 to your computer and use it in GitHub Desktop.
Save levicole/1081087 to your computer and use it in GitHub Desktop.
class Grid
constructor: (@heightInCells, @widthInCells, @cellSize, canvas) ->
@canvas = canvas
@canvas.width = @widthInCells * @cellSize
@canvas.height = @heightInCells * @cellSize
@ctx = @canvas.getContext("2d")
@cells = @initializeCells()
initializeCells: ->
rows = (((new Cell(x,y,'dead',@)) for x in [0..(@widthInCells-1)]) for y in [0..(@heightInCells-1)])
seed: ->
x = (Math.floor(Math.random() * @widthInCells))
y = (Math.floor(Math.random() * @heightInCells))
cell = @cells[y][x]
cell.revive() if cell.state != 'alive'
drawCells: ->
(cell.draw() for cell in row for row in @cells)
step: ->
@ctx.clearRect(0, 0, @canvas.width, @canvas.height)
cell.applyRules() for cell in row for row in @cells
@drawCells()
class Cell
constructor: (@x, @y, @state='dead', @grid) ->
revive: ->
@state = 'alive'
isAlive: =>
@state == 'alive'
draw: ->
if @isAlive()
@grid.ctx.fillRect(@x*@grid.cellSize, @y*@grid.cellSize, @grid.cellSize, @grid.cellSize)
applyRules: ->
neighbors = {}
neighbors['n'] = @grid.cells[@y-1][@x] if @y > 0
neighbors['s'] = @grid.cells[@y+1][@x] if @y < @grid.heightInCells - 1
neighbors['e'] = @grid.cells[@y][@x+1] if @x < @grid.widthInCells - 1
neighbors['w'] = @grid.cells[@y][@x-1] if @x > 0
neighbors['ne'] = @grid.cells[@y-1][@x+1] if @y > 0 && @x < @grid.widthInCells - 1
neighbors['nw'] = @grid.cells[@y-1][@x-1] if @y > 0 && @x < 0
neighbors['se'] = @grid.cells[@y+1][@x+1] if @x < @grid.widthInCells - 1 && @y < @grid.heightInCells - 1
neighbors['sw'] = @grid.cells[@y+1][@x-1] if @y < @grid.heightInCells - 1 && @x > 0
livingNeighbors = (cell for cell in neighbors when cell.isAlive())
if @isAlive()
if livingNeighbors <= 1 || livingNeighbors >= 4
@state = 'dead'
if livingNeighbors is 2 || livingNeighbors is 3
@revive()
else
if livingNeighbors.length is 3
@revive()
$ ->
canvas = (document.getElementById "gol")
grid = new Grid(30, 30, 5, canvas)
ctx = grid.ctx
grid.seed() for x in [0..100]
grid.drawCells()
grid.cells[1][1].applyRules()
# setInterval((-> grid.step()), 1000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment