3

I'm writing a generic snake game in Java, and I want my apple to be drawn at random coordinates on call. However, when I set my coordinates based off Math.random(), both coordinates create the same Math.random result. This means the apple is always drawn on a linear line ex. (4,4)

//Draws apple
public void drawApple(Graphics2D gfx) {
    rectCoords(gfx, red, (int) Math.floor(Math.random()*20), (int) Math.floor(Math.random()*20));
}
// rectCoords(graphics, color, xcoordinate, ycoordinate)

I assume this is because they're using the same time value for their seed, since they were called at the same time.

I've tried Math.random(), Random objects, even a combination of both. I've tried declaring them as variables at different times throughout the code, even throwing in a Thread.sleep(); (although I had some trouble actually getting it to work).

Surely I'm not the only one who's tried to generate two random numbers at the same time. I appreciate anyone who looks this over or points me to a similar thread. Thanks!

EDIT: I fixed it, it was a problem in another piece of code. Although, not really sure how to close this thread or mark it resolved...

Kyle Sayers
  • 33
  • 1
  • 4
  • 1
    Are you *sure* the code you're running is the same as the code you've posted here? – Bohemian Nov 25 '16 at 08:10
  • Math.random() gives a double value which is >0 and <1, which when you convert to integer it will always becomes 0 – Vasu Nov 25 '16 at 08:10
  • What is the same numbers you are getting? is it always 0? – Jobin Nov 25 '16 at 08:13
  • 1
    Are you *sure* you've using `java.lang.Math` (and you haven't imported another class called `Math`? – Bohemian Nov 25 '16 at 08:13
  • 2
    Hum. That's *very* intriguing. Be assured they are *not* called at the same time: that's not how Java works when evaluating function argument lists. Note also that Math.random() doesn't work well in a multi-threaded environment. Personally though, I think you have a bug in your rectCoords function: you're discarding one of the arguments. – Bathsheba Nov 25 '16 at 08:13
  • 1
    I'm going to use my psychic powers... You have a typo in your `rectCoords` method; you have coded either `xcoordinate` twice or `ycoordinate` twice, when you meant to use both. – Bohemian Nov 25 '16 at 08:21

1 Answers1

3

You will always get a number which is less than 20 with your current code (because Math.random() gives a double value which is >=0 and <1), so instead you can use nextInt() method from java.util.Random as shown below:

public void drawApple(Graphics2D gfx) {
     Random random = new Random();
    rectCoords(gfx, red, random.nextInt(), random.nextInt());
}

Also, you can actually use the overloaded method nextInt(maxNumber) to set the maximum limit to the random number by using/passing maxNumber value random.nextInt(maxNumber).

Vasu
  • 21,832
  • 11
  • 51
  • 67