0

I'd like to make a Cellular Automaton in C#. This is a fairly easy task, which I almost have no problem with. However I'm getting an awful performance by just drawing rectangles of size one in Windows Forms Application, so my question is: How to draw all the pixels one by one and yet have a good performance?

EDIT: Okay, so this is my code:

public partial class Form1 : Form
{
    Task t;
    const int _numberOfStates = 5;
    const int _resolutionX = 1920, _resolutionY = 1200;
    Color[] states = new Color[_numberOfStates] { Color.Aqua, Color.Green, Color.Orange, Color.Red, Color.Blue };
    Bitmap bmp = new Bitmap(1920, 1200);
    short[,] map = new short[_resolutionX, _resolutionY];
    public Form1()
    {
        InitializeComponent();
        Size = new Size(_resolutionX, _resolutionY);
        Random rand = new Random();
        for (int x = 0; x < _resolutionX; x++)
            for (int y = 0; y < _resolutionY; y++)
                map[x, y] = (short)rand.Next(_numberOfStates);
        t = new Task(() => { MapToBitmap(); IterateMap(); });
        t.Start();
    }
    protected override void OnPaint(PaintEventArgs e)
    {
        t.Wait();
        e.Graphics.DrawImage(bmp, new PointF(0, 0));
        t = new Task(() => { MapToBitmap(); IterateMap(); });
        t.Start();
    }
    void MapToBitmap()
    {
        for (int x = 0; x < _resolutionX; x++)
            for (int y = 0; y < _resolutionY; y++)
                bmp.SetPixel(x, y, states[map[x, y]]);
    }
    void IterateMap()
    {
        for (int x = 0; x < _resolutionX; x++)
            for (int y = 0; y < _resolutionY; y++)
                for (int i = -1; i <= 1; i++)
                    for (int j = -1; j <= 1; j++)
                        if ((i != 0 || j != 0) && x + i >= 0 && x + i <= _resolutionX && y + j >= 0 && y + j <= _resolutionY)
                            map[x, y] = (short)((map[x, y] + 1) % _numberOfStates);
    }
}

Don't bother looking at IterateMap() and MapToBitmap() functions, however my problem now is, the OnPaint function is only called once, so I get only one iteration.
Any idea why?

huB1erTi2
  • 23
  • 5

0 Answers0