#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2011
    Posts
    43
    Rep Power
    3

    How to include Thread in while loop ?


    I need to make the object change modes (movements) depending on the seconds elapsed. I created a while loop with while(object alive) ...
    The thing is it loops way faster than seconds and goes into infinte loop. Someone suggested to include a Thread but I never worked with threads..some help or guidance is appreciated

    Code:
    	private int seconds=0;
    	private boolean ghostalive=true;
    	
    	protected static final int chaseMode = 0;
    	protected static final int scatterMode = 1;
    	protected static final int frightenedMode = 2;
    	
    	static int mode = scatterMode; //initially ghost start in scatterMode
     
    	public Ghost(int x, int y, Maze maze){
    		super(x, y, maze);
    		futureDirection = 0;
    		timer = 0;
    		updateMode();
    		//chaseMode = false; 
    		//frightenedMode = false;
    		
    	}     
    	
    	public static int getMode(){
    		return mode;
    	}
    
    	//LEVEL 1
    	//scatter for 7s 
    	//chase for 20s 
    	//scatter for 7s 
    	//chase for 20s 
    	//scatter for 5s 
    	//chase for 20s
    	//scatter for 5s 
    	//chase indefinite
    
    	public void updateMode(){
    		
    		
    	while(ghostalive){
    		
    		if(seconds<7){
    			mode = scatterMode;
    		}
    		if(7<seconds && seconds<27){
    			mode = chaseMode;
    		}
    		if(27<seconds && seconds<34){
    			mode = scatterMode;
    		}
    		if(34<seconds && seconds<54) {
    			mode = chaseMode;
    		}
    		if(54<seconds && seconds>59) {
    			mode = scatterMode;
    		}
    		if(59< seconds && seconds<79){
    			mode = chaseMode;
    		}
    		if(seconds>84){
    			mode = scatterMode;
    		}
    		seconds++;
    		
    		}	
    	}
  2. #2
  3. Contributing User
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Aug 2010
    Location
    Eastern Florida
    Posts
    3,696
    Rep Power
    347
    Some comments on the code:
    The chain of if tests inside the while look will all be executed. I assume that only one is supposed to be true at a time which means that none of the other if tests should be executed. If so, the if chain should be changed to if/else if.
    it loops way faster than seconds and goes into infinte loop
    How does the while() loop exit? I don't see where the ghostalive value is changed.
    It will hang the program and execute forever. How many times should the while loop go around? When should it stop?

    depending on the seconds elapsed.
    You could use a Timer for that. Set the timer to call a method after the elapsed time. The method could then change the mode and start the timer for the next duration.

IMN logo majestic logo threadwatch logo seochat tools logo