Results 1 to 15 of 15
Like Tree2Likes
  • 2 Post By DarrylBurke

Thread: Breakout paddle doesn't move

  1. #1
    Join Date
    Aug 2012
    Posts
    6
    Rep Power
    0

    Default Breakout paddle doesn't move

    Hi there, I'm new to java and I'm attempting to create a Breakout game (or something similar). Right now, I've succeeded in creating a ball and a paddle. However, I cannot get the paddle to move when I press the left and right arrow keys... I've posted my code so far below.
    Any help would be greatly appreciated!

    The game class (puts together the ball and paddle classes) :

    Java Code:
    import java.applet.Applet;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    
    public class game extends Applet implements Runnable, KeyListener {	
    //variables
    	private Image i;	
    	private Graphics doubleG;
    	private Thread th = new Thread(this);
    	private boolean running = true;
    	private int fps = 50;
    	private ball ball;
    	private Paddle paddle;	
    //centers the paddle at the bottom of the screen
    	private int x = 450;
    	private int y = 950;
    //setting the screen and creating the ball and paddle 
    	public void init() {
    		setSize(1000, 1000);
    		paddle = new Paddle(x, y);
    		ball = new ball();
    		ball.setColor(Color.red);
    	}
    //starts the thread
    	public void start() {
    		th.start();
    	}
    //to end the game later
    	public void endGame() {
    		running = false;
    	}
    //The main run method that executes all of the animation in the while loop
    	public void run() {
    		while (running) {
    			repaint();
    			ball.update(this);
    			if ((paddle.leftPressed) && (!paddle.rightPressed)) {
    				paddle.moveLeft();
    			}
    			if ((paddle.rightPressed) && (!paddle.leftPressed)) {
    				paddle.moveRight();
    			}
    			try {
    				Thread.sleep(1000 / fps);
    			} catch (Exception e) {
    			}
    		}
    	}
    
    // double buffering the image to avoid flickering
    	public void update(Graphics g) {
    		if (i == null) {
    			i = createImage(this.getSize().width, this.getSize().height);
    			doubleG = i.getGraphics();
    		}
    		doubleG.setColor(getBackground());
    		doubleG.fillRect(0, 0, this.getSize().width, this.getSize().height);
    		doubleG.setColor(getForeground());
    		paint (doubleG);
    		g.drawImage(i,0, 0, this);
    	}
    
    //putting the ball and paddle on the screen
    	public void paint(Graphics g) {
    		ball.paint(g);
    		paddle.paint(g);
    	}
    //The key events that should make the paddle move
    	public void keyPressed(KeyEvent e) {
    		if (e.getKeyCode() == KeyEvent.VK_LEFT) {
    			paddle.leftPressed = true;
    		}
    		
    		if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
    			paddle.rightPressed = true;
    		}		
    	}
    	public void keyReleased(KeyEvent e) {
    		if (e.getKeyCode() == KeyEvent.VK_LEFT) {
    			paddle.leftPressed = false;
    		}		
    		if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
    			paddle.rightPressed = false;
    		}		
    	}
    	public void keyTyped(KeyEvent e) {			
    	}	
    }

    The Ball class (Creates and formats a ball. Also includes the bounce logic) :

    Java Code:
    import java.awt.*;
    import java.util.ArrayList;
    
    import javax.swing.*;
    
    import acm.util.RandomGenerator;
    
    
    public class ball  {
    
    //Variables	
    //The velocity, initial x and y positions, and the velocity are all random integers	
    
    	private RandomGenerator rgen = RandomGenerator.getInstance();
    	private int radius = 20;
    	private double xPos = rgen.nextInt(radius + 1, radius + 100);
    	private double yPos = rgen.nextInt(radius + 1, radius + 100);
    
    	private double angle = rgen.nextInt(0, 360);
    	private double velocity = rgen.nextInt(15, 25);
    	private int xSin= 1;
    	private int ySin = 1;
    	Color color = Color.black;
    	public int numLives = 3;
    	public boolean isRunning = true;
    
    // The update method contains the logic of the ball.
    //Based on the angle, velocity, and position, the x and y positions are updated.
    // the if statements are to keep the ball inside the screen
    
    	public void update(game mv) {
    		
    		if (xPos >= (mv.getWidth() -radius - 5)) {
    			xSin = -1 * xSin; 
    		}
    		
    		if (xPos <= 0 + radius) {
    			xSin = -1 * xSin; 
    		}
    
    
    		if (yPos >= (mv.getHeight() - radius - 5)) {
    			ySin = -1 * ySin;
    		} 
    		
    		if (yPos <= radius) {
    			ySin = -1 * ySin;
    		}
    
    		xPos += xSin * velocity * (Math.cos(angle));
    		yPos += ySin * velocity * (Math.sin(angle));
    	}
    // To keep track of the number of lives later 	
    	public void lostLife(int numLives) {
    		numLives = numLives - 1;
    	}
    
    	
    //paints the ball to the screen with the updated x and y positions	
    	public void paint(Graphics g) {
    		g.fillOval((int)xPos - radius, (int)yPos - radius, 2 * radius, 2 * radius);
    		g.setColor(color);
    		
    
    	}
    // getters and setters
    	public void setLocation(int i, int j) {
    		xPos = i;
    		yPos = j;
    	}
    
    	public void setAngle(int i) {
    		angle = i;
    	}
    
    	public void setSpeed(int i) {
    		velocity = i;
    	}
    	
    	public void setColor(Color colorofball) {
    		color = colorofball;
    	}
    	
    	public int getRadius() {
    		return radius;
    	}
    	
    	public void setRadius(int i) {
    		radius = i;
    	}
    	
    
    }
    And finally, the paddle class, which creates a paddle (basically a rectangle) :

    Java Code:
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.awt.*;
    
    
    public class Paddle {
    	public int xPosition = 0;
    	public int yPosition = 0;
    // dx is the distance to travel each time in pixels	
    	int dx = 5;
    	int minx = 0;
    	int maxx = 1000;
    
    	int width = 100;
    	int height = 20; 
    	public boolean leftPressed = false;
    	public boolean rightPressed = false;	
    // constructor
    	public Paddle(int x, int y) {
    		this.xPosition = x;
    		this.yPosition = y;	
    		
    	}	
    // painting the paddle to the screen
    	public void paint(Graphics g) {
    		g.setColor(Color.black);
    		g.fillRect(xPosition, yPosition, width, height);
    
    	}
    // when the moveLeft method is called by the keyPressed method, the paddle should move to the left
    	public void moveLeft() {
    		if (xPosition-dx>minx) {
    			xPosition -= dx;  
    		} else {		  
    			xPosition = minx;
    		}
    	}	 
    	
    // when the moveRight method is called by the keyPressed method, the paddle should move to the left	
    	public void moveRight() {
    		if (xPosition-dx>minx) {
    			xPosition += dx;  
    		} else {		  
    			xPosition = minx;
    		}
    	}	    
    // to set the location of the paddle manually	
    	public void setLocation(int i, int j) {
    		xPosition = i;
    		yPosition = j;
    	}
    
    	public int getLength() {
    		return width;
    	}
    
    }
    Again, thank you so much for any help you provided.

    JavaProgrammerToo
    Last edited by JavaProgrammerToo; 08-08-2012 at 07:18 AM.

  2. #2
    SRaith is offline Member
    Join Date
    Oct 2011
    Posts
    14
    Rep Power
    0

    Default Re: Breakout paddle doesn't move

    You just forgot to add the KeyListener to your applet :).
    Just add it in your init method and it should work.

  3. #3
    Join Date
    Aug 2012
    Posts
    6
    Rep Power
    0

    Default So I added it...

    Thanks so much for your quick reply!!
    So, I added it into the init() method (the new line is in bold)
    Java Code:
    public void init() {
            addKeyListener()
            setSize(1000, 1000);
            paddle = new Paddle(x, y);
    
            ball = new ball();
            ball.setColor(Color.red);
    }
    but it gives me an error:
    the method addKeyListener(KeyListener) in the type Component is not applicable for the arguments().

    What do I do???

    JavaProgrammerToo
    Last edited by JavaProgrammerToo; 08-14-2012 at 04:15 PM.

  4. #4
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,271
    Rep Power
    25

    Default Re: Breakout paddle doesn't move

    Please post the full text of the compiler's error message showing the line where the error happens.

    Where is the method: addKeyListener() (called on line 2) defined?

    Have you read the API doc for the class where the method is defined to see how to call it?
    Have you read the tutorial on how to write a listener:
    Lesson: Writing Event Listeners (The Java™ Tutorials > Creating a GUI With JFC/Swing)
    If you don't understand my response, don't ignore it, ask a question.

  5. #5
    SRaith is offline Member
    Join Date
    Oct 2011
    Posts
    14
    Rep Power
    0

    Default Re: Breakout paddle doesn't move

    The addKeyListener method need a KeyListener as parameter. If you look at your game class, you implement KeyListener,
    which means, you can give the addKeyListener this class as parameter.

    Java Code:
    public void init() {
            addKeyListener(this);
            setSize(1000, 1000);
            paddle = new Paddle(x, y);
     
            ball = new ball();
            ball.setColor(Color.red);
        }

  6. #6
    Join Date
    Aug 2012
    Posts
    6
    Rep Power
    0

    Default Re: Breakout paddle doesn't move

    Sorry to bother again, but the paddle still doesn't move when I changed the line to addKeyListener(this). I don't understand why though.
    Is there faulty logic in any of my classes that is preventing the paddle from moving?

    JavaProgrammerToo

  7. #7
    quad64bit's Avatar
    quad64bit is offline Moderator
    Join Date
    Jul 2009
    Location
    VA
    Posts
    1,323
    Rep Power
    6

    Default Re: Breakout paddle doesn't move

    Put a System.out.println() in the move action and see if it prints anything when you hit the key. That way you'll know if your keyListener is even firing.

  8. #8
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,188
    Rep Power
    19

    Default Re: Breakout paddle doesn't move

    A KeyListener is only triggered for the focused component. Which in turn implies that said component be focusable.

    Why, in this day and age, are you writing AWT code? Swing superseded AWT more than 10 years ago.

    db
    quad64bit and kammce like this.
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  9. #9
    Join Date
    Aug 2012
    Posts
    6
    Rep Power
    0

    Default Re: Breakout paddle doesn't move

    Ok, so I tried the println statements, and it seems like both the leftPressed and rightPressed booleans are always true and are both being called each update. So, their movement is cancelled out by each other. I know now that the problem lies in the key listener. When I put println statements there, they don't seem to work. Is there any particular reason why? I've read the key Listener tutorials and tried a couple things like focus, and it still doesn't work :(

  10. #10
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,188
    Rep Power
    19

    Default Re: Breakout paddle doesn't move

    Just make the change to Swing and use Key Bindings already instead of hacking away at obsolete stuff.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  11. #11
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,271
    Rep Power
    25

    Default Re: Breakout paddle doesn't move

    they don't seem to work
    Please explain.
    Do you mean that the code with the printlns is not being executed?
    If you don't understand my response, don't ignore it, ask a question.

  12. #12
    Join Date
    Aug 2012
    Posts
    6
    Rep Power
    0

    Default Re: Breakout paddle doesn't move

    Wow... I worded that kinda weird. I meant to say that I put the println statements in the moveLeft and moveRight methods, and they were both being called every update. Then I tried putting the println statements in the keyPressed and keyReleased methods. The two methods weren't being called when I ran the program.
    Sorry for the confusion...

  13. #13
    quad64bit's Avatar
    quad64bit is offline Moderator
    Join Date
    Jul 2009
    Location
    VA
    Posts
    1,323
    Rep Power
    6

    Default Re: Breakout paddle doesn't move

    That makes it sound like your keyPressed/released methods are never happening, which means the event isn't being caught. When you put the println in the keyPressed method, you didn't nest it in any logic did you? You put the printout on the first line of the method[s]?

  14. #14
    Join Date
    Aug 2012
    Posts
    6
    Rep Power
    0

    Default Re: Breakout paddle doesn't move

    In my keyPressed and keyReleased methods, the println statement is on the first line of code, no logic whatsoever. It should work, and I can't figure out why it isn't.
    Another question... why are both methods, moveLeft() and moveRight(), being called every update? I think that this is also part of the problem, but the key listener isn't working either :(

    JavaProgrammerToo

  15. #15
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,271
    Rep Power
    25

    Default Re: Breakout paddle doesn't move

    why are both methods, moveLeft() and moveRight(), being called every update
    What logic controls when those methods are called? Add some println statements to print out the values of the variables that control when they are called to see why.

    What do you mean by an "update"? What event are you referring to?

    Can you post the code for the current program?
    If you don't understand my response, don't ignore it, ask a question.

Similar Threads

  1. Moving a Paddle with the Mouse
    By aortell24 in forum New To Java
    Replies: 2
    Last Post: 08-06-2012, 11:26 PM
  2. Breakout Paddle
    By Newbieprogrammer in forum New To Java
    Replies: 1
    Last Post: 08-05-2012, 02:02 PM
  3. Replies: 1
    Last Post: 06-25-2012, 11:39 PM
  4. Paddle Class: Trying to code details to ball & paddle..
    By CuppaCoffee in forum New To Java
    Replies: 1
    Last Post: 01-09-2012, 12:14 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
  •