Newer
Older
for y in 0..life.size_cells {
for x in 0..life.size_cells {
if rand::thread_rng().gen_bool(0.5) {
life.set_fill(x, y, Color32::BLACK);
}
}
}
// This would replace the grid with a single oscillator.
/*
life.clear_fill();
life.set_fill(5, 5, Color32::BLACK);
life.set_fill(6, 5, Color32::BLACK);
life.set_fill(7, 5, Color32::BLACK);
*/
Self {
life,
governor: Governor::default(),
}
}
Frame::none().margin(Margin::same(20.0)).show(ui, |ui| {
ui.vertical_centered(|ui| {
ui.heading("Cellular Automata");
});
});
// Need to continuously animate the grid, or at least poll the governor.
if self.governor.ready(ui.ctx().input().time, 0.2) {
/// Run one iteration of Conway's Game of Life on the grid, producing a new grid.
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
let mut new = grid.clone();
new.clear_fill();
for cy in 0..grid.size_cells {
for cx in 0..grid.size_cells {
let mut neighbors = 0;
for dy in -1..=1 {
for dx in -1..=1 {
let (x, y) = match (cx.checked_add_signed(dx), cy.checked_add_signed(dy)) {
(Some(x), Some(y)) if x < grid.size_cells && y < grid.size_cells => (x, y),
_ => continue,
};
if x == cx && y == cy {
// Don't consider self.
continue;
}
if grid.fill(x, y).a() > 0 {
neighbors += 1;
}
}
}
let mut alive = grid.fill(cx, cy).a() > 0;
alive = match (alive, neighbors) {
(false, 3) => true,
(false, _) => false,
(true, 2) | (true, 3) => true,
(true, _) => false,
};
new.set_fill(
cx,
cy,
if alive {
Color32::BLACK
} else {
Color32::TRANSPARENT
},
);
}
}
new
}