Skip to content

Instantly share code, notes, and snippets.

@j4mie
Created July 31, 2011 09:02
Show Gist options
  • Save j4mie/1116622 to your computer and use it in GitHub Desktop.
Save j4mie/1116622 to your computer and use it in GitHub Desktop.
Conway's Life in CoffeeScript and Processing.js
<!DOCTYPE html>
<title>CoffeeScript/Processing</title>
<script src="https://raw.github.com/jeresig/processing-js/master/processing.js"></script>
<script src="https://raw.github.com/jashkenas/coffee-script/master/extras/coffee-script.js"></script>
<script src="https://raw.github.com/gist/1114064/professing.js"></script>
<script type="text/coffeescript">
sketch ->
grid = []
# Settings
# --------
CANVAS_SIZE = 300 # number of pixels along each side of the canvas
GRID_SIZE = 30 # number of cells per side
FRAMES_PER_SECOND = 10
GRID_COLOUR = 100
ON_COLOUR = 0
OFF_COLOUR = 255
# Processing main functions
# -------------------------
@setup = =>
@size CANVAS_SIZE, CANVAS_SIZE
@background 255
@noFill()
@stroke GRID_COLOUR
@strokeWeight 0.2
@frameRate FRAMES_PER_SECOND
grid = createRandomGrid GRID_SIZE
@draw = =>
grid = computeNextGrid grid
render grid
# Grid creation/manipulation functions
# ------------------------------------
createRandomGrid = (size) =>
randomBoolean() for y in [0...size] for x in [0...size]
randomBoolean = =>
(@random 1) > 0.5
computeNextGrid = (grid) =>
computeNextValueForCell x, y, grid for y in [0...grid.length] for x in [0...grid.length]
# Game of Life rules
computeNextValueForCell = (x, y, grid) =>
livingNeighbourCount = countLivingNeighbours x, y, grid
return grid[x][y] if livingNeighbourCount is 2
return on if livingNeighbourCount is 3
return off
countLivingNeighbours = (x, y, grid) =>
total = 0
for [offsetX, offsetY] in getNeighbourOffsets()
neighbourX = calculateNeighbourCoordinate x, offsetX, grid.length
neighbourY = calculateNeighbourCoordinate y, offsetY, grid.length
total++ if grid[neighbourX][neighbourY]
return total
getNeighbourOffsets = =>
return getNeighbourOffsets.offsets ? do =>
offsets = []
(offsets.push [x, y] if not (x is 0 and y is 0)) for y in [-1..1] for x in [-1..1]
getNeighbourOffsets.offsets = offsets # memoise
calculateNeighbourCoordinate = (coordinate, offset, gridSize) =>
return @abs (coordinate + offset + gridSize) % gridSize # toroidal grid
# Rendering/drawing functions
# ---------------------------
render = (grid) =>
drawCell x, y, grid[x][y] for y in [0...grid.length] for x in [0...grid.length]
drawCell = (x, y, alive) =>
cellSize = CANVAS_SIZE / GRID_SIZE
@fill if alive then ON_COLOUR else OFF_COLOUR
@rect x * cellSize, y * cellSize, cellSize, cellSize
</script>
@j4mie
Copy link
Author

j4mie commented Jul 31, 2011

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment