一個十分簡單的生命遊戲實例#
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!(" ");
}
}