examples/apps/csharp/life/src/life_board.cs

165 lines
3.4 KiB
C#

using System;
public class LifeBoard
{
public const int Width = 47;
public const int Height = 31;
public static int IndexForPosition(int x, int y)
{
return y * Width + x;
}
public bool[] Cells
{
get { return board; }
}
private int gen = 0;
private bool[] board;
private bool[] board1, board2;
private efl.ILoop_Timer lifeTimer = null;
private LifeRender lifeRender = null;
private void CellOn(int x, int y)
{
board1[IndexForPosition(x, y)] = true;
}
private void BoardSetup()
{
// glide
CellOn(16, 1);
CellOn(17, 2);
CellOn(18, 2);
CellOn(16, 3);
CellOn(17, 3);
// oscilate
CellOn(22, 15);
CellOn(23, 15);
CellOn(24, 15);
// block
CellOn(32, 15);
CellOn(33, 15);
CellOn(32, 16);
CellOn(33, 16);
}
public LifeBoard()
{
board1 = new bool[Height * Width];
board2 = new bool[Height * Width];
BoardSetup();
board = board1;
}
public void Run(efl.ui.IWin win)
{
lifeTimer = new efl.Loop_Timer(win, (efl.ILoop_Timer etimer) => {
etimer.SetInterval(0.1);
});
lifeTimer.TickEvt += (object sender, EventArgs ev) => {
Nextgen();
if (this.lifeRender != null)
this.lifeRender.Refresh(win);
};
}
public int SumAround(int x, int y)
{
int i, sum = 0;
int max = Width * Height;
i = IndexForPosition(x - 1, (y - 1));
if (i >= 0 && board[i])
++sum;
++i;
if (i >= 0 && board[i])
++sum;
++i;
if (i >= 0 && board[i])
++sum;
i = IndexForPosition(x - 1, y);
if (i >= 0 && board[i])
++sum;
i += 2;
if (i < max && board[i])
++sum;
i = IndexForPosition(x - 1, (y + 1));
if (i < max && board[i])
++sum;
++i;
if (i < max && board[i])
++sum;
++i;
if (i < max && board[i])
++sum;
return sum;
}
public void Nextgen()
{
bool[] work = null;
++gen;
if (board == board1)
work = board2;
else
work = board1;
for (int y = 0; y < Height; y++)
for (int x = 0; x < Width; x++)
{
int i = IndexForPosition(x, y);
int n = SumAround(x, y);
if (board[i])
{
if (n > 3 || n < 2)
work[i] = false;
else
work[i] = true;
}
else
{
if (n == 3)
work[i] = true;
else
work[i] = false;
}
}
board = work;
}
public void TogglePause(efl.ui.IWin win)
{
if (lifeTimer != null)
{
lifeTimer.SetParent(null);
lifeTimer.Dispose();
lifeTimer = null;
Console.WriteLine("Paused.");
}
else
{
Run(win);
Console.WriteLine("Restarted.");
}
}
public void SetRender(LifeRender render)
{
lifeRender = render;
}
}