Commit 9a5516a

mo khan <mo@mokhan.ca>
2014-12-31 04:07:12
extract each.
1 parent f233e93
src/cell.c
@@ -16,3 +16,7 @@ Cell* cell_create(int number_of_cells) {
 int cell_alive(Cell *cell) {
   return cell->alive ? 1 : 0;
 };
+
+void cell_change_life(Cell *cell, bool alive) {
+  cell->alive = alive;
+}
src/cell.h
@@ -6,3 +6,4 @@ typedef struct {
 
 Cell* cell_create(int number_of_cells);
 int cell_alive(Cell *cell);
+void cell_change_life(Cell *cell, bool alive);
src/world.c
@@ -74,15 +74,19 @@ World* world_create(int width, int height) {
   return world;
 }
 
-int random_life() {
-  return rand() % 2 == 0 ? true : false;
+void world_each(World *world, each_cell callback){
+  for (int i = 0; i < world_number_of_cells(world); i++) {
+    callback(&world->cells[i]);
+  }
+}
+
+void choose_random_life(Cell *cell){
+  cell_change_life(cell, rand() % 2 == 0 ? true : false);
 }
 
 World* world_random(int width, int height){
   World *world = world_create(width, height);
-  for (int i = 0; i < world_number_of_cells(world); i++) {
-    world_cell_at(world, i)->alive = random_life();
-  }
+  world_each(world, choose_random_life);
   return world;
 }
 
src/world.h
@@ -6,6 +6,8 @@ typedef struct {
   Cell* cells;
 } World;
 
+typedef void (*each_cell)(Cell *cell);
+
 World* world_create(int width, int height);
 World* world_random(int width, int height);
 World* world_evolve(World* world);