一个十分简单的生命游戏实例#
fn main() {
// 初始化世界
let mut map: [[i32; 12]; 12] = [[0; 12]; 12];
// 初始化数据
map = lode(map);
let mut loop_num: u32 = 0;
while loop_num != 6 {
// 进行判断
map = comput(map);
// 绘制世界
display(map);
loop_num += 1;
}
}
fn lode(data: [[i32; 12]; 12]) -> [[i32; 12]; 12] {
let mut _data: [[i32; 12]; 12] = data;
// 初始化生命数据
_data[1][2] = 1;
_data[1][3] = 1;
_data[3][1] = 1;
_data[3][2] = 1;
_data[3][3] = 1;
_data
}
fn comput(data: [[i32; 12]; 12]) -> [[i32; 12]; 12] {
let mut _data: [[i32; 12]; 12] = data;
for h in 0..12 {
for w in 0..12 {
// 设定变量储存周边生命
let mut state :i32 = 0;
// 探测生命
if !(h==0 || w==0) {
state = state + _data[h-1][w-1];
}
if !(h==0) {
state = state + _data[h-1][w];
}
if !(h==0 || w==11) {
state = state + _data[h-1][w+1];
}
if !(w==0) {
state = state + _data[h][w-1];
}
if !(w==11) {
state = state + _data[h][w+1];
}
if !(h==11 || w==0) {
state = state + _data[h+1][w-1];
}
if !(h==11) {
state = state + _data[h+1][w];
}
if !(h==11 || w==11) {
state = state + _data[h+1][w+1];
}
if state > 3 || state < 2 {
_data[h][w] = 0;
} else if state == 3 {
_data[h][w] = 1;
}
}
}
_data
}
fn display(_data: [[i32; 12]; 12]) {
for h in 0..12 {
for w in 0..12 {
if _data[h][w] == 1 {
print!(" # ");
} else {
print!(" ");
}
}
println!(" ");
}
}