Click here to Skip to main content
15,881,898 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
First my code:

Main game class:
C#
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace WindowsGame2
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
       public static GraphicsDeviceManager graphics;
       public static SpriteBatch spriteBatch;
       public static Texture2D rocket,flame;
       public static KeyboardState state;
       public static SpriteFont font;
       public static Texture2D ball;
        public Game1()
           
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            IsMouseVisible = true;
            graphics.ApplyChanges();
            
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
            base.Initialize();


        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
            rocket = Content.Load<Texture2D>("rocket");
            font = Content.Load<SpriteFont>("SpriteFont1");
            ball = Content.Load<Texture2D>("ball");
            flame = Content.Load<Texture2D>("flame");
            // TODO: use this.Content to load your game content here
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            state = Keyboard.GetState();
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();            
            // TODO: Add your update logic here
            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.White);
            // TODO: Add your drawing code here
            Ball.Generatenewball();
            base.Draw(gameTime);
        }
    }
}


Ball class:
C#
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;


namespace WindowsGame2
{      
    public class Ball
    {
        public static Random rand=new Random();
        private static int width, height,movement,i;
        public static List<Ball> balls = new List<Ball>();
        public Ball()
        {
            width = rand.Next(1,GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width);
        height=rand.Next(1,GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height);}
        public static void Update()
        {
            movement = rand.Next(1, 5);
            if (movement == 1)
            {
                if (height <= -50)
                { height = 800; }
                height -= 10;
            }
            if (movement == 2)
            {
                if (height >= 800)
                { height = -50; }
                height += 10;
            }
            if (movement == 3)
            {
                if (width >= 1350)
                { width = -30; }
                width += 10;
            }
            if (movement == 4)
            {
                if (width <= -30)
                { width = 1350; }
                width -= 10;
            }
        }
        public static void Draw()
        {Game1.spriteBatch.Begin();
        Game1.spriteBatch.Draw(Game1.ball, new Vector2(width, height), Color.White);
        Game1.spriteBatch.End();}
        public static void Generatenewball()
        {
            i++;
            if (i % 500 == 0)
            {
                balls.Add(new Ball());
            }
            foreach (Ball ball in balls) 
            {Draw();
            Update();
            }
            
         }
        }
    }


I want to spawn a new ball at regular intervals.A new ball is spawned,but all the balls are at a single position and move together.I want different balls at different positions around the screen.I know I am doing something wrong,please correct me and give the correct code.
Posted
Comments
Nathan Minier 5-Sep-14 8:56am    
Always seed your RNG.
swapnil999 5-Sep-14 9:06am    
I don't understand you are saying!Please Explain
Nathan Minier 5-Sep-14 9:28am    
Sorry, that was me being a smart-ass. RNG = Random Number Generator. Mr. Kreskowiak has a great suggestion below.

1 solution

Don't put your Random in the Ball class. Instead, pass it into the constructor. A better method would be to wrap the Random class in an Interface so you can supply various implementations of random number generators, especially useful for testing your application. This is called "dependency injection".

Instead of the Ball class using it's own RNG, it'll can use a Random implementation passed to it by the calling code.


The problem that you're running into is when your code creates a bunch of instances of Ball, one or more of them can use the default seed value which is the current Timer value. In that case, each one of those Random classes will kick out the same sequence of "random" numbers.

Your modified Ball class:
public class Ball
{
    IRandom rng;

    private Ball()
    {
        // "private" removes the parameterless constructor.
        // This forces your code to provide a IRandom implementation.
    }

    public Ball(IRandom random)
    {
        if (random == null)
        {
            throw new ArgumentNullException("random");
        }

        rng = random;
    }

    ... snip 8< ...
}

The IRandom interface:
public interface IRandom
{
    int Next();
    int Next(int);
    double NextDouble();
}


Your "default" IRandom implementation:
public class DefaultRandom : IRandom
{
    Random rng;

    public DefaultRandom()
    {
        rng = new Random();
    }

    public DefaultRandom(int seed)
    {
        rng = new Random(seed);
    }

    public int Next()
    {
        return rng.Next();
    }

    public int Next(int ceiling)
    {
        return rng.Next(ceiling);
    }

    public double NextDouble()
    {
        return rng.NextDouble();
    }

}


Finally, in your game code, you simply create an instance of your IRandom implementation and pass it to your Ball. Your game should have only one IRandom and you can then pass that to as many objects as you want. Everything would work off of the same RNG:
DefaultRandom rng = new DefaultRandom();

// ... snip 8< ...

Ball myBall = new Ball(rng);
 
Share this answer
 
v4

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900