0
public void Draw(SpriteBatch theSpriteBatch)
    {
        Random rand = new Random();
        for(int y = 0; y < map.GetLength(0); y++) {
            for(int x = 0; x < map.GetLength(1); x++) {
                theSpriteBatch.Draw(tile[rand.Next(0,3)], new Rectangle(x*tileWidth,y*tileHeight,tileWidth,tileHeight), 
                    Color.White);
            }
        }
    }

When I do this it just flickers the tiles and constantly redraws them. What do I do to get the random effect with it only drawing once? Is there a way I could click on these tiles with the mouse and have them change? Also, is there a way to make one tile more prevalent than the others?

tshepang
  • 12,111
  • 21
  • 91
  • 136
Corey
  • 73
  • 4
  • 13

1 Answers1

3

I believe you are looking to only randomly generate the tiles one time and then draw THAT random sequence every time. Remember, Draw in XNA runs every "frame", which is generally way more than once per second!

Copy your current loops over to a new area: your map loading. Also add a 2D data structure (array or whatever) to store the results of your tile generation. I'm calling my sample 2D integer array tileNums. Now, keep the loops as they are now but change the innards to store the results instead of draw:

    Random rand = new Random();
    for(int y = 0; y < map.GetLength(0); y++) {
        for(int x = 0; x < map.GetLength(1); x++) {
            tileNums[x, y] = rand.Next(0,3);
        }
    }

Now just change the innards of your current Draw loop to no longer generate randomly and instead to take from this data:

    //Random object no longer needed
    for(int y = 0; y < map.GetLength(0); y++) {
        for(int x = 0; x < map.GetLength(1); x++) {
            theSpriteBatch.Draw(tile[tileNums[x, y]], new Rectangle(x*tileWidth,y*tileHeight,tileWidth,tileHeight), 
                Color.White);
        }
    }
  • Thank you! I didn't know draw ran every frame, but I figured that was the problem when I seen it flickering. I just wasn't sure how to handle getting the random but I got it now. One problem though I get index out of bounds with the tileNums array. I create the array like this int[,] tileNums = new int[0,3]; right? – Corey Feb 27 '12 at 07:19
  • Nope, those are the sizes of each dimension. This structure should be the exact same size as your map, so I would do `new int[map.GetLength(1), map.GetLength(0)];` (since I did it `x, y`, of course you could do `y, x` and reverse them) –  Feb 27 '12 at 07:23
  • Ahhh! Ok that makes perfect sense now that I think about it :p. Thanks a ton for helping me out – Corey Feb 27 '12 at 07:28