-
-
Save olabini/322823 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
GameOfLife = Origin mimic do( | |
initialize = method(rows:, columns:, | |
@grid = Grid withDimensions(rows, columns)) | |
evolve = method( | |
nextGrid = grid blankGrid | |
grid filter(numLiveNeighbours in?(2..3)) each(cellInfo, nextGrid spawnCell(cellInfo coords first, cellInfo coords second)) | |
@grid = nextGrid | |
) | |
spawn = method(row, col, | |
grid tap(spawn(row, col))) | |
) | |
GameOfLife Grid = Origin mimic do( | |
appendMimic!(Mixins Sequenced) | |
Cell = Origin mimic | |
withDimensions = method(rows, columns, | |
with( | |
state: Dict withDefault(0), | |
numCols: columns, | |
maxRowIdx: rows - 1, | |
maxColIdx: columns - 1 | |
) | |
) | |
blankGrid = method(with(state: Dict withDefault(0))) | |
spawnCell = method(row, col, state[[row, col]] = 1) | |
seq = macro(allCells seq) | |
;internal methods | |
permutations = method(a, b, a flatMap(i, b map(j, (i,j)))) | |
countLiveNeighbours = method("Count the number of live neighbours for a given set of cell coordinates", | |
row, col, | |
neighbourCoords = permutations((-1..1), (-1..1)) - [(0,0)] | |
neighbourCoords inject(0, sum, (r_mod,c_mod), state[[row + r_mod, col + c_mod]] + sum)) | |
allCellCoords = method("Generate a list tuples representing all the coordinates of the cells in the Grid", | |
permutations(0..maxRowIdx, 0..maxColIdx)) | |
allCells = method("Generate a list of all the cells in the Grid consisting of coordinates and number of live neighbours", | |
allCellCoords map((row, col), Cell with(coords: (row, col), numLiveNeighbours: countLiveNeighbours(row, col)))) | |
;for output purposes | |
asList = method("Returns the list of cells as a list of 0s and 1s, with 1 representing a live cell", | |
rowsOfCoords = allCellCoords seq sliced(numCols) | |
cellList = [] | |
while(rowsOfCoords next?, cellList << (rowsOfCoords next map((row, col), state[[row,col]])))) | |
asText = method("Returns the list of cells in a pretty ascii art representation", | |
"\n+-#{"--" * (numCols)}+\n| #{asList map(map(i, if(i == 0, " ", "* ")) join) join("|\n| ")}|\n+-#{"--" * (numCols)}+") | |
) | |
System ifMain( | |
life = GameOfLife mimic(rows: 5, columns: 6) | |
life grid spawnCell(1,0) | |
life grid spawnCell(1,1) | |
life grid spawnCell(1,2) | |
life grid spawnCell(1,3) | |
life grid spawnCell(1,4) | |
life grid spawnCell(1,5) | |
life grid asText println | |
10 times(life evolve asText println) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment