Results 1 to 6 of 6
  1. #1
    dstars5 is offline Member
    Join Date
    Mar 2013
    Posts
    19
    Rep Power
    0

    Question My Failed Attempt at thread.sleep(1000)

    Hey guys,

    I am currently writing a bit of code for a simple Mini Golf game. I need a while loop to run with thread.sleep(). I can't get it to work though. The while loop runs like it isn't even there. Any help?

    Here is the part of the code with the while loop:

    Java Code:
    while (playerNotClicked) {
    				System.out.println("player not clicked");
    				boolean atTop = false;
    				for (int i = 0; i < MAX_POWER; i++) {
    					System.out.println("power bar");
    					if (!atTop) {
    						g.fillRect(TOTAL_WIDTH + BUMPER_WIDTH, getHeight() - SIDE_OFFSET - BUMPER_WIDTH - i * (BUMPER_WIDTH / 2), BUMPER_WIDTH, BUMPER_WIDTH / 2);
    					} else {
    						g.fillRect(TOTAL_WIDTH + BUMPER_WIDTH, getHeight() - SIDE_OFFSET - BUMPER_WIDTH - i * (BUMPER_WIDTH / 2), BUMPER_WIDTH, i * (BUMPER_WIDTH /2));
    					}
    					
    					try {
    						 thread.sleep(1000);
    					} catch (Exception e) {
    						
    					}
    				}
    				//playerNotClicked = false;
    				
    				try {
    					thread.sleep(17);
    				} catch (Exception e) {
    					
    				}
    			}
    This part of the code also has thread.sleep() but it works fine:

    Java Code:
        public void run() {
            while(playing) {
                System.out.println("Playing");
                repaint();
                try {
                    Thread.sleep(17);
                } catch (Exception e) {
                     
                }
            }
            System.out.println("Not Playing");
        }
    And here is the full code (Note that it is pretty messy.. I haven't worked with graphics much, so this project has been a lot of trial and error):

    Java Code:
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionAdapter;
    import java.awt.geom.Ellipse2D;
    import java.awt.geom.Rectangle2D;
    import java.util.Random;
    
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    
    public class MiniGolf extends JPanel implements Runnable {
    	public Thread thread = new Thread(this);
    
    	Random generator = new Random();
    	
    	int ballX;
    	int ballY;
    	int repaints = 0;
    	
    	boolean playerNotClicked = true;
    	
    	int stage = 0;
    	
    	int cupX = ballX;
    	
    	int currentPow = 0;
    	
    	private boolean playing = true;
    	
    	private static final int BUMPER_WIDTH = 50;
    	private static final int TOTAL_WIDTH = 2 * BUMPER_WIDTH + 6 * BUMPER_WIDTH;
    	private static final int SIDE_OFFSET = 10;
    	private static final int BALL_WIDTH = 10;
    	private static final int BALL_OFFSET = 50;
    	private static final int SPEED_LOSS = 50;
    	private static final int MAX_POWER = 6;
    	
    	private int WIDTH = 0;
    	private int HEIGHT  = 0;
    	
    	private double x_vel = 0;
    	private double y_vel = 10;
    	
    	public void run() {
    		while(playing) {
    			System.out.println("Playing");
    			repaint();
    			try {
    				Thread.sleep(17);
    			} catch (Exception e) {
    				
    			}
    		}
    		System.out.println("Not Playing");
    	}
    	
    	public MiniGolf() {
    		thread.start();
    	}
    	
    	public static void main(String[] args) {
    	}
     
    	public void paintComponent(Graphics g) {
    		Graphics2D g2 = (Graphics2D)g;
    		
    		//Draw the Course
    
    		if (stage == 0) {
    			Rectangle2D grass = new Rectangle2D.Float(SIDE_OFFSET, SIDE_OFFSET, TOTAL_WIDTH, getHeight() - 2 * SIDE_OFFSET);
    	
    			Rectangle2D r1 = new Rectangle2D.Float(SIDE_OFFSET, SIDE_OFFSET, BUMPER_WIDTH, getHeight() - 2 * SIDE_OFFSET);
    			Rectangle2D r2 = new Rectangle2D.Float(SIDE_OFFSET, SIDE_OFFSET, TOTAL_WIDTH, BUMPER_WIDTH); 
    			Rectangle2D r3 = new Rectangle2D.Float(SIDE_OFFSET, getHeight() - (SIDE_OFFSET + BUMPER_WIDTH), TOTAL_WIDTH, BUMPER_WIDTH);
    			Rectangle2D r4 = new Rectangle2D.Float(SIDE_OFFSET + TOTAL_WIDTH - BUMPER_WIDTH, SIDE_OFFSET, BUMPER_WIDTH, getHeight() - 2 * SIDE_OFFSET); 
    			
    			Ellipse2D hole = new Ellipse2D.Float(cupX, SIDE_OFFSET + BUMPER_WIDTH + BALL_OFFSET, (int)(BALL_WIDTH * 2.5), (int)(BALL_WIDTH * 2.5));
    			
    			Ellipse2D ball = new Ellipse2D.Float(ballX, ballY, BALL_WIDTH, BALL_WIDTH);
    
    			ballX = (TOTAL_WIDTH + SIDE_OFFSET - BALL_WIDTH / 2) / 2;
    			ballY = getHeight() - (BUMPER_WIDTH + SIDE_OFFSET + BALL_OFFSET);
    			
    			cupX = ballX;
    			
    			g.setColor(Color.yellow);
    			g.fillRect(TOTAL_WIDTH + BUMPER_WIDTH, getHeight() - SIDE_OFFSET - BUMPER_WIDTH - 6 * (BUMPER_WIDTH / 2), BUMPER_WIDTH, BUMPER_WIDTH / 2);
    			
    			while (playerNotClicked) {
    				System.out.println("player not clicked");
    				boolean atTop = false;
    				for (int i = 0; i < MAX_POWER; i++) {
    					System.out.println("power bar");
    					if (!atTop) {
    						g.fillRect(TOTAL_WIDTH + BUMPER_WIDTH, getHeight() - SIDE_OFFSET - BUMPER_WIDTH - i * (BUMPER_WIDTH / 2), BUMPER_WIDTH, BUMPER_WIDTH / 2);
    					} else {
    						g.fillRect(TOTAL_WIDTH + BUMPER_WIDTH, getHeight() - SIDE_OFFSET - BUMPER_WIDTH - i * (BUMPER_WIDTH / 2), BUMPER_WIDTH, i * (BUMPER_WIDTH /2));
    					}
    					
    					try {
    						 thread.sleep(1000);
    					} catch (Exception e) {
    						
    					}
    				}
    				//playerNotClicked = false;
    				
    				try {
    					thread.sleep(17);
    				} catch (Exception e) {
    					
    				}
    			}
    			
    			
    			g.setColor(Color.green);
    			g2.fill(grass);
    			
    			g.setColor(Color.white);
    			g2.fill(ball);
    			g2.fill(hole);
    			
    			g.setColor(Color.black);
    			g2.fill(r1);
    			g2.fill(r2);
    			g2.fill(r3);
    			g2.fill(r4);
    			
    		} else if (stage == 1) {
    			
    			
    			
    		} else if (stage == 2) {
    			Rectangle2D grass = new Rectangle2D.Float(SIDE_OFFSET, SIDE_OFFSET, TOTAL_WIDTH, getHeight() - 2 * SIDE_OFFSET);
    			
    			Rectangle2D r1 = new Rectangle2D.Float(SIDE_OFFSET, SIDE_OFFSET, BUMPER_WIDTH, getHeight() - 2 * SIDE_OFFSET);
    			Rectangle2D r2 = new Rectangle2D.Float(SIDE_OFFSET, SIDE_OFFSET, TOTAL_WIDTH, BUMPER_WIDTH); 
    			Rectangle2D r3 = new Rectangle2D.Float(SIDE_OFFSET, getHeight() - (SIDE_OFFSET + BUMPER_WIDTH), TOTAL_WIDTH, BUMPER_WIDTH);
    			Rectangle2D r4 = new Rectangle2D.Float(SIDE_OFFSET + TOTAL_WIDTH - BUMPER_WIDTH, SIDE_OFFSET, BUMPER_WIDTH, getHeight() - 2 * SIDE_OFFSET); 
    			
    			Ellipse2D hole = new Ellipse2D.Float(cupX, SIDE_OFFSET + BUMPER_WIDTH + BALL_OFFSET, (int)(BALL_WIDTH * 2.5), (int)(BALL_WIDTH * 2.5));
    			
    			ballX += x_vel;
    			ballY += y_vel;
    			
    			if (x_vel < 0 && repaints % SPEED_LOSS == 0) {
    				x_vel += 1;
    			} else if (x_vel > 0 && repaints % SPEED_LOSS == 0) {
    				x_vel -= 1;
    			}
    			
    			if (y_vel < 0 && repaints % SPEED_LOSS == 0) {
    				y_vel += 1;
    			} else if (y_vel > 0 && repaints % SPEED_LOSS == 0) {
    				y_vel -= 1;
    			}
    			
    			Ellipse2D ball = new Ellipse2D.Float(ballX, ballY, BALL_WIDTH, BALL_WIDTH);
    			
    			if (ball.intersects(r1) || ball.intersects(r4)) {
    				x_vel = -x_vel;
    			} else if (ball.intersects(r2) || ball.intersects(r3)) {
    				y_vel = -y_vel;
    			} 
    			
    			if (ball.intersects(hole.getBounds2D())) {
    				playing = false;
    				System.out.println("------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------");
    				JOptionPane.showMessageDialog(null, "You made it in the hole!", "Congratulations!", JOptionPane.ERROR_MESSAGE);
    			}
    		
    			g.setColor(Color.green);
    			g2.fill(grass);
    			
    			g.setColor(Color.white);
    			g2.fill(ball);
    			g2.fill(hole);
    			
    			g.setColor(Color.black);
    			g2.fill(r1);
    			g2.fill(r2);
    			g2.fill(r3);
    			g2.fill(r4);
    			
    		}
    		repaints++;
    		
    	}
    }
    Last edited by dstars5; 04-14-2013 at 06:16 AM. Reason: More info

  2. #2
    kjkrum's Avatar
    kjkrum is offline Senior Member
    Join Date
    Apr 2011
    Location
    Tucson, AZ
    Posts
    1,060
    Rep Power
    6

    Default Re: My Failed Attempt at thread.sleep(1000)

    First of all, you should not be calling Thread.sleep() in the UI event thread. Ever.

    Second, you're calling a static method on an instance of Thread. That may not do what you think. When you call thread.sleep(), you are not making the thread named "thread" sleep. You are making the current thread sleep. This confusion is one of the reasons you should never call a static method on an instance.

    BTW, a negative name for a boolean variable ("playerNotClicked") can also be very confusing. What about when it's not not clicked? Better to call it playerClicked and initialize it to false. If you need to invert the condition, use while(!playerClicked) ...
    Get in the habit of using standard Java naming conventions!

  3. #3
    dstars5 is offline Member
    Join Date
    Mar 2013
    Posts
    19
    Rep Power
    0

    Default Re: My Failed Attempt at thread.sleep(1000)

    Ha, that third one's a pretty good idea.. playerNotClicked sounded better in my head when I wrote it.

    You lost me on the first and second ones, though. Can you elaborate a little? And (I am sure I will get some crap for this ) maybe show me the fixed code? If you would prefer not to, that is fine. I just tend to learn better when I can see a correct version to compare to the wrong version.

  4. #4
    kjkrum's Avatar
    kjkrum is offline Senior Member
    Join Date
    Apr 2011
    Location
    Tucson, AZ
    Posts
    1,060
    Rep Power
    6

    Default Re: My Failed Attempt at thread.sleep(1000)

    When you call repaint(), it causes paintComponent() to be called in the Swing UI thread. If you call Thread.sleep() in the UI thread, the entire UI will lock up for the duration of the sleep.

    On lines 106 and 114 you wrote thread.sleep() instead of Thread.sleep(). Sleep is a static method of Thread, so although it looks like you're calling the sleep() on the thread called "thread", you're actually calling the static Thread.sleep(), which makes the current thread sleep. Actually, I'm not sure why you're even allowed to call a static method on an instance. It's often confusing.
    Last edited by kjkrum; 04-14-2013 at 08:28 AM.
    Get in the habit of using standard Java naming conventions!

  5. #5
    kjkrum's Avatar
    kjkrum is offline Senior Member
    Join Date
    Apr 2011
    Location
    Tucson, AZ
    Posts
    1,060
    Rep Power
    6

    Default Re: My Failed Attempt at thread.sleep(1000)

    Also, if you're waiting in a loop in the UI thread for player(Not)Clicked to change, and the thing that changes it is a click on the UI, then it'll never change because the UI thread will never process the click; it's stuck in the loop.
    Get in the habit of using standard Java naming conventions!

  6. #6
    dstars5 is offline Member
    Join Date
    Mar 2013
    Posts
    19
    Rep Power
    0

    Default Re: My Failed Attempt at thread.sleep(1000)

    Ok, thank you! I ended up just saving which part of the game I needed running, and then just used some if statements. Works like a charm now!

Similar Threads

  1. Replies: 1
    Last Post: 09-24-2012, 07:01 PM
  2. Leave thread yield or attempt join... or something else?
    By JavaCoder in forum Advanced Java
    Replies: 1
    Last Post: 08-11-2010, 06:35 PM
  3. Difference between Thread.yield() and Thread.sleep() methods
    By Nageswara Rao Mothukuri in forum New To Java
    Replies: 12
    Last Post: 07-30-2010, 05:37 PM
  4. how to reduce the thread sleep time and wake up the thread
    By baktha.thalapathy in forum Threads and Synchronization
    Replies: 2
    Last Post: 06-24-2010, 07:36 PM
  5. my Quicksort attempt has failed
    By Jeremy8 in forum New To Java
    Replies: 4
    Last Post: 11-16-2009, 02:56 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •