-1

I've got a uni ball maze java project(CBallMaze on internet & Github), and I want to make the ball move automatically to end goal by calling methods for each 4 directions. I wanted to know if I could place time interval to each method, that would cause the methods to last for their set time interval - or if there are other approaches to this matter.

Below, is the current code for my Run button

        if (source == buttonRun) {
        timer = new Timer(1000, this);
        timer.start();
        System.out.println("The program's timer has started");
        if (Maze == Maze1) {

            for (int i=0;i<2;i++) {
            moveLeft();
            moveLeft();
            moveLeft();
            //2nd section//
            moveDown();
            moveDown();
            moveDown();
            //3rd section//
            moveLeft();
            moveLeft();
            //4th section
            moveDown();
            moveDown();
            moveDown();
            //5th section//
            moveRight();
            moveRight();
            //6th section//
            moveDown();
            moveDown();
            moveDown();
            //7th section//
            moveRight();
            moveRight();
            moveRight();
            //8th section//
            moveDown();
            moveDown();
            moveDown();
            //9th section//
            moveLeft();
            moveLeft();
            moveLeft();
            moveLeft();
            moveLeft();
            moveLeft();
            moveLeft();
        }
    }
    }

The code does move the ball, but does not get it to its destination and cannot seem to make the ball move to each tile on its own at a decent pace for a user to see. Any help / guidance will be appreciated.

3
  • if (Maze == Maze1) { - please stick to naming conventions. Variable names should always start with lower case character, thanks.
    – Zabuzard
    Apr 18, 2018 at 22:38
  • 3
    It is unclear what you're asking. We cannot reproduce your problem with the information provided in the question. E.g. why does it matter how long a specific method call lasts? Apr 18, 2018 at 22:41
  • 1
    The concept you are looking for is a clock or similar in a second thread
    – Jacob B.
    Apr 18, 2018 at 22:44

1 Answer 1

2

Every time you go in the method read the current time and save it as a long variable startTime. Then in a while loop do:

while (currentTime() - startTime < x) {
    // perform task
}

x is the arbitrary time duration you want the function to keep running.

1
  • You could improve the quality of the answer by giving a complete example, with the corresponding currentTime() method and assignments of startTime and x, possibly even with links to the documentation. Nonetheless, good answer.
    – Zabuzard
    Apr 18, 2018 at 23:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.