0

I have two classes one called GameObjects.cs, this initialises a object and its x and y values and my second class is Program.cs and in this I would like a way to randomise the x and y coordinates of the objects each time i run the codei.e. currently its is (10, 10) for example for a tree object.

Game Object class

namespace objectRandom
{
    class GameObject
{
        public string Name { get; }
        public int X { get; }
        public int Y { get; }

    public GameObject(string name, int x, int y)
    {
        Name = name;
        X = x;
        Y = y;
    }

    public override string ToString()
    {
        return String.Format("Name: {0}, X: {1}, Y: {2}", Name, X, Y);
    }
}

Program class

namespace objectRandom
{
    class Program
    {
        static IEnumerable<GameObject> GenerateGameObjects(int mapWidth, int mapHeight)
        {
        List<GameObject> gameObjects = new List<GameObject>();

        gameObjects.Add(new GameObject("Tree", 10, 10));

        return gameObjects;
    }

    static void Main(string[] args)
    {

        foreach (GameObject gameObject in GenerateGameObjects(50, 50))
        {
            Console.WriteLine(gameObject);
        }
    }
}
kay
  • 19
  • 6
  • https://learn.microsoft.com/en-us/dotnet/api/system.random?view=netframework-4.8 – Mitch Wheat Dec 02 '19 at 23:31
  • Have you looked into the Random() function ? – Jawad Dec 02 '19 at 23:31
  • Okay, so what happens when *using* the `Random` class? Searches in the form "msdn C# random" will be useful, eg. – user2864740 Dec 02 '19 at 23:31
  • You get random numbers between x and y ( where you define x and y in the call) – Jawad Dec 02 '19 at 23:32
  • What have you tried...? What research have you done? This is the kind of question that answers are rather excessively plentiful online – Klaycon Dec 02 '19 at 23:33
  • https://stackoverflow.com/a/2706537/1390548 – Jawad Dec 02 '19 at 23:33
  • The Random Class and it's "NextInt()" function is the droid you are looking for. Important: Keep the instance around. A common mistake is to try to get more randomness by creating a new instance - the opposite will be the effect. – Christopher Dec 02 '19 at 23:55

1 Answers1

1

Just use Random class to generate random numbers in range you want:

var rnd = new Random();
int minX = 0, maxX= 1000, minY = 0, maxY = 1000;
gameObjects.Add(new GameObject("Tree", rnd.Next(minX, maxX + 1), rnd.Next(minY, maxY + 1)));
Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171