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

Thread: Pong Game won't update

  1. #1
    Junior Member
    Join Date
    Apr 2014
    Posts
    5
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Exclamation Pong Game won't update

    I'm a beginner at java and am trying to code a basic pong game java applet.
    The code has no errors in it but when i run it the .png's do not come up in the window until its moved off screen.
    when the .png's are shown they do not update whatsoever.
    i thought the problem could be with the key-listener but even the ball (which moves independently of user input) does not move.
    I've placed all the code from the 5 classes below.
    there's some unnecessary code in the background class but that's because I'm thinking of making the background scroll later on.

    package main;
     
    import java.applet.Applet;
    import java.awt.Color;
    import java.awt.Frame;
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.net.URL;
     
    public class MainClass extends Applet implements Runnable, KeyListener {
     
    	private Player1 p1;
    	private Player2 p2;
    	private Ball ball;
    	private Image image, paddle1, paddle2, Ball, backTile;
    	private Graphics second;
    	private URL base;
    	private static Background bg;
     
    	@Override
    	public void init() {
     
    		setSize(960, 720);
    		setBackground(Color.DARK_GRAY);
    		setVisible(true);
    		setFocusable(true);
    		addKeyListener(this);
    		Frame frame = (Frame) this.getParent().getParent();
    		frame.setTitle("Pong");
    		try {
    			base = getDocumentBase();
    		} catch (Exception e) {
    			// TODO:handle exception
    		}
     
    		// Image Setups
    		paddle1 = getImage(base, "resource/paddle1.png");
    		paddle2 = getImage(base, "resource/paddle2.png");
    		backTile = getImage(base, "resource/backTile.png");
    		Ball = getImage(base, "resource/Ball.png");
     
    	}
     
     
    	@Override
    	public void start() {
     
    		bg = new Background(0, 0);
    		p1 = new Player1();
    		p2 = new Player2();
    		ball = new Ball();
    		Thread thread = new Thread(this);
    		thread.start();
     
    	}
     
    	@Override
    	public void stop() {
     
    	}
     
    	@Override
    	public void destroy() {
     
    	}
     
    	@Override
    	public void run() {
    		while (true) {
    			p1.update1();
    			p2.update2();
    			ball.update3();
    			bg.update4();
    			repaint();
    			try {
    				Thread.sleep(17);
    			} catch (InterruptedException e) {
    				e.printStackTrace();
     
    			}
     
    		}
     
    	}
     
    	@Override
    	public void update(Graphics g) {
    		if (image == null) {
    			image = createImage(this.getWidth(), this.getHeight());
    			second = image.getGraphics();
    		}
     
    		second.setColor(getBackground());
    		second.fillRect(0, 0, getWidth(), getHeight());
    		second.setColor(getForeground());
    		paint(second);
     
    		g.drawImage(image, 0, 0, this);
    	}
     
    	@Override
    	public void paint(Graphics g) {
    		g.drawImage(backTile, bg.getBgX(), bg.getBgY(), this);
    		g.drawImage(paddle1, p1.getCenterX1()-16, p1.getCenterY1()-63, this);
    		g.drawImage(paddle2, p2.getCenterX2()-16, p2.getCenterY2()-63, this);
    		g.drawImage(Ball, ball.getCenterX3()-16, ball.getCenterY3()-16, this);
     
    	}
     
     
     
    	@Override
    	public void keyPressed(KeyEvent e) {
     
    		switch (e.getKeyCode()) {
     
    		case KeyEvent.VK_W:
    			p1.moveUp1();
    			p1.setMovingUP1(true);
    			break;
     
    		case KeyEvent.VK_S:
    			p1.moveDown1();
    			p1.setMovingDown1(true);
    			break;
     
    		case KeyEvent.VK_UP:
    			p2.moveUp2();
    			p2.setMovingUP2(true);
    			break;
     
    		case KeyEvent.VK_DOWN:
    			p2.moveDown2();
    			p2.setMovingDown2(true);
    			break;
     
    		}
     
    	}
     
    	@Override
    	public void keyReleased(KeyEvent e) {
    		switch (e.getKeyCode()) {
     
    		case KeyEvent.VK_W:
    			p1.stop();
    			break;
     
    		case KeyEvent.VK_S:
    			p1.stop();
    			break;
     
    		case KeyEvent.VK_UP:
    			p2.stop();
    			break;
     
    		case KeyEvent.VK_DOWN:
    			p2.stop();
    			break;
     
    		}
     
    	}
     
    	@Override
    	public void keyTyped(KeyEvent arg0) {
    		// TODO Auto-generated method stub
     
    	}
     
    }

    package main;
     
    public class Player1 {
     
    	final int SPEED = 5;
    	final int CEILING = 71;
    	final int GROUND = 649;
     
    	public int centerX1 = 40;
    	public int centerY1 = GROUND;
    	private boolean movingUp1 = false;
    	private boolean movingDown1 = false;
     
    	private int speedY1 = 0;
     
    	public void update1() {
    		if(speedY1 > 0 && centerY1 > CEILING) {
    			centerY1 += speedY1;
    		}
     
    		if(speedY1 < 0 && centerY1 < GROUND){
    			centerY1 += speedY1;
    		}
     
    	}
     
    	public void moveUp1() {
    		speedY1 = SPEED;
    	}
     
    	public void moveDown1() {
    		speedY1 = -SPEED;
    	}
     
    	public void stop() {
    		if(isMovingUp1() == false && isMovingDown1() == false) {
    			speedY1 = 0;
    		}
     
    		if (isMovingUp1() == false && isMovingDown1() == true) {
    			moveDown1();
    		}
     
    		if (isMovingUp1() == true && isMovingDown1() == false) {
    			moveUp1();
    		}
     
    	}
     
    	public int getCenterY1() {
    		return centerY1;
    	}
     
    	public int getSpeedY1() {
    		return speedY1;
    	}
     
    	public void setCenterY1(int centerY1) {
    		this.centerY1 = centerY1;
    	}
     
    	public void setSpeedY1(int speedY1) {
    		this.speedY1 = speedY1;
    	}
     
    	public int getCenterX1() {
    		return centerX1;
    	}
     
    	public void setCenterX1(int centerX1) {
    		this.centerX1 = centerX1;
    	}
     
    	public boolean isMovingUp1() {
    		return movingUp1;
    	}
     
    	public void setMovingUP1(boolean movingup) {
    		this.movingUp1 = movingUp1;
    	}
     
    	public boolean isMovingDown1() {
    		return movingDown1;
    	}
     
    	public void setMovingDown1(boolean movingdown) {
    		this.movingDown1 = movingDown1;
    	}
     
    }

    package main;
     
    public class Player2 {
     
    	final int SPEED = 5;
    	final int CEILING = 71;
    	final int GROUND = 649;
     
    	public int centerX2 = 920;
    	public int centerY2 = GROUND;
    	private boolean movingUp2 = false;
    	private boolean movingDown2 = false;
     
    	private int speedY2 = 0;
     
    	public void update2() {
    		if(speedY2 > 0 && centerY2 > CEILING) {
    			centerY2 += speedY2;
    		}
     
    		if(speedY2 < 0 && centerY2 < GROUND){
    			centerY2 += speedY2;
    		}
     
    	}
     
    	public void moveUp2() {
    		speedY2 = SPEED;
    	}
     
    	public void moveDown2() {
    		speedY2 = -SPEED;
    	}
     
    	public void stop() {
    		if(isMovingUp2() == false && isMovingDown2() == false) {
    			speedY2 = 0;
    		}
     
    		if (isMovingUp2() == false && isMovingDown2() == true) {
    			moveDown2();
    		}
     
    		if (isMovingUp2() == true && isMovingDown2() == false) {
    			moveUp2();
    		}
     
    	}
     
    	public int getCenterY2() {
    		return centerY2;
    	}
     
    	public int getSpeedY2() {
    		return speedY2;
    	}
     
    	public void setCenterY2(int centerY2) {
    		this.centerY2 = centerY2;
    	}
     
    	public void setSpeedY2(int speedY2) {
    		this.speedY2 = speedY2;
    	}
     
    	public int getCenterX2() {
    		return centerX2;
    	}
     
    	public void setCenterX2(int centerX2) {
    		this.centerX2 = centerX2;
    	}
     
    	public boolean isMovingUp2() {
    		return movingUp2;
    	}
     
    	public void setMovingUP2(boolean movingup) {
    		this.movingUp2 = movingUp2;
    	}
     
    	public boolean isMovingDown2() {
    		return movingDown2;
    	}
     
    	public void setMovingDown2(boolean movingdown) {
    		this.movingDown2 = movingDown2;
    	}
     
    }

    package main;
     
    import java.util.Random;
     
    public class Ball {
     
    	private Player1 p1;
    	private Player2 p2;
     
    	final int SPEED =  8;
    	final int CEILING = 71;
    	final int GROUND = 649;
     
    	private int centerX3 = 480;
    	private int centerY3 = 360;
     
    	private int speedX3 = SPEED;
    	private int speedY3 = SPEED;
     
    	Random rand = new Random();
     
    	public int dir = rand.nextInt(5) + 1;
     
    	public void update3() {
     
    		if(centerX3-16 == p1.centerX1+16 && centerY3 >= p1.centerY1-63 || centerX3-16 == p1.centerX1+16 && centerY3 <= p1.centerY1+63 ) {
    			dir = rand.nextInt(2)+1;
    			moveBall2();
    		}
     
    		else if(centerX3+16 == p2.centerX2-16 && centerY3 >= p2.centerY2-63 || centerX3-16 == p2.centerX2+16 && centerY3 <= p2.centerY2+63) {
    			dir = rand.nextInt(2)+1;
    			moveBall4();
    		}
     
    		else if(centerY3 == CEILING) {
    			dir = rand.nextInt(2)+1;
    			moveBall3();
    		}
     
    		else if(centerY3 == GROUND) {
    			dir = rand.nextInt(2)+1;
    			moveBall1();
    		}
     
    		else {
    			move();
    		}
     
    	}
     
    	public int getCenterX3() {
    		return centerX3;
    	}
     
    	public void setCenterX3(int centerX3) {
    		this.centerX3 = centerX3;
    	}
     
    	public int getCenterY3() {
    		return centerY3;
    	}
     
    	public void setCenterY3(int centerY3) {
    		this.centerY3 = centerY3;
    	}
     
    	public void move() {
    		centerX3 += speedX3;
    		centerY3 += speedY3;
    	}
     
    	public void moveBall1() {
    		switch(dir) {
     
    		case 1:
    			speedX3 = -SPEED;
    			speedY3 = -SPEED;
    			move();
    			break;
     
     
    		case 2:
    			speedX3 = SPEED;
    			speedY3 = -SPEED;
    			move();
    			break;
     
     
     
    		}
    	}
     
    	public void moveBall2() {
    		switch(dir) {
     
    		case 1:
    			speedX3 = SPEED;
    			speedY3 = -SPEED;
    			move();
    			break;
     
     
    		case 2:
    			speedX3 = SPEED;
    			speedY3 = SPEED;
    			move();
    			break;
     
     
     
    		}
    	}
     
    	public void moveBall3() {
    		switch(dir) {
     
    		case 1:
    			speedX3 = -SPEED;
    			speedY3 = SPEED;
    			move();
    			break;
     
     
    		case 2:
    			speedX3 = SPEED;
    			speedY3 = SPEED;
    			move();
    			break;
     
     
     
    		}
    	}
     
    	public void moveBall4() {
    		switch(dir) {
     
    		case 1:
    			speedX3 = -SPEED;
    			speedY3 = -SPEED;
    			move();
    			break;
     
     
    		case 2:
    			speedX3 = -SPEED;
    			speedY3 = SPEED;
    			move();
    			break;
     
     
     
    		}
    	}
     
     
     
     
     
    }

    package main;
     
    public class Background {
     
    	private int bgX, bgY;
     
    	public Background(int x, int y){
    		bgX = 0;
    		bgY = 0;
    	}
     
    	public void update4() {
     
     
    	}
     
    	public int getBgX() {
    		return bgX;
    	}
     
    	public int getBgY() {
    		return bgY;
    	}
     
     
    	public void setBgX(int bgX) {
    		this.bgX = bgX;
    	}
     
    	public void setBgY(int bgY) {
    		this.bgY = bgY;
    	}
     
     
    }


  2. #2
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Pong Game won't update

    Welcome to the forum! Thanks for taking the time to learn how to post code correctly. If you haven't already, please read this topic to learn other useful info for new members.

    Are you restricted to using AWT rather than the more modern Swing?

  3. #3
    Junior Member
    Join Date
    Apr 2014
    Posts
    5
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Pong Game won't update

    I dont know if I'm restricted but awt is what i've learned to use. does it make much of a difference?

  4. #4
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Pong Game won't update

    Don't leave catch blocks empty. It's a bad habit and pointless.
    does it make much of a difference?
    It can, but mostly Swing builds on AWT in many ways, improving it, making it more programmer friendly and capable.

    Are you monitoring the console output as your program runs? Are you getting any exceptions other than the uncaught one?

  5. #5
    Junior Member
    Join Date
    Apr 2014
    Posts
    5
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Pong Game won't update

    This is the console output when I run the program.

    Exception in thread "AWT-EventQueue-1" java.lang.NullPointerException
    at main.MainClass.paint(MainClass.java:105)
    at sun.awt.RepaintArea.paintComponent(Unknown Source)
    at sun.awt.RepaintArea.paint(Unknown Source)
    at sun.awt.windows.WComponentPeer.handleEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$200(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPri vilege(Unknown Source)
    at java.security.ProtectionDomain$1.doIntersectionPri vilege(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPri vilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilter s(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(U nknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarch y(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)
    Exception in thread "Thread-3" java.lang.NullPointerException
    at main.Ball.update3(Ball.java:26)
    at main.MainClass.run(MainClass.java:74)
    at java.lang.Thread.run(Unknown Source)

  6. #6
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Pong Game won't update

    Ahhh. You have some NPEs to find and fix. Since I was able to mostly run your code and from the error message/stack trace you've posted, I see the NPE occurs in the paint() method. Check line number 105 and determine which object is null and fix it.

    I also noted that class Ball contains objects that have not been initialized which you may have meant to not be declared at all. Rather, you may have meant those objects (p1, p2, and others) to be the same as those in MainClass.

    I forgot: I also noted that you call setVisible() before the Applet's components are all initialized. Setting the container visible will attempt to draw it by calling the paint() method. There are objects in the paint() method that have not been initialized before the setVisible() method is called. Order sometimes matters.

  7. #7
    Junior Member
    Join Date
    Apr 2014
    Posts
    5
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Pong Game won't update

    Thanks a lot for replying to this. Its helped me with learning to analyze code.
    I realized i could get rid of the setVisible() call as it's not needed with applets.
    Ive looked over the code repeatedly, mostly the parts you specified and I've made a few changes but i cant seem to find whats stopping the program from running .
    the image loads and shows the background, the two paddles and the ball in their original positions but nothing moves.
    I'm thinking the problem must be in the mainClass since everything isn't working.
    this is my first proper java code so it could just be something really simple that i'm missing.

  8. #8
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Pong Game won't update

    When you make changes to your code, post the updates. Since I don't know what you've done, I can only help you with your original code, and you've already moved on from there.

    I recommend that you test your code incrementally and in small enough chunks that you are able to catch errors early, fixing and learning from small errors as you code. If the first time you tried to compile and test this code was after all 5 classes were written pretty much as they are in your first post, then you're missing valuable opportunities to improve your code along the way, AND you end up with a much larger mess to fix than if you'd tested smaller blocks of code. For example, you should have first tested something like this:
    import java.applet.Applet;
    import java.awt.Color;
    import java.awt.Graphics;
     
    public class TestClass extends Applet
    {
    	@Override
    	public void init()
    	{
    		setSize(960, 720);
    		setBackground(Color.DARK_GRAY);
     
    	} // end method init()
     
    	@Override
    	public void paint(Graphics g)
    	{
    		// call paint on the parent to ensure all included lightweight
    		// components are painted
    		super.paint( g );
     
    		// due to the dark background, set the drawing color light
    		g.setColor( Color.WHITE );
     
    		// draw a simple message on the applet
    		g.drawString( "Hello World!", 50, 50 );
     
    	} // end method paint()
     
    } // end class TestClass
    From there, continue adding needed functionality and features, testing each change as you go.

    Another point I'll make about the code you've posted is that overriding the update() method is an advanced technique that should be avoided. There are some methods in Java that CAN be overridden, but that doesn't mean they should be or that it's good practice. There may be times when solving a complex programming problem requires overriding one of the methods that CAN be but SHOULDN'T be, but this isn't one of those times.

    Post your updated code - only the updates - when you can.

  9. #9
    Junior Member
    Join Date
    Apr 2014
    Posts
    5
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Pong Game won't update

    Thanks so much again for helping with this.
    You were right about the problem. it was the uninitialized objects in the ball class.
    I changed the line "private Player1 p1" to "private Player1 p1 = MainClass.getp1();"
    and "private Player2 p2" to "private Player2 p2 = Mainclass.getp2();"
    and created the necessary methods in the MainClass.

    the code still has a few input related errors but its running now, and i think i can fix the myself.
    Im completely new to Java programming so thanks so much for all the advice. it was genuinely more help than i expected to get from a forum.
    i'd appreciate any other tips you have in regards to good practise and bad habits.

  10. #10
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Pong Game won't update

    Glad to help, and it sounds like that with just a few hints you've made good progress. You mentioned that you've gotten more help from a forum than you thought you'd get, but you've done more with the little bit of help you've gotten than most. You have aptitude, you take direction, and you have potential.

    As for tips, I'll bore you with the same ones I give everyone else: build a solid foundation of basic tools and skills, including a thorough understanding of Object Oriented Programming (OOP) principles, before moving to graphical interfaces, document your code, and (a bonus) switch from AWT to Swing when you do begin/continue your graphical programming studies.

    Keep coding!

  11. The Following User Says Thank You to GregBrannon For This Useful Post:

    jimbagas (April 21st, 2014)

Similar Threads

  1. [SOLVED] Need help with Pong game
    By SauronWatchesYou in forum What's Wrong With My Code?
    Replies: 4
    Last Post: April 16th, 2014, 06:57 AM
  2. Why, won't this update?
    By Jerba in forum What's Wrong With My Code?
    Replies: 4
    Last Post: October 5th, 2012, 09:06 PM
  3. How to defeat computer in a Java game? (Pong)
    By DJBENZ10 in forum Java Theory & Questions
    Replies: 3
    Last Post: July 13th, 2012, 01:00 PM
  4. Pong game - Collision detection
    By Hokap in forum Java Theory & Questions
    Replies: 73
    Last Post: May 13th, 2012, 04:11 PM
  5. [SOLVED] Fixing of bug for Pong game
    By phoenix in forum What's Wrong With My Code?
    Replies: 11
    Last Post: July 14th, 2009, 01:19 PM