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 11 of 11

Thread: MeteorDodger Game JPanel Help (Timer?)

  1. #1
    Junior Member
    Join Date
    May 2011
    Posts
    12
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default MeteorDodger Game JPanel Help (Timer?)

    I made a game that creates meteors in random places at the top of the window, they fall, and you have to avoid them. The only problem is, it doesn't work right. There are no errors, it just doesn't work as intended. I think it has to to with the Timer and my inexperience with it, but I don't know.

    import javax.swing.*;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Event;
    import java.awt.Graphics; 
    import java.awt.MouseInfo;
    import java.awt.Point;
    import java.awt.PointerInfo;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseMotionListener;
    import java.awt.event.MouseMotionAdapter;
    import java.util.ArrayList;
    public class MeteorDodger {
    	public static void main(String[] args) {
     
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createInterface(); 
                }
            });
        }
    	private static void createInterface() {
            JFrame f = new JFrame("METEOR DODGER");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
            f.add(new MyPanel());
            f.setSize(500,500);
            f.setVisible(true);
        }
     
    }
    class MyPanel extends JPanel implements ActionListener {
     
        Meteor meteor = new Meteor();
        Player player = new Player();
        boolean gameOver = false;
        boolean isCollide = false;
        ArrayList<Meteor> meteorList = new ArrayList<Meteor>();
        int score = 0;
        int playerX = player.getMousePositionX();
    	int playerY = player.getMousePositionY();
        Timer timer = new Timer(100, this);
     
        public MyPanel() {
     
            setBorder(BorderFactory.createLineBorder(Color.white));
            setBackground(Color.black);
     
        }
        //make meteor fall
        private void fall(Meteor m){
            final int FALL_DIST = 5;
                repaint(m.getX(), m.getY(), m.getRadius(), m.getRadius());
                m.setY(m.getY() + 5);
                repaint(m.getX(), m.getY() + FALL_DIST, m.getRadius(), m.getRadius());
        }
        //repaint the player if its moved
        private void repaintPlayer(){
     
        	if(playerX != player.getMousePositionX() && playerY != player.getMousePositionY()){
        		repaint(playerX, playerY, 20, 20);
        		repaint(player.getMousePositionX(), player.getMousePositionY(), 20, 20);
        	}
        }
        //creates a list of meteors and adds them to screen
        private void createMeteor(){
    		meteorList.add(meteor);
    		while(!(gameOver)){
    			for (int i = 0; i < meteorList.size(); i++){
    				meteorList.add(new Meteor());
    				updateMeteorList();
    			}
    		}
     
    	}
        //checks if meteor is off screen
        private void updateMeteorList(){
        	for (int i = 0; i < meteorList.size(); i++){
        		if((meteorList.get(i).isOutOfFrame())){
        			meteorList.remove(i);
        			//reset meteorList to check again(-1 accounts for increment of I after iteration is complete on next line)
        			i = -1;
        		}
        	}
        }
        //test if player touched a meteor
        private boolean collision(){
        	for (int i = 0; i < meteorList.size(); i++){
    	    	int pX = player.getMousePositionX();
    			int pY = player.getMousePositionY();
    			int mX = meteorList.get(i).getX();
    			int mY = meteorList.get(i).getY();
    			if(pX > mX - 5 && pX < mX + 5){
    				if(pY > mY - 5 && pY < mY + 5){
    					isCollide = true;
    					return isCollide;
    				}
    			}
    			else{
    				isCollide = false;
    			}
     
        	}
        	return isCollide;
        }
     
        private boolean testGameOver(){
        	if(isCollide == true){
        		gameOver = true;
        		timer.stop();
        	}
        	return gameOver;
        }
     
        //increment score by 5
        private int scoreIncrement(){
        	if((gameOver)){
        		return score;
        	}
        	else{
        		return score+=5;
        	}
        }
     
        public Dimension getPreferredSize() {
            return new Dimension(250,200);
        }
        //Perform all actions ever 1/10 of a second
        @Override
        public void actionPerformed(ActionEvent e) {
    		// TODO Auto-generated method stub
    		createMeteor();
    		for (int i = 0; i < meteorList.size(); i++){
    			fall(meteorList.get(i));
    		}
    		repaintPlayer();
    		scoreIncrement();
    		collision();
    		testGameOver();
    		timer.restart();
     
    	}  
     
        public void paintComponent(Graphics g) {
            super.paintComponent(g);       
            g.drawString("Score: " + score, 10 ,240);
            meteor.paintMeteor(g);
            player.paintPlayer(g);
            timer.start();
        }
     
     
    }

    import java.awt.Color;
    import java.awt.Graphics;
    import java.applet.*;
     
    public class Meteor{
     
        private final int X = (int) (Math.random() * 250);
        private int y = 0;
        private int radius = 10;
     
        public int getX(){
            return X;
        }
     
        public void setY(int _y){
            this.y = _y;
        }
     
        public int getY(){
            return y;
        }
     
        public int getRadius(){
            return radius;
        }
        public boolean isOutOfFrame(){
        	if(getY() >= 250){
        		return true;
        	}
        	else{
        		return false;
        	}
        }
        public void paintMeteor(Graphics g){
            g.setColor(Color.white);
            g.fillOval(X, y, 2 * radius, 2 * radius); 
        }
    }
    import java.awt.Color;
    import java.awt.Event;
    import java.awt.Graphics;
    import java.applet.Applet;
    import java.awt.*;
    import javax.swing.*;
     
    public class Player {
    	private int mousePositionX = getMousePositionX(), mousePositionY = getMousePositionY();
    	public int getMousePositionX() {
    		PointerInfo a = MouseInfo.getPointerInfo();
    	    Point b = a.getLocation();
    	    int x = (int) b.getX();
    	    return x;
    	}
     
    	public int getMousePositionY() {
    		PointerInfo a = MouseInfo.getPointerInfo();
    	    Point b = a.getLocation();
    	    int y = (int) b.getY();
    	    return y;
    	}
    	//updates where the circle around your mouse is
    	public void paintPlayer(Graphics g){
            g.setColor(Color.red);
            g.fillOval(getMousePositionX(), getMousePositionY(), 20, 20); 
        }
     
     
    }


  2. #2
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,320
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: MeteorDodger Game JPanel Help (Timer?)

    Can you please define in detail what you mean by doesn't work right?

  3. #3
    Junior Member
    Join Date
    May 2011
    Posts
    12
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: MeteorDodger Game JPanel Help (Timer?)

    A single white ball appears at the top of the screen, and a red ball appears in the general area of where your mouse was when you ran the program. Nothing else happens.

  4. #4
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,320
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: MeteorDodger Game JPanel Help (Timer?)

    But what do you want to happen, or what do you expect to happen...otherwise we are left guessing

  5. #5
    Junior Member
    Join Date
    May 2011
    Posts
    12
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: MeteorDodger Game JPanel Help (Timer?)

    I expect that several randomly placed(on the x axis) white balls will fall down, and the red ball follows your mouse. I expected that at least, i knew I would have to fix up a couple other glitches, but I knew Id cross that bridge once I got the majority of the program working. I also expect it to print "Score = 0" at the bottom of the screen but that isnt there either.

  6. #6
    Junior Member
    Join Date
    May 2011
    Posts
    12
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: MeteorDodger Game JPanel Help (Timer?)

    Just another thought. Could nothing happening also be the result of the repaint method call not working?

  7. #7
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: MeteorDodger Game JPanel Help (Timer?)

    When I run your code it gets in a tight loop and I am unable to close the window.

  8. #8
    Junior Member
    Join Date
    May 2011
    Posts
    12
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: MeteorDodger Game JPanel Help (Timer?)

    Yeah me too. I dont know what thats about either. I have to force close it

  9. #9
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: MeteorDodger Game JPanel Help (Timer?)

    Look at your logic for the createMeteor() method. It has loops that run forever.

  10. #10
    Junior Member
    Join Date
    May 2011
    Posts
    12
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: MeteorDodger Game JPanel Help (Timer?)

    Even when you fix that, i set it at 15 for example instead of meteorList.size(), and it still doesnt close or do anything.

  11. #11
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: MeteorDodger Game JPanel Help (Timer?)

    The logic is bad. Rethink how to generate and control the fall of the meteors. The loops you have go forever.

    For example I changed that method to:
        private void createMeteor(){
    		meteorList.add(meteor);
    //		while(!(gameOver)){     //<>>>>>>>>>>>>>>>>>>>>> NOTE: Forever loop ???
    //			for (int i = 0; i < meteorList.size(); i++){
    				meteorList.add(new Meteor());
    				updateMeteorList();
    //            System.out.println("i=" + i + " ListSize=" +  meteorList.size()); 
    //			}
    //		}
     
    	}

    and now it exits the create.. Method and I can close the window.

    I suggest that you do some debugging by adding print statements to your code. Here are some samples:


    System.out.println("isOutOfFrame id=" + id);
    System.out.println("created id=" + id + " X=" + X);
    System.out.println(" >>>>>>>>>>removed id=" + m.id);
    System.out.println("isCollide=" + isCollide);
    System.out.print(" moving id=" + m.id);


    I added an id to the meteor:
    int id;

    public Meteor(int id) {
    this.id = id;
    System.out.println("created id=" + id + " X=" + X);
    }
    Last edited by Norm; May 14th, 2011 at 11:54 AM.

Similar Threads

  1. jpanel and using the timer class
    By kswiss in forum AWT / Java Swing
    Replies: 2
    Last Post: March 31st, 2011, 12:35 PM
  2. Timer Class help
    By Deadbob in forum What's Wrong With My Code?
    Replies: 0
    Last Post: February 23rd, 2010, 12:18 AM
  3. How to copy image from one jpanel to another jpanel
    By ramanavarayuri1986 in forum AWT / Java Swing
    Replies: 0
    Last Post: February 15th, 2010, 02:36 AM
  4. Timer?
    By TimW in forum File I/O & Other I/O Streams
    Replies: 1
    Last Post: October 27th, 2009, 07:43 AM
  5. Creating and displaying a JPanel inside another JPanel
    By JayDuck in forum AWT / Java Swing
    Replies: 1
    Last Post: April 7th, 2009, 08:02 AM