Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 14 of 14

Thread: Method keeps looping and timer issues.

  1. #1
    Junior Member
    Join Date
    May 2013
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Question Method keeps looping and timer issues.

    Alright this consists of two problems I have with my recreation of Snake game in GUI. The first is that when the game ends, I want a pop up that gives the users the option to replay or quit. However, when the snake hits the tail or board, the message continually pops up. So in essence, the gameOver method repeats itself over and over.

    private void checkDotCollision () {
     
     
    		for (int z = dots; z > 0; z--) {
     
                if ((z > 2) && (x[0] == x[z]) && (y[0] == y[z])) {
                    inGame = false;
     
                    gameOver ();
                }
            }
     
            if (y[0] == screenHeight) {
            	inGame = false;
     
            	gameOver ();
            }
     
            if (y[0] == 0) {
            	inGame = false;
     
            	gameOver ();
            }
     
            if (x[0] == screenWidth) {
            	inGame = false;
     
            	gameOver ();
            }
     
            if (x[0] == 0) {
                inGame = false;
     
                gameOver ();
            }
     
     
    	}
     
     
    	private void gameOver () {
     
    		if (inGame == false) {
     
    		JFrame gameOverFrame = new JFrame();
    		gameOverFrame.setVisible(true);
    		JTextField gameOverPrompt = new JTextField(30);
    		gameOverPrompt.setText("Game Over. Would you like to play again?");
    		gameOverPrompt.setEditable(false);
    		JButton buttonReplay = new JButton("Replay");
    		buttonReplay.addActionListener( // New actionListener which has an
    											// inner class and method within it.
    				new ActionListener() {
    					public void actionPerformed(ActionEvent e) {
    						Initialize();
     
    					}
    				});
    		JButton buttonQuit = new JButton("Quit");
    		buttonQuit.addActionListener( // New actionListener which has an
    				// inner class and method within it.
    				new ActionListener() {
    					public void actionPerformed(ActionEvent e) {
    						System.exit (0);
    					}
    				});
    		gameOverFrame.add (gameOverPrompt);
    		gameOverFrame.add (buttonReplay);
    		gameOverFrame.add (buttonQuit);
    		gameOverFrame.setLayout(new FlowLayout());
    		gameOverFrame.pack ();
    		inGame = true;
     
     
    	}else if (inGame == true) {
     
     
    	}
    	}

    Also it seems that when I do hit the replay button, the snake seems to speed up and I'm not sure whether it's a timer issue or not. When I replay the game (jumping back to the Initialize method), the snake seems to move faster every time.

    private void Initialize () {
     
    		//sets the amounts of dots on screen to start at 1
    		dots = 1;
     
    		 for (int z = 0; z < dots; z++) {
    	            x[z] = 50 - z * 10;
    	            y[z] = 50;
    	        }
     
    		 //jumps to randomEdibleDot method
    		 randomEdibleDot ();
     
    		 //starts the timer to set the speed at which the snakeHead travels
    		 timer = new Timer (delay, this);
    		 timer.start ();
     
    	}

    I am a beginner at coding and any help is appreciated. Thanks.


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Method keeps looping and timer issues.

    Can you post a complete program that compiles, executes and shows the problem?

    snake seems to move faster every time.
    Is there more than one method being executed that move the snake? Add println() statements next to the code that changes the location of the snake so you can see how often the snake's location is being changed.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    May 2013
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Method keeps looping and timer issues.

    Complete program is as follows:

    runGame.java

    import java.awt.*;
    import javax.swing.*;
     
     
    	public class runGame extends JFrame  {
     
    		public runGame () {
    		snake snake_ = new snake ();
    		getContentPane().add(snake_);
    		setTitle ("Snake: The Game");
    		setLocationRelativeTo(null);
    		setResizable (false);
    		pack ();
     
    	}
     
     
     
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
     
    		EventQueue.invokeLater (new Runnable () {
     
    			@Override
    			public void run () {
    				JFrame ex = new runGame ();
    				ex.setVisible (true);
    			}
    		});
    	}
     
    }

    snake.java

    import java.awt.*;
     
    import javax.imageio.ImageIO;
    import javax.swing.*;
     
    import java.awt.event.*;
    import java.io.IOException;
     
    public class snake extends JPanel implements ActionListener {
     
    	//declare variables used in the beginning. by making them private, they can be seen only by the classes they belong to 
    	//sets the screen width to be 400
    	private static int screenWidth = 400;
    	//sets the screen height to be 400
    	private static int screenHeight = 400;
    	//sets the size of each dot to be 10
    	private int dotSize = 10;
    	//sets the max number of dots that can be on the screen (400*400/10*10)
    	private int maxDots = 1600;
    	//used to randomize a dot to appear on screen
    	private int randomPosition = 37;
    	//speed of the game
    	private int delay = 160;
     
    	//creates an array of all of the x coordinates of the snake that can be on screen
    	private int x [] = new int [maxDots];
    	//creates an array of all of the y coordinates of the snake that can be on the screen
    	private int y [] = new int [maxDots];
    	//creates variable for the dots on snake
    	private int dots;
    	//the x coordinate for the current edible dot
    	private int edibleDotX;
    	//the y coordinate for the current edible dot
    	private int edibleDotY;
     
    	//boolean for the left direction of the snake
    	private boolean left = false;
    	//boolean for the right direction of the snake
    	private boolean right = false;
    	//boolean for the up direction of the snake set to true as it starts going up
    	private boolean up = true;
    	//boolean for the down direction of the snake
    	private boolean down = false;
     
    	private int points = 0;
     
    	//boolean for whether the game should continue running or end
    	private boolean inGame = true;
     
    	//add a timer object
    	private Timer timer;
     
    	//image variable for the dots. accessible only by the class that needs it
    	private Image dotSprite;
    	//image variable for snake head. accessible only by the class that needs it
    	private Image snakeHead;
    	//image variable for snake body. accessible only by the class that needs it
    	private Image snakeBody;
     
    	//creates a content pane
    	Container contentPane;
     
     
     
     
    	//initializes the screen. this method is public because everything is displayed here
    	public snake () {
     
    		//sets the screen size to the values listed as screenWidth and screenHeight
    		setPreferredSize(new Dimension (screenWidth, screenHeight));
    		//adds KeyListener so actions can be performed when keys are pressed
    		addKeyListener (new TAdapter ());
    		//sets the screen visible
    		setVisible (true);
    		//the component can gain focus if requested to do so
    		setFocusable (true);
    		//goes to the load images method
    		loadImages ();
    		//sets the background color to be white after the images are loaded
    		setBackground(Color.white);
     
     
     
     
    		//goes to the initialize method		
    		Initialize ();
     
    		validate ();
     
    	}
     
     
    	private void loadImages () {
     
    		//sets the default image icon to be blank
    		ImageIcon ish = null;
    		//try catch exception to search for the image
    		try {
    			ish = new ImageIcon (ImageIO.read(snake.class.getResource("snakeHead.png")));
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		//defines the variable snakeHead as the image that was retrieved.
    		snakeHead = ish.getImage ();
     
    		//sets the default image icon to be blank
    		ImageIcon id = null;
    		//try catch exception to search for the image
    		try {
    			id = new ImageIcon (ImageIO.read(snake.class.getResource ("dot.png")));
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		//defines the variable dotSprite as the image that was retrieved.
    		dotSprite = id.getImage ();
     
    		//sets the default image icon to be blank
    		ImageIcon isb = null;
    		//try catch exception to search for the image
    		try {
    			isb = new ImageIcon (ImageIO.read(snake.class.getResource ("snakeBody.png")));
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		//defines the variable snakeBody as the image that was retrieved.
    		snakeBody = isb.getImage ();
     
     
    	}
     
    	private void Initialize () {
     
    		//sets the amounts of dots on screen to start at 1
    		dots = 1;
     
    		 for (int z = 0; z < dots; z++) {
    	            x[z] = 50 - z * 10;
    	            y[z] = 50;
    	        }
     
    		 //jumps to randomEdibleDot method
    		 randomEdibleDot ();
     
    		 //starts the timer to set the speed at which the snakeHead travels
    		 timer = new Timer (delay, this);
    		 timer.start ();
     
    	}
     
     
     
    	 public void paintComponent(Graphics g) {
    	        super.paintComponent(g);
     
    	        doDrawing(g);
    	    }
     
    	   public void doDrawing(Graphics g) {
     
     
     
    	        if (inGame == true) {
     
    	        	g.drawString ("Score: " + points, 300, 20);
    	            g.drawImage(dotSprite, edibleDotX, edibleDotY, this);
     
    	            for (int z = 0; z < dots; z++) {
    	                if (z == 0) {
    	                    g.drawImage(snakeHead, x[z], y[z], this);
    	                } else {
    	                    g.drawImage(snakeBody, x[z], y[z], this);
    	                }
    	            }
     
    	            Toolkit.getDefaultToolkit().sync();
    	            g.dispose();
     
    	        } else if (inGame == false) {
     
     
    	           gameOver ();
    	        }        
    	    }
     
     
     
     
     
     
     
    	private void randomEdibleDot () {
     
    		//randomly positions a dot in a new place on the board. 
    		  int r = (int) (Math.random () * randomPosition);
    	        edibleDotX = ((r * dotSize));
     
    	        r = (int) (Math.random() * randomPosition);
    	        edibleDotY = ((r * dotSize));
     
    	}
     
    	private void checkDot() {
     
            if ((x[0] == edibleDotX) && (y[0] == edibleDotY)) {
     
                dots++;
                points = (points + 10);
                randomEdibleDot();
            }
        }
     
    	private void moving () {
     
    		 for (int z = dots; z > 0; z--) {
    	            x[z] = x[(z - 1)];
    	            y[z] = y[(z - 1)];
    	        }
     
    	        if (left) {
    	            x[0] -= dotSize;
    	        }
     
    	        if (right) {
    	            x[0] += dotSize;
    	        }
     
    	        if (up) {
    	            y[0] -= dotSize;
    	        }
     
    	        if (down) {
    	            y[0] += dotSize;
    	        }
    	    }
     
    	private void checkDotCollision () {
     
     
    		for (int z = dots; z > 0; z--) {
     
                if ((z > 2) && (x[0] == x[z]) && (y[0] == y[z])) {
                    inGame = false;
     
                    gameOver ();
                }
            }
     
            if (y[0] == screenHeight) {
            	inGame = false;
     
            	gameOver ();
            }
     
            if (y[0] == 0) {
            	inGame = false;
     
            	gameOver ();
            }
     
            if (x[0] == screenWidth) {
            	inGame = false;
     
            	gameOver ();
            }
     
            if (x[0] == 0) {
                inGame = false;
     
                gameOver ();
            }
     
     
    	}
     
     
    	private void gameOver () {
     
    		if (inGame == false) {
     
    		JFrame gameOverFrame = new JFrame();
    		gameOverFrame.setVisible(true);
    		JTextField gameOverPrompt = new JTextField(30);
    		gameOverPrompt.setText("Game Over. Would you like to play again?");
    		gameOverPrompt.setEditable(false);
    		JButton buttonReplay = new JButton("Replay");
    		buttonReplay.addActionListener( // New actionListener which has an
    											// inner class and method within it.
    				new ActionListener() {
    					public void actionPerformed(ActionEvent e) {
    						Initialize();
     
    					}
    				});
    		JButton buttonQuit = new JButton("Quit");
    		buttonQuit.addActionListener( // New actionListener which has an
    				// inner class and method within it.
    				new ActionListener() {
    					public void actionPerformed(ActionEvent e) {
    						System.exit (0);
    					}
    				});
    		gameOverFrame.add (gameOverPrompt);
    		gameOverFrame.add (buttonReplay);
    		gameOverFrame.add (buttonQuit);
    		gameOverFrame.setLayout(new FlowLayout());
    		gameOverFrame.pack ();
    		inGame = true;
     
     
    	}else if (inGame == true) {
     
     
    	}
    	}
    	@Override
    	public void actionPerformed(ActionEvent arg0) {
    		// TODO Auto-generated method stub
     
    		if (inGame == true) {
     
                checkDot();
                checkDotCollision();
                moving();
            }
     
            repaint();
        }
     
        private class TAdapter extends KeyAdapter {
     
            @Override
            public void keyPressed(KeyEvent e) {
     
               int key = e.getKeyCode();
     
                if ((key == KeyEvent.VK_LEFT) && (!right)) {
                    left = true;
                    up = false;
                    down = false;
                }
     
                if ((key == KeyEvent.VK_RIGHT) && (!left)) {
                    right = true;
                    up = false;
                    down = false;
                }
     
                if ((key == KeyEvent.VK_UP) && (!down)) {
                    up = true;
                    right = false;
                    left = false;
                }
     
                if ((key == KeyEvent.VK_DOWN) && (!up)) {
                    down = true;
                    right = false;
                    left = false;
                }
            }
        }
    }

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Method keeps looping and timer issues.

    What is printed out by the println()s I suggested you add? Do they print more often as the snake speeds up?
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    May 2013
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Method keeps looping and timer issues.

    Quote Originally Posted by Norm View Post
    What is printed out by the println()s I suggested you add? Do they print more often as the snake speeds up?
    Nope they print once every time I press the replay button. But I think the timer fires faster or something because every time I press Replay, the initial snake head moves faster and faster. It may also be due to the fact that the gameOver method keeps looping every time I press Replay by popping up another Replay or Quit prompt.

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Method keeps looping and timer issues.

    Put a println() in the actionPerformed() method that is called by the time to see when it is called.
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Junior Member
    Join Date
    May 2013
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Method keeps looping and timer issues.

    Yeah it prints over and over constantly while I'm playing.

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Method keeps looping and timer issues.

    prints over and over constantly while I'm playing.
    Does it ever stop?
    After a replay, how many timers are running?

    Add a call to System.currentTimeMillis() to the println so you can see how often the method is called:
    System.out.println("aP @ " + System.currentTimeMillis() + " " + inGame);
    If you don't understand my answer, don't ignore it, ask a question.

  9. #9
    Junior Member
    Join Date
    May 2013
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Method keeps looping and timer issues.

    It prints something like this:

    aP @ 1403042040387 true
    aP @ 1403042040548 true
    aP @ 1403042040709 true
    aP @ 1403042040870 true
    aP @ 1403042041031 true
    aP @ 1403042041192 true
    aP @ 1403042041353 true
    aP @ 1403042041514 true
    aP @ 1403042041675 true
    aP @ 1403042041836 true
    aP @ 1403042041997 true
    aP @ 1403042042158 true
    aP @ 1403042042319 true
    aP @ 1403042042480 true
    aP @ 1403042042641 true
    aP @ 1403042042802 true

    etc. etc. etc.

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Method keeps looping and timer issues.

    Did you look at the times for the first slower run and for later faster runs.
    Were the the print outs made more frequently later?

    How many timers are running on the second run and on later runs?

    Should the variable: inGame ever be false? Did the print out ever show it as false?
    If you don't understand my answer, don't ignore it, ask a question.

  11. #11
    Junior Member
    Join Date
    May 2013
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Method keeps looping and timer issues.

    Yeah they print out more frequently later once I slowed down the delay. It should have been false when it hit the end of the board but it didn't and they were all true. I have no idea how many timers are running and that's what I'm curious about. If you look at my Initialize code it makes a new Timer every iteration of that method. So is that the problem? And if so, how do I make it so it's only one timer throughout?

    --- Update ---

    Oh never mind. I was really dumb. Fixed the timer issue by just placing it outside of the Initialize method. But it still gives a popup and repeats the gameOver method.

  12. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Method keeps looping and timer issues.

    Initialize code it makes a new Timer every iteration of that method. So is that the problem?
    Yes that is one of the problems.

    it still gives a popup and repeats the gameOver method.
    What should it do?
    If you don't understand my answer, don't ignore it, ask a question.

  13. #13
    Junior Member
    Join Date
    May 2013
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Method keeps looping and timer issues.

    Well it should restart the game when you press Replay and go to the Initialize method. It does that except when you press Replay, the pop up doesn't disappear and another pop up appears as well. The game itself does restart but now there are two pop up dialogs in the way.

  14. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Method keeps looping and timer issues.

    the pop up doesn't disappear
    There isn't any code to make the JFrame disappear. Look at the JFrame class (and the classes it extends) to see if there are any methods that will do what you want.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. Making a countdown timer using the currentTimeMillis method
    By Michael_D in forum Loops & Control Statements
    Replies: 10
    Last Post: June 6th, 2014, 12:02 PM
  2. Looping method problem.
    By Swen in forum What's Wrong With My Code?
    Replies: 24
    Last Post: December 29th, 2011, 09:49 AM
  3. Timer expiry calls a method
    By jack_nutt in forum Java Theory & Questions
    Replies: 1
    Last Post: July 11th, 2011, 07:46 PM
  4. Timer expires invoke method
    By jack_nutt in forum What's Wrong With My Code?
    Replies: 7
    Last Post: July 11th, 2011, 05:52 PM
  5. looping method
    By dcshoecousa in forum What's Wrong With My Code?
    Replies: 1
    Last Post: December 5th, 2010, 09:19 PM

Tags for this Thread