1
\$\begingroup\$

I am making a maze game in Java, where you have to escape the maze without being caught by the randomly-moving AI.

The code I am using to decide which direction the enemy moves in causes the character to change direction way too fast. It currently chooses a random number, which corresponds to the direction in which the AI moves.

How can I edit this method so it only chooses a random number every 3 seconds?

if(new Random().nextInt(4) == 0){
    xMove = speed;
}
if(new Random().nextInt(4) == 1){
    xMove = -speed;
}
if(new Random().nextInt(4) == 2){
    yMove = speed;
}
if(new Random().nextInt(4) == 3){
    yMove = -speed;
}
\$\endgroup\$

2 Answers 2

3
\$\begingroup\$

You need to store the last time it changed direction, let's set this to the currrent time:

long lastTurn = System.currentTimeMillis();

Each frame you first check the time difference between the current time and the last time. If this is more than 3000 milliseconds, then you change direction and reset the lastTurn variable:

if (System.currentTimeMillis() - lastTurn >= 3000) {
    // Change direction here
    lastTurn = System.currentTimeMillis();
}

Side note: your currrent way of changing direction is very inefficient. You should store the random somewhere. Also, because you generate a new number each time, there's a chance every if statement gets executed. I'd suggest storing an instance of random somewhere and using a switch instead of couple separate ifs.

\$\endgroup\$
1
\$\begingroup\$

Using a timer: Put these IFs into an ActionListener inside a function, like AI, then create a timer (REMEMBER: Import from javax.swing), then define the timer with 3000ms, and launch it. (You need only more, to run this method from ex. Constructor)

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .