Here are two brief samples of loading random content in XNA
1) Loading a random texture
2) Loading a random object
Random Texture
Using the XNA content pipeline in GSE 1.0, it is simple to generate random textures. In my first game, I only require one background image per game. The following code sample randomly selects the "background0" or "background1" asset names with the same path.
// Load random background texture
Random random = new Random();
int randomNum = random.Next(1,3);
string randomBackgroundAssetName = string.Concat("Content\\background", randomNum.ToString());
Texture2D background = _content.Load<Texture2D>(randomBackgroundAssetName) as Texture2D;
This sample demonstrates how to randomly select a texture within a set of pre-loaded textures, again, using the content pipeline. Using an array of Texture2D values we can store all the textures and access them randomly.
// Load all textures
int numberOfBackgrounds = 2;
Texture2D[] textures = new Texture2D[numberOfBackgrounds];
for (int i = 0; i < numberOfBackgrounds; i++)
{
string randomBackgroundAssetName = string.Concat("Content\\background", i);
textures[i] = _content.Load<Texture2D>(randomBackgroundAssetName) as Texture2D;
}
// Randomly select texture
Random random = new Random();
int randomNum = random.Next(1, 3);
Texture2D randomTexture = textures[randomNum];
Creating random objects
In my Tetris sample game I have a method called GetRandomShape(). It returns a randomized Shape base object. Formally this would fall into a Factory pattern but you get the idea.
///
<summary>
/// This method returns a random shape
/// </summary>
/// <param name="position">Position of the new shape</param>
/// <returns>A base shape object</returns>
private Shape GetRandomShape(Vector2 position)
{
Shape myShape = null;
Random random = new Random();
int randomNum = random.Next(0, _numberOfShapes);
switch (System.Enum.GetName(typeof(Shapes), randomNum))
{
case "Bar":
myShape = new Bar(position);
break;
case "Square":
myShape = new Square(position);
break;
case "ThreeOne":
myShape = new ThreeOne(position);
break;
case "OneThree":
myShape = new OneThree(position);
break;
case "TwoUpTwoDown":
myShape = new TwoUpTwoDown(position);
break;
case "TwoDownTwoUp":
myShape = new TwoDownTwoUp(position);
break;
case "OneTwoOne":
myShape = new OneTwoOne(position);
break;
}
return myShape;
}
Hopefully this resource will help you add dynamic content to your XNA game.
Print | posted on Tuesday, December 26, 2006 5:38 AM