0

I want to develop my first game, but I have the problem that I don´t know how to make my player move to a random X Position. Instead of "0" (down) at Food.MoveTo(0, Game.SceneBounds.Top); it should be something that makes my player move to a random position.

      if(Food.Position.Y <= Game.SceneBounds.Bottom + Turtle.Size.Height / + 10 && Food.Position.X != Turtle.Position.X)
           {
               Food.MoveTo(0, Game.SceneBounds.Top);
                lives--;
           }
d219
  • 2,707
  • 5
  • 31
  • 36
  • 3
    replace 0 with a random number? – BugFinder Oct 31 '19 at 14:45
  • 2
    Generate a random int and us e it: [SO question: How do I generate a random int number](https://stackoverflow.com/questions/2706500/how-do-i-generate-a-random-int-number) – JNevill Oct 31 '19 at 14:46

2 Answers2

1

You can put somewhere at the class level:

private Random RNG = new Random();

So you can use it to generate a number:

int x = RNG.Next(valueMin, valueMax + 1);
Food.MoveTo(x, Game.SceneBounds.Top);

Where valueMin is the minimum and valueMax is the maximum (the +1 is here because the high bound parameter is excluded).

For example to generate a number between 10 and 50:

int x = RNG.Next(10, 51);
0

For using random numbers you can make use of the Random class like this:

var random = new Random(); var number = random.Next(1,999);

so now you would have the random number stored in the number variable (min 1, max 999). Now you can easily replace the 0 with number variable

Rampage64
  • 158
  • 1
  • 6