1: public class Cell //: Life
2: {
3: protected World CurrentWorld { get; private set; }
4: internal int PosX = 0;
5: internal int PosY = 0;
6: private const double InitAliveProbability = 0.2D;
7: private static Random _rnd = new Random();
8: public Cell(World world, int posX, int posY) //: base(world, posX, posY)
9: {
10: this.CurrentWorld = world;
11: // setup world
12: this.PosX = posY;
13: this.PosY = posY;
14: this.CurrentWorld.PutOn(this, posX, posY);
15: this.IsAlive = (_rnd.NextDouble() < InitAliveProbability);
16: }
17: public bool IsAlive { get; private set; }
18: protected IEnumerable<Cell> FindNeighbors()
19: {
20: foreach (Cell item in new Cell[] {
21: this.CurrentWorld.GetCell(this.PosX -1, this.PosY-1),
22: this.CurrentWorld.GetCell(this.PosX, this.PosY-1),
23: this.CurrentWorld.GetCell(this.PosX+1, this.PosY-1),
24: this.CurrentWorld.GetCell(this.PosX-1, this.PosY),
25: this.CurrentWorld.GetCell(this.PosX+1, this.PosY),
26: this.CurrentWorld.GetCell(this.PosX-1, this.PosY+1),
27: this.CurrentWorld.GetCell(this.PosX, this.PosY+1),
28: this.CurrentWorld.GetCell(this.PosX+1, this.PosY+1)})
29: {
30: if (item != null) yield return item;
31: }
32: yield break;
33: }
34: public void OnNextStateChange()
35: {
36: int livesCount = 0;
37: foreach (Cell item in this.FindNeighbors())
38: {
39: if (item.IsAlive == true) livesCount++;
40: }
41: if (this.IsAlive == true && livesCount <1)
42: {
43: //孤單死亡:如果細胞的鄰居小於一個,則該細胞在下一次狀態將死亡。
44: this.IsAlive = false;
45: }
46: else if (this.IsAlive == true && livesCount >= 4)
47: {
48: //擁擠死亡:如果細胞的鄰居在四個以上,則該細胞在下一次狀態將死亡。
49: this.IsAlive = false;
50: }
51: else if (this.IsAlive == true && (livesCount == 2 || livesCount == 3))
52: {
53: //穩定:如果細胞的鄰居為二個或三個,則下一次狀態為穩定存活。
54: //this.IsAlive = true;
55: }
56: else if (this.IsAlive == false && livesCount == 3)
57: {
58: //復活:如果某位置原無細胞存活,而該位置的鄰居為三個,則該位置將復活一細胞。
59: this.IsAlive = true;
60: }
61: else
62: {
63: // ToDo: 未定義的狀態? assert
64: }
65: }
66: }