rust game of life学后感
- 背景
- 介绍
- 做法
- 结果
背景
这个是一个有趣的可视化demo,初衷是为了通过学习他掌握rust
介绍
let live_neighbours = self.live_neighbour_count(row, col);
next[idx] = match (cell, live_neighbours) {
(Cell::Alive, x) if x < 2 => Cell::Dead,
(Cell::Alive, 2) | (Cell::Alive, 3) => Cell::Alive,
(Cell::Alive, x) if x > 3 => Cell::Dead,
(Cell::Dead, 3) => Cell::Alive,
(otherwise, _) => otherwise,
};
这个实际上是做了个小视频,你假定无限个格子,根据当前格子的状态和周边八个格子的状态,决定下一帧他是个什么状态,连续的改变会看起来很有意思
上面的代码这样翻译为规则
C 当前
N 邻居
如果C存活,且邻居有两个以下活着,他会死
如果C存活,邻居有2或者3个活着,他下一帧没事
如果C存活,邻居大于3个活着,他会死
如果他死了,邻居有3个活着,他会下一帧复活
做法
初始化格子,给几个位置0 其他的1,然后进入tick开始迭代
pub fn tick(&mut self) {
let mut next = self.cells.clone();
for row in 0..self.height {
for col in 0..self.width {
let idx = self.get_index(row, col);
let cell = self.cells[idx];
let live_neighbours = self.live_neighbour_count(row, col);
next[idx] = match (cell, live_neighbours) {
(Cell::Alive, x) if x < 2 => Cell::Dead,
(Cell::Alive, 2) | (Cell::Alive, 3) => Cell::Alive,
(Cell::Alive, x) if x > 3 => Cell::Dead,
(Cell::Dead, 3) => Cell::Alive,
(otherwise, _) => otherwise,
};
}
}
self.cells = next;
}
结果
学完之后,对rust熟练度+0.01
不过这个可以之后体验compute shader实现一下
我看的B站视频 https://www.bilibili.com/video/BV16r4y1c7mT/?spm_id_from=333.999.0.0