vendredi 25 novembre 2016

Math.random() Generates same number

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!




Aucun commentaire:

Enregistrer un commentaire