Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 70 lines (57 sloc) 1.623 kb
217b046c »
2012-01-30 add in more stuffs
1 "use strict"
2
3 initGrid = (size) ->
4 grid = []
5 for i in [0...size]
6 grid[i] = []
7 for j in [0...size]
8 grid[i][j] = 0
9 return grid
10
11 isInBounds = (grid, x, y) ->
12 xLen = grid.length
13 yLen = grid[0].length
14 return ((0 <= x < xLen) and (0 <= y < yLen))
15
16 numberOfNeighbors = (grid, x, y) ->
17 neighbors = 0
18 surroundings = [
19 [-1, -1], [0, -1], [1, -1],
20 [-1, 0], [1, 0],
21 [-1, 1], [0, 1], [1, 1]
22 ]
23
24 for pair in surroundings
25 if isInBounds(grid, x+pair[0], y+pair[1]) and grid[x+pair[0]][y+pair[1]]
26 neighbors++
27
28 return neighbors
29
30 class Board
31 constructor: (@size) ->
32 @grid = initGrid(@size)
33 @nextTickGrid = initGrid(@size)
34
35 tick: ->
36 for x in [0...@size]
37 for y in [0...@size]
38 neighbors = numberOfNeighbors(@grid, x, y)
39 # If cell is currently alive
40 if @getCell(x, y)
41 if neighbors < 2
42 @nextTickGrid[x][y] = 0
43 else if neighbors == 2 or neighbors == 3
44 @nextTickGrid[x][y] = 1
45 else
46 # Overcrowded, so dies out
47 @nextTickGrid[x][y] = 0
48 else
49 # Cell is dead, so it may become alive
50 if neighbors == 3
51 @nextTickGrid[x][y] = 1
52
53 @grid = @nextTickGrid
54 @nextTickGrid = initGrid(@size)
55
56 reset: ->
57 for x in [0...@size]
58 for y in [0...@size]
59 @setCell(x, y, 0)
60
61 getCell: (x, y) ->
62 throw new Error("out of bounds") if not isInBounds(@grid, x, y)
63 return @grid[x][y]
64
65 setCell: (x, y, val) ->
66 throw new Error("out of bounds") if not isInBounds(@grid, x, y)
67 @grid[x][y] = val
68
69 module.exports = Board
Something went wrong with that request. Please try again.