-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlife.rs
More file actions
144 lines (122 loc) · 2.55 KB
/
life.rs
File metadata and controls
144 lines (122 loc) · 2.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
use std::libc::funcs::posix88::unistd::sleep;
use std::int;
enum Cell {
dead = 0,
live = 1
}
struct Grid {
cells: ~[Cell],
width: uint,
height: uint
}
fn uint_to_cell(u: uint) -> Cell {
match u {
0 => { dead }
1 => { live }
_ => { fail!("Invalid Cell value"); }
}
}
fn Grid(c: ~[Cell], w:uint, h:uint) -> ~Grid {
~Grid {
cells: c,
width: w,
height: h
}
}
type Point = (int, int);
type WrappedPoint = (uint, uint);
fn main() {
let mut grid = Grid(
[0,0,1,0,0,
0,0,0,1,0,
0,1,1,1,0,
0,0,0,0,0,
0,0,0,0,0].map(|c| uint_to_cell(*c)), 5, 5);
print_grid(grid);
loop {
unsafe { sleep(1); }
grid = evolve(grid);
print_grid(grid);
}
}
fn neighbours(c: &Point) -> ~[Point] {
match *c {
(x, y) => {
~[(x-1,y-1), (x,y-1), (x+1,y-1),
(x-1,y ), (x+1,y ),
(x-1,y+1), (x,y+1), (x+1,y+1),
]}
}
}
fn at(g: &Grid, c: &Point) -> Cell {
match *wrap(c, g) {
(x, y) => {
g.cells[y * g.width + x]
}
}
}
fn wrap(c: &Point, g: &Grid) -> ~WrappedPoint {
match *c {
(x, y) => { ~((nwrap(x, g.width)),
(nwrap(y, g.height)))
}
}
}
fn nwrap(x: int, w: uint) -> uint {
let r = x % (w as int);
return if r < 0 {
(r + (w as int)) as uint
} else {
r as uint
}
}
fn density(g: &Grid, c: &Point) -> uint {
neighbours(c).map(|n| at(g, n)).foldl(0, |a, i| {*a + (*i as uint)})
}
fn survives(g: &Grid, c:&Point) -> Cell {
let d = density(g, c);
match at(g, c) {
dead => {
match d {
3 => { live }
_ => { dead }
}
}
live => {
match d {
2 | 3 => { live }
_ => { dead }
}
}
}
}
fn all_points(g: &Grid) -> ~[Point]
{
let mut coords: ~[Point] = ~[];
for int::range(0, g.height as int) |y| {
for int::range(0, g.width as int) |x| {
coords += [(x, y)];
}
}
return coords;
}
fn evolve(g: &Grid) -> ~Grid {
~Grid {
cells: all_points(g).map( |c| survives(g, c) ),
width: g.width,
height: g.height
}
}
fn print_grid(g: &Grid)
{
for all_points(g).each |c| {
match *c {
(0, _) => {println("")}
_ => {}
}
match at(g, c) {
dead => {print("-")}
live => {print("*")}
}
}
}