Skip to content

Instantly share code, notes, and snippets.

@iamvery
Created June 3, 2014 18:59
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iamvery/2835d63b1c392883ecab to your computer and use it in GitHub Desktop.
Save iamvery/2835d63b1c392883ecab to your computer and use it in GitHub Desktop.
Game of Life WIP with @nybblr
# Live cells with < 2 living neighbors dies to underpop
# > 3 living neighbors dies to overpop
# Otherwise, lives!
#
# Dead cells with exactly 3 living neighbors is born
# . 0 .
# . 0 .
# . 0 .
#
# . . .
# 0 0 0
# . . .
class Cell
constructor: ({@board, @isLiving, @x, @y}) ->
shouldLive: ->
neighbors = @neighbors()
neighbors = (neigh for neigh in neighbors when neigh.isAlive())
count = neighbors.length
switch
when count < 2
false
when count > 3
false
when count is 3
true
else
@isLiving
isAlive: ->
@isLiving
neighbors: ->
# Neighbor positions
positions = []
for i in [-1, 0, 1]
for j in [-1, 0, 1]
continue if i is 0 and j is 0
positions.push x: @x + i, y: @y + j
# Filter out of bounds
positions = (pos for pos in positions when @board.inBounds(pos))
cells = (@board.cellAt(x: pos.x, y: pos.y) for pos in positions)
draw: ->
if @isLiving
"0"
else
"."
class Board
constructor: ({@width, @height}) ->
@cells = new Array(@width * @height)
@fromPictogram: (pict) ->
lines = pict.split("\n")
tokens = (line.trim().split(" ") for line in lines)
width = tokens[0].length
height = tokens.length
board = new Board
width: width
height: height
tokens = [].concat.apply([], tokens)
cells = for i in [0..tokens.length]
token = tokens[i]
alive = token is "0"
{x, y} = board._indexToPos(i)
new Cell
board: board
isLiving: alive
x: x
y: y
board.populate(cells)
board
_indexToPos: (index) ->
x = index % @width
y = index / @width | 0
x: x, y: y
_posToIndex: ({x, y}) ->
x + y * @width
inBounds: ({x, y}) ->
0 <= x < @width and 0 <= y < @height
cellAt: (pos) ->
@cells[@_posToIndex(pos)]
populate: (cells) ->
@cells = cells
iterate: ->
# Returns a new Board
newBoard = new Board
width: @width
height: @height
newCells = for cell in @cells
new Cell
board: newBoard
x: cell.x
y: cell.y
isLiving: cell.shouldLive()
newBoard.populate(newCells)
newBoard
draw: ->
text = ""
for i in [0..@cells.length]
text += "\n" if i % @width is 0
text += @cells[i].draw() + " "
console.log text
module.exports =
Board: Board
Cell: Cell
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment