Skip to content

Instantly share code, notes, and snippets.

@mecampbellsoup
Last active December 24, 2015 23:09
Show Gist options
  • Select an option

  • Save mecampbellsoup/6878532 to your computer and use it in GitHub Desktop.

Select an option

Save mecampbellsoup/6878532 to your computer and use it in GitHub Desktop.
This was the bulk of my logic for coding Conway's Game of Life as I was first learning to code (last week, that is).
# setup code whereby the world of gridsize "x" by "x" cells is
# generated has been omitted for brevity, but know that the world
# argument below refers to an array of arrays giving us a 2D 'map'
# of sorts full of cells; if a cell's value == 1, that cell is alive;
# if its value == 0, that cell is dead. whether a cell lives or dies
# in the next generation of life depends solely on its # of neighbors
# and that logic is contained below.
def run_generation_of_life(world)
new_world = []
world.each_with_index do |row, row_index|
new_world_row = []
row.each_with_index do |cell, column_index|
if cell == 1
if neighbors(row_index, column_index, world).size > 3 || neighbors(row_index, column_index, world).size < 2
cell = 0
new_world_row << cell
elsif [2,3].include? neighbors(row_index,column_index,world).size
cell = 1
new_world_row << cell
end
elsif cell == 0 # if cell is dead...
if neighbors(row_index,column_index,world).size == 3
cell = 1
new_world_row << cell
else
cell = 0
new_world_row << cell
end
end
end
new_world << new_world_row
end
new_world
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment