views:

116

answers:

4

I'm writing an implementation of Conway's Game of Life in C#. This is the code I'm using to draw the grid, it's in my panel_Paint event. g is the graphics context.

for (int y = 0; y < numOfCells * cellSize; y += cellSize)
{
     for (int x = 0; x < numOfCells * cellSize; x += cellSize)
     {
          g.DrawLine(p, x, 0, x, y + numOfCells * cellSize);
          g.DrawLine(p, 0, x, y + size * drawnGrid, x);
     }
}

When I run my program, it is unresponsive until it finishes drawing the grid, which takes a few seconds at numOfCells = 100 & cellSize = 10. Removing all the multiplication makes it faster, but not by very much.

Is there a better/more efficient way to draw my grid?

Thanks

+1  A: 

Create a bitmap image of, say, 100x100 pixels with the grid lines and display it in tiles.
Make sure that the seam between tiles doesn't cause a discontinuity in the spaces of the grid.

shoosh
+2  A: 

The problem is that you are drawing the X lines for every Y coordinate. You can simplify first by just rendering the Y lines in one loop and then the X lines in another loop.

Here is a quick example

  for (int y = 0; y < numOfCells; ++y)
  {
    g.DrawLine(p, 0, y * cellSize, numOfCells * cellSize, y * cellSize);
  }

  for (int x = 0; x < numOfCells; ++x)
  {
    g.DrawLine(p, x * cellSize, 0, x * cellSize, numOfCells * cellSize);
  }

As you progress, you can use double buffering to reduce any flashing etc. Take a look at Control.SetStyle < br/> http://msdn.microsoft.com/en-us/library/system.windows.forms.control.setstyle.aspx

Chris Taylor
or in the same loop, if the grid is a square ;)
Thomas Levesque
@Thomas, agreed. I struggle with this when answering, my view is that the OP was not seeing the basic problem and that is why I go for the obvious first and then once the problem is understood improve from there. But just an opinion.
Chris Taylor
Ugh, I don't know what I was thinking with the nested loops. Thanks for the help.Enabling double buffering doesn't seem to do anything, but that's okay, there's only a little flickering when I start it up.
Joel
@Joel, you should look at Thomas solution which is even more optimized since it only does one loop rather than the 2 above.
Chris Taylor
@Chris, That's actually the solution I've used, since my grid is a square. However, I chose your solution as the answer since you gave a little more detail.
Joel
+1  A: 

You don't need nested loops :

for (int i = 0; i < numOfCells; i++)
{
    // Vertical
    g.DrawLine(p, i * cellSize, 0, i * cellSize, numOfCells * cellSize);
    // Horizontal
    g.DrawLine(p, 0, i * cellSize, numOfCells * cellSize, i * cellSize);
}
Thomas Levesque
A: 

You should take a look at XNA for this. It would probably be more efficent to do this in a rendered window instead of a WinForm.

XNA is the game framework for C#. Find more information at http://creators.xna.com/

Kurru