Question

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?

Was it helpful?

Solution

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);
        }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top