Search code examples
c#monogame

How to make a 2d grid with c#


I want to start making 2d simulations like conway's game of life, pathfinding and sand simulations and so.. I understand the concept and that I have to make a grid... The thing is that i can't find how to make a grid.. I have tried searching and I don't seem to find a proper tutorial or something helpful... I am using monogame framework and have some knowledge with c#. I just want to understand how to make one so i can use it to make simulations if someone can break it down for me or give me an existing tutorial I'll be thankful.


Solution

  • A grid is implemented in an array of simple values(byte, uint, float...) or objects depending on complexity.

    For pathfinding, it is not uncommon to use a parallel grid for indication of visited or changed nodes.

    Game of life example:

    // class level variables 
    const int WIDTH = 32;
    const int HEIGHT = 32;
    byte[,] Grid = new byte[WIDTH,HEIGHT]; // byte is 1/4 smaller than bool
    byte[,] NextGrid = new byte[WIDTH,HEIGHT];
    // 1 is alive 0 is dead
    
    //in Initialize()
    
    // build a period 2 Blinker
    Grid[5,4] = 1;
    Grid[5,5] = 1;
    Grid[5,6] = 1;
    
    
    //in Update()
    // follow row major form and  count the 8 possible live neighbors
    for (int y=0;y<HEIGHT;y++)
       for (int x=0;x<WIDTH;x++)
       {
          byte nLiveCount = 0;
          if(x > 0) // left 3
          {
             nLiveCount += Grid[x-1,y];
             if(y > 0)
                nLiveCount += Grid[x-1,y-1];
             if(y < HEIGHT - 1)
                nLiveCount += Grid[x-1,y+1];
          }
          if(x < WiDTH - 1) // right 3
          {
             nLiveCount += Grid[x+1,y];
             if(y > 0)
                nLiveCount += Grid[x+1,y-1];
             if(y < HEIGHT - 1)
                nLiveCount += Grid[x+1,y+1];
          }
          if(y < HEIGHT - 1) // above
             nLiveCount += Grid[x,y+1];
          if(y > 0) // below
             nLiveCount += Grid[x,y-1];
    
          if(Grid[x,y]== 1) // test live
          {
             if((nLiveCount == 2 || nLiveCount ==3))
                NextGrid[x,y] = 1;
          }   
          else
             if(nLiveCount == 3) // birth
                NextGrid[x,y] = 1;
       }
    Grid = NextGrid;
    NextGrid = new byte[WIDTH,HEIGHT]; // Ready nextGrid for next step
    
    // in Draw()
    
    // this assumes 2 loaded 8x8 textures called black and white
    for (int y=0;y<HEIGHT;y++)
       for (int x=0;x<WIDTH;x++)
          spriteBatch.Draw((Grid[x,y]==1)?black:white, new Vector2(8 * x, 8 * y), Color.White);
    
    // could be simplified to a single white texture 8x8 with:
    //spriteBatch.Draw(white, new Vector2(8 * x, 8 * y), (Grid[x,y]==1) ? Color.Black : Color.White);