• Welcome to the PopMalt Forums! Whether you're new to forums or a veteran, welcome to our humble home on the web! We're a 20-year old forum community with thousands of discussions on entertainment, lifestyle, leisure, and more.

    Our rules are simple. Be nice and don't spam. Registration is free, so what are you waiting for? Join today!.

Need help getting Pong to work in Java

pineappelle

New Member
I am making Pong with Java and using Jcreator to compile and run it but I can't get the paddles to function quite right. the code below is as far as i can get.

Code:
/**
 * @(#)pong.java
 *
 * pong Applet application
 *
 * @author
 * @version 1.00 2012/2/15
 */

import java.awt.*;
import java.applet.*;
import java.awt.event.*;

public class pong extends java.applet.Applet implements KeyListener, Runnable {

	Graphics screen, offscreen;
	Rectangle ball;
	Thread runner;
	int y, x, character_int, y2, x2, ballx, bally, xmove, ymove;
	Image workspace;

	public void init() {

		requestFocus();
		addKeyListener(this);
		y=5;
		x=5;
		x2=580;
		y2=5;
		workspace=createImage(600,400);
		offscreen=workspace.getGraphics();
		ball=new Rectangle();
		ball.x=150;
		ball.y=200;
		ball.width=20;
		ball.height=20;
		xmove=3;
		ymove=3;

	}

	public void keyPressed(KeyEvent event) {
		character_int=event.getKeyCode();

		if (character_int==40) {
			y=y+10;
			repaint();
		}
		else if(character_int==38) {
			y=y-10;
			repaint();
		}
		else if(character_int==39) {
			y2=y2+10;
			repaint();
		}
		else if(character_int==37) {
			y2=y2-10;
			repaint();
		}

	}

	public void keyReleased(KeyEvent event) {
	}

	public void keyTyped(KeyEvent event) {
	}

	public void paint(Graphics screen) {

		offscreen.setColor(Color.white);
		offscreen.fillRect(0,0,600,400);
		offscreen.setColor(Color.black);
		offscreen.fillOval(ball.x,ball.y,ball.width,ball.height);
		offscreen.fillRect(x,y,20,100);
		offscreen.fillRect(x2,y2,20,100);
		offscreen.drawLine(300,0,300,400);
		offscreen.drawRect(0,0,599,399);
		screen.drawImage(workspace,0,0,600,400,this);

	}

	public void start() {
		if(runner==null) {
			runner=new Thread(this);
			runner.start();
		}
	}

	public void run() {
		while(true) {
			repaint();;
			checkbounce();
			ball.x=ball.x+xmove;
			ball.y=ball.y+ymove;
			try {Thread.sleep(20);}
			catch(InterruptedException e) {}
		}
	}

	public void checkbounce() {
		if(ball.x<0||ball.x+20>600) {
			xmove=xmove*-1;
		}
		if(ball.y<0||ball.y+20>400) {
			ymove=ymove*-1;
		}
		if(ball.x<25&&ball.y>y&&ball.y<y+100||ball.x>580&&ball.y>y2&&ball.y<y2+100) {
			xmove=xmove*-1;
		}
	}

	public void stop() {
		if(runner!=null) {
			runner.stop();
			runner=null;
		}
	}

	public void update(Graphics screen) {
		paint(screen);
	}

}
 
Top