Java Bean Drop, Only Going to The Right

77 Views Asked by At

I have this game where a ball drops on the screen. The problem is, the ball only goes to right. I believe the issue is in the transition from The LR method to the main game loop. I created a variable and it takes the LR method and runs it inside the loop that refreshes and clears the canvas every second. Here is the code:

package cats;

public class BeanDrop {

public static void main(String[] args) throws InterruptedException {
    mainGameLoop();
    }
public static void mainGameLoop() throws InterruptedException{
    double x = .5;
    double y = .9;
    while (true){
    int choice = LR();
    arena();
    ball(x , y);
    if (choice == 1){
        // right outcome
        x = x + .1;
    }
    else if(choice == 2){
        //left outcome
        x = x -.1;
    }
    y = y - .1;
    Thread.sleep(1000);
    StdDraw.clear();
    }
}
public static void arena(){
    StdDraw.picture(.5, .5, "balldrop.jpeg");
}

private static int LR(){
    int choice = ((int) Math.random() * 2 + 1);
    return choice;
}
public static void ball(double x , double y){
    StdDraw.picture(x, y, "ball.jpeg",.05,.05);
}
}
1

There are 1 best solutions below

4
On

Take a look at this: How do I generate random integers within a specific range in Java?

What it says basically is to use this to get a random number:

Random rand;

// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
int randomNum = rand.nextInt((max - min) + 1) + min;

return randomNum;

So for you, you could use this:

private static int LR(){
    int choice = rand.nextInt(2) + 1;
    return choice;
}

EDIT: You must make an instance of Random and name it rand at the top of your code:

private Random rand;

And have this before you initialize the game loop:

rand = new Random();