Njdart
Njdart

Reputation: 312

indirectly draw to panel from another function

I am creating Conway's Game of life in C# and everything works fine, except the refreshing of the panel to display the next generation. I can draw to the panel to establish grid lines for the cells, place and destroy "life" using simWindow_Paint and simWindow_MouseClick but at present i cannot update it.

private void updateGame(){

    int living = 0;
    int dead = 0;

    for(int i = 1; i < gameHeight; i++)
        for (int j = 1; j < gameWidth; j++){

            //set cell location and size
            Rectangle cell = new Rectangle();
            cell.Height = cell.Width = 9;
            int X = j - 1;
            int Y = i - 1;
            cell.X = Convert.ToInt32(X * 10 + 1);
            cell.Y = Convert.ToInt32(Y * 10 + 1);

            using (Graphics g = this.simWindow.CreateGraphics()){
                if (gameArray[i, j] == true){
                    Brush brush = new SolidBrush(Color.Red);
                    g.FillRectangle(brush, cell);
                   ++living;
                } else {
                    Brush brush = new SolidBrush(Color.White);
                    g.FillRectangle(brush, cell);
                    ++dead;
                }
            }
        }
    }

I am not sure if what i am attempting to do is possible in C#, I have already done this in Pascal, but i am not sure if C# works the same way...

Upvotes: 0

Views: 351

Answers (2)

Matt Burland
Matt Burland

Reputation: 45155

Difficult to say with what you've shown us, but I suspect the problem might be in your simWindow_Paint method. This is (presumably) responding to the paint event for your panel and I suspect what you are doing is overwriting (or over painting) all the drawing you are doing in your updateGame() method.

All the drawing should be done in your paint handler. So you paint handler should know the state of the game and draw it accordingly. Your updateGame() method should just update the state of the game and then invalidate the panel (forcing a repaint).

Upvotes: 1

Peter Ritchie
Peter Ritchie

Reputation: 35869

I recommend you review the following documentation on custom painting in WinForms: http://msdn.microsoft.com/en-us/library/kxys6ytf.aspx

Upvotes: 0

Related Questions