Home > Software design >  Run each loop at a different time interval
Run each loop at a different time interval

Time:04-05

I'm currently working on a program that pits two simulated fighters against one another. The way I have it right now, each round is done and the output is printed all at once (virtually all at once because it is calculated so fast).

How would I take the below code and make it so that actions in the second loop occur in pseudo real time where it executes x amount of seconds where x is a random roll? Any suggestions or guidance would be great. I would even settle for the second while loop executing every three seconds or so. This is a prototype for now and the simulation will get more varied so reading the output may get more interesting.

public static void fight(Character player1, Character player2, int roundMax){
        player1.setTempHitPoints(player1.getHitPoints());
        player2.setTempHitPoints(player2.getHitPoints());
        int r = ROUND;
        while(!isFightOver(player1, player2)){
            roundTimer = 0;
            System.out.println("================");
            System.out.println("Round "   r   " FIGHT!");
            System.out.println("================");
            while(roundTimer < roundMax && !isFightOver(player1, player2)){
                roundTimer = roundTimer   Commands.roll(10);
                round(player1, player2);
                timerPrint(roundTimer, roundMax);
            }
            System.out.println("================");
            System.out.println("Round "   r   " OVER!");
            System.out.println("================");
            System.out.println("");

            if(!isFightOver(player1, player2)){
                Commands.rest(player1);
                Commands.rest(player2);
            }
            System.out.println("");
            r  ;
        }
            declareWinner(player1, player2);
    }

CodePudding user response:

You can use Thread.sleep() to slow down the processing. E.g. Thread.sleep(1000) causes the current thread to suspend execution for a second (1000 ms). Can you use that method judiciously to put delays into the code? You can use java.util.Random to generate random numbers.

Random random = new Random();

Thread.sleep((random.nextInt(6)   1) * 1000);  // Delays from 1 - 6 secs
  • Related