Skip to main content
gamedev.net
🔒 Locked

[java] Java pong

Started by Adi5 May 18, 2008 at 9:57 AM 5 replies 2.2k views
Original Post
Adi5
Adi5
Right first of all i want to say hello to everybody since i have recently registered. Now i know this is kinda greedy and i might not have a right to ask it since i just registered but i need help creating a game of pong in java. Now i'm been on the site for a while searched through the forums anyways i was using a tutorial written by Adam king but sadly the site that displayed his source code is down and without it i can't understand how to make the game. Basicly what i know is how to draw the paddles and the ball but from that point on i have no idea what i'm doing. I know the basics behind key listener but i don't know how to implement it within the game. For example i know how to draw the paddle but not how to implement moving it up and down. Now i'm wondering if anybody can help me step by step in creating the game. I would really apreciate it Thanks in advance
Glass_Knife
Glass_Knife
These articles I wrote might help.

Active Rendering
Keyboard and Mouse

Just remember that writing you first game is the hardest. A lot of people have high hopes for their first game, and never finish it because they want to do too much. Hang in there. Game programming is a journey, not a destination.


Adi5
Adi5
Thanks a lot your tutorials helped me a lot i have managed to make the paddles for player 1 & 2 and managed to make them move. Now i have to make the ball and the goals do you know of any good tutorials for the ball physics and the goals?




Swattkidd
Swattkidd
Well the goals are just if the ball passes the paddles (meaning they go off of the screen) so just check and see if the ball goes off the screen, and depending on which direction it went off the screen give the point to player 1 or player 2.
Adi5
Adi5
Hey guys i'm having a small bug with my project and i can't figure out the problem so i'm hoping that you can look at it and see whats up. The thing is when i use else if (f<0) that is when i don't call the ball.hit the whole thing works fine that is to say it makes the ball bounce off the walls. I implemented this to make it bounce off the paddles and for some reason it doesn't work. Also for some reason the else if thats commented out of the project is always activated if its not commented out. I can;t figure out why. I will wait for your reply and hope that you can help me.

Thanks in advance



main class (where the problem is its under draw ball)


package pong_main;
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.util.*;
import javax.swing.JFrame;
import paddles.Paddles;
import ball.Ball;

public class Game_Main extends JFrame {

static final int WIDTH = 640;
static final int HEIGHT = 480;
public static int f = 0; // ball position
public static int g = 0; // ball position
public static int speedX = 6; // ball speed
public static int speedY = 6; // ball speed
public static int x1 = 0; // paddle 1 position
public static int y1 = 0; // paddle 1 position
public static int x2 = 0; // paddle 2 position
public static int y2 = 0; // paddle 2 position

public static boolean progres = true;
class Paddle_1 { int w, h, dy; }
class Paddle_2 { int w, h, dy; }
Paddles paddles = new Paddles(); // Keyboard polling
Canvas canvas; // Our drawing component
Paddle_1 paddle_1 = new Paddle_1(); // Player 1 paddle
Paddle_2 paddle_2 = new Paddle_2(); // Player 2 paddle

public Game_Main() {

setIgnoreRepaint( true );
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
canvas = new Canvas();
canvas.setIgnoreRepaint( true );
canvas.setSize( WIDTH, HEIGHT );
add( canvas );
pack();

addKeyListener( paddles );
canvas.addKeyListener( paddles );

x2 = y2 = 50;
paddle_2.dy = 5;
paddle_2.w = 10;
paddle_2.h =60;

x1 = y1 = 575;
paddle_1.dy = 5;
paddle_1.w = 10;
paddle_1.h =60;
}

public void run() {

canvas.createBufferStrategy( 2 );
BufferStrategy buffer = canvas.getBufferStrategy();
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gd.getDefaultConfiguration();
BufferedImage bi = gc.createCompatibleImage( WIDTH, HEIGHT );

Graphics graphics = null;
Graphics2D g2d = null;
Color background = Color.BLACK;
while( progres ) {
try {

// Poll the paddles
paddles.poll();
// Should we exit?
if( paddles.keyDownOnce( KeyEvent.VK_ESCAPE ) )
break;

// Clear the back buffer
g2d = bi.createGraphics();
g2d.setColor( background );
g2d.fillRect( 0, 0, WIDTH, HEIGHT );

// Tutorial
g2d.setColor( Color.WHITE );
g2d.drawString( "Use arrow keys to move player 2", 20, 20 );
g2d.drawString( "Use W,S to move player 1", 20, 32 );
g2d.drawString( "Press ESC to exit", 20, 44 );

// Move Paddles
processInput();

// Draw Players 1 & 2
g2d.setColor( Color.WHITE );
g2d.fillRect( x1, y1, paddle_1.w, paddle_1.h );
g2d.fillRect( x2, y2, paddle_2.w, paddle_2.h );

// Draw Ball
Ball ball = new Ball();
if (f>=640)
speedX = -speedX;
else if (f<0 && ball.hit1() == true)
speedX = - speedX;
if (g>=480){
speedY = -speedY;
}
//else if (g>=480)
// {
// progres = false;
// }
if (g<0 && ball.hit1() == true)
speedY = -speedY;
// else if (g<=0){
// progres = false;
// }
f = f + speedX;
g = g + speedY;
g2d.fillOval(f,g, 20,20);


// Blit image and flip...
graphics = buffer.getDrawGraphics();
graphics.drawImage( bi, 0, 0, null );
if( !buffer.contentsLost() )
buffer.show();

// Let the OS have a little time...
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}

} finally {
// Release resources
if( graphics != null )
graphics.dispose();
if( g2d != null )
g2d.dispose();
}
}
}
protected void processInput() {
// If moving down
if( paddles.keyDown( KeyEvent.VK_DOWN ) ) {
y1 += paddle_1.dy;
// Check collision with botton
if( y1 + paddle_1.h > HEIGHT - 1 )
y1 = HEIGHT - paddle_1.h - 1;
}
// If moving up
if( paddles.keyDown( KeyEvent.VK_UP ) ) {
y1 -= paddle_1.dy;
// Check collision with top
if(y1 < 0 )
y1 = 0;
}

if( paddles.keyDown( KeyEvent.VK_S ) ) {
y2 += paddle_2.dy;
// Check collision with botton
if( y2 + paddle_2.h > HEIGHT - 1 )
y2 = HEIGHT - paddle_2.h - 1;
}
// If moving up
if( paddles.keyDown( KeyEvent.VK_W ) ) {
y2 -= paddle_2.dy;
// Check collision with top
if( y2 < 0 )
y2 = 0;
}

}


public static void Initilize() {

Game_Main app = new Game_Main();
app.setTitle( "Pong" );
app.setVisible( true );
app.run();
System.exit( 0 );




}
public static boolean isProgres() {
return progres;
}

public static void setProgres(boolean progres) {
Game_Main.progres = progres;
}


public static int getX1() {
return x1;
}

public static void setX1(int x1) {
Game_Main.x1 = x1;
}

public static int getY1() {
return y1;
}

public static void setY1(int y1) {
Game_Main.y1 = y1;
}

public static int getX2() {
return x2;
}

public static void setX2(int x2) {
Game_Main.x2 = x2;
}

public static int getY2() {
return y2;
}

public static void setY2(int y2) {
Game_Main.y2 = y2;
}
}








ball class


package ball;
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.util.*;
import javax.swing.JFrame;
import pong_main.Game_Main;
public class Ball {

public boolean hit1() {
boolean bounceoff1 = false;
int B1 = 0;
while (B1<60){
if ( Game_Main.y1 == Game_Main.g + B1){
bounceoff1 = true;
}

B1++;
}
return bounceoff1;
}
public boolean hit2(){
boolean bounceoff2 = false;
int B2 = 0;
while (B2<60){
if(Game_Main.y2 == Game_Main.g + B2){
bounceoff2 = true;
}
B2++;
}
return bounceoff2;
}



}




paddles class

package paddles;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class Paddles implements KeyListener {

private static final int KEY_COUNT = 256;

private enum KeyState {
RELEASED, // Not down
PRESSED, // Down, but not the first time
ONCE // Down for the first time
}

// Current state of the keyboard
private boolean[] currentKeys = null;

// Polled keyboard state
private KeyState[] keys = null;

public Paddles() {
currentKeys = new boolean[ KEY_COUNT ];
keys = new KeyState[ KEY_COUNT ];
for( int i = 0; i < KEY_COUNT; ++i ) {
keys[ i ] = KeyState.RELEASED;
}
}

public synchronized void poll() {
for( int i = 0; i < KEY_COUNT; ++i ) {
// Set the key state
if( currentKeys[ i ] ) {
// If the key is down now, but was not
// down last frame, set it to ONCE,
// otherwise, set it to PRESSED
if( keys[ i ] == KeyState.RELEASED )
keys[ i ] = KeyState.ONCE;
else
keys[ i ] = KeyState.PRESSED;
} else {
keys[ i ] = KeyState.RELEASED;
}
}
}

public boolean keyDown( int keyCode ) {
return keys[ keyCode ] == KeyState.ONCE ||
keys[ keyCode ] == KeyState.PRESSED;
}

public boolean keyDownOnce( int keyCode ) {
return keys[ keyCode ] == KeyState.ONCE;
}

public void keyPressed( KeyEvent e ) {
int keyCode = e.getKeyCode();
if( keyCode >= 0 && keyCode < KEY_COUNT ) {
currentKeys[ keyCode ] = true;
}
}

public void keyReleased( KeyEvent e ) {
int keyCode = e.getKeyCode();
if( keyCode >= 0 && keyCode < KEY_COUNT ) {
currentKeys[ keyCode ] = false;
}
}

public void keyTyped( KeyEvent e ) {
// Not needed
}
}


run class(i made this just cos i can;t start the project out of my main class for some reason but thats not a problem)

package pong_main;

import pong_main.Game_Main;

public class Run {



public static void main(String args[]){
Game_Main main = new Game_Main();
main.Initilize();

}
}




Adi5
Adi5
Ok so now i've made the game everything works but there is a new problem. I made a simple start page with two buttons new game and exit. Now when i press new game it opens the pong window but its all messed up that is to say it doesn't work nothing works except the ball which moves until a goal is scored. Any ideas as to why this is happening. Also after one of the goals is scored the game should print out Player 1 or 2 depending on who scored the goal wins but it only works for player 2 with player 1 it prints it for a second and then removes it


Main


package pong_main;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.util.*;
import javax.swing.JFrame;
import paddles.Paddles;
import ball.Ball;
import java.awt.Graphics2D;

public class Game_Main extends JFrame {
Random random = new Random();
static final int WIDTH = 640;
static final int HEIGHT = 480;
static int f = 0; // ball position
public static int g = 0; // ball position
public static int speedX = 8; // ball speed
public static int speedY = 6; // ball speed
public static int x1 = 0; // paddle 1 position
public static int y1 = 0; // paddle 1 position
public static int x2 = 0; // paddle 2 position
public static int y2 = 0; // paddle 2 position

public static boolean progres = true;
class Paddle_1 { int w, h, dy; }
class Paddle_2 { int w, h, dy; }
Paddles paddles = new Paddles(); // Keyboard polling
Canvas canvas; // Our drawing component
Paddle_1 paddle_1 = new Paddle_1(); // Player 1 paddle
Paddle_2 paddle_2 = new Paddle_2(); // Player 2 paddle


public Game_Main() {

setIgnoreRepaint( true );
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
canvas = new Canvas();
canvas.setIgnoreRepaint( true );
canvas.setSize( WIDTH, HEIGHT );
add( canvas );
pack();

addKeyListener( paddles );
canvas.addKeyListener( paddles );


x2 = 50;
paddle_2.dy = 6;
paddle_2.w = 10;
paddle_2.h =60;

y1 = y2 = 350;

x1 = 570;
paddle_1.dy = 6;
paddle_1.w = 10;
paddle_1.h =60;
}


public void run() {

canvas.createBufferStrategy( 2 );
BufferStrategy buffer = canvas.getBufferStrategy();
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gd.getDefaultConfiguration();
BufferedImage bi = gc.createCompatibleImage( WIDTH, HEIGHT );

Graphics graphics = null;
Graphics2D g2d = null;
Color background = Color.BLACK;
while( progres ) {
try {

// Poll the paddles
paddles.poll();
// Should we exit?
if( paddles.keyDownOnce( KeyEvent.VK_ESCAPE ) )
break;

// Clear the back buffer
g2d = bi.createGraphics();
g2d.setColor( background );
g2d.fillRect( 0, 0, WIDTH, HEIGHT );

// Tutorial
g2d.setColor( Color.WHITE );
g2d.drawString( "Use arrow keys to move player 2", 20, 20 );
g2d.drawString( "Use W,S to move player 1", 20, 32 );
g2d.drawString( "Press ESC to exit", 20, 44 );

// Move Paddles
processInput();

// Draw Players 1 & 2
g2d.setColor( Color.WHITE );
g2d.fillRect( x1, y1, paddle_1.w, paddle_1.h );
g2d.fillRect( x2, y2, paddle_2.w, paddle_2.h );

// Draw Ball
Ball ball = new Ball();

g2d.fillOval(f,g, 20,20);

{

int f = this.f, g = this.g;

if(speedX > 0)
f += 20;
if(speedY > 0)
g += 20;

if (f >= 640 || f <= 0)
speedX = -speedX;
if (g >= 480 || g <= 0)
speedY = -speedY;

if((f >= x1 && f <= (x1 + paddle_1.w)) && (g >= y1 && (g <= y1 + paddle_1.h))
||(f >= x2 && f <= x2 + paddle_2.w) && (g >= y2 && g <= y2 + paddle_2.h))
speedX = -speedX;
else if (f<= 0){
speedX = 0;
speedY = 0;
g2d.setColor( Color.WHITE ); //This is where i set the code for printing out the text
g2d.drawString("Player 2 Wins", 100, 200); //This is where i set the code for printing out the text
Restart restart = new Restart(); //This is where i set the code for printing out the text
}

else if (f>= 640){
speedX = 0;
speedY = 0;
g2d.setColor( Color.WHITE ); //This is where i set the code for printing out the text
g2d.drawString("Player 1 Wins", 100, 200); //This is where i set the code for printing out the text
Restart restart = new Restart(); //This is where i set the code for printing out the text
}
}

f = f + speedX;
g = g + speedY;




// Blit image and flip...
graphics = buffer.getDrawGraphics();
graphics.drawImage( bi, 0, 0, null );
if( !buffer.contentsLost() )
buffer.show();

// Let the OS have a little time...
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}

} finally {
// Release resources
if( graphics != null )
graphics.dispose();
if( g2d != null )
g2d.dispose();
}
}
}
protected void processInput() {
// If moving down
if( paddles.keyDown( KeyEvent.VK_DOWN ) ) {
y1 += paddle_1.dy;
// Check collision with botton
if( y1 + paddle_1.h > HEIGHT - 1 )
y1 = HEIGHT - paddle_1.h - 1;
}
// If moving up
if( paddles.keyDown( KeyEvent.VK_UP ) ) {
y1 -= paddle_1.dy;
// Check collision with top
if(y1 < 0 )
y1 = 0;
}

if( paddles.keyDown( KeyEvent.VK_S ) ) {
y2 += paddle_2.dy;
// Check collision with botton
if( y2 + paddle_2.h > HEIGHT - 1 )
y2 = HEIGHT - paddle_2.h - 1;
}
// If moving up
if( paddles.keyDown( KeyEvent.VK_W ) ) {
y2 -= paddle_2.dy;
// Check collision with top
if( y2 < 0 )
y2 = 0;
}

}


public static void Initilize() {

Game_Main app = new Game_Main();
app.setTitle( "Pong" );
app.setVisible( true );
app.run();
System.exit( 0 );



}
}





New game window



package start_finish;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import pong_main.Game_Main;


public class Start extends JFrame{

private JButton newGame;
private JButton exit;

public Start(){

super("Chose");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(640,480);
setResizable(false);
setLayout(null);
setContentPane(new MyPanel());
setLocationRelativeTo(null);

newGame = new JButton("NEW GAME");
newGame.setBounds(250, 100, 150, 50);

exit = new JButton("EXIT");
exit.setBounds(250, 200, 150, 50);

newGameAction nghandler = new newGameAction();
exitAction ehandler = new exitAction();

newGame.addActionListener(nghandler);
exit.addActionListener(ehandler);


add(newGame);
add(exit);


setVisible(true);



}

private class newGameAction implements ActionListener{


public void actionPerformed(ActionEvent e) {

Game_Main game = new Game_Main(); //This should call the Game_Main class normal and start the game but it does not
game.Initilize(); //

setVisible(false); // this just closes the window after it is used



}


}

private class exitAction implements ActionListener{


public void actionPerformed(ActionEvent e) {

System.exit(1);



}


}

public class MyPanel extends JPanel{

private Image img;
public MyPanel(){
setLayout(null);

try{

java.net.URL imageURL = Start.class.getResource("Background finished.JPG");
img = new ImageIcon(imageURL).getImage();
}catch(NullPointerException ex){
System.err.println(ex); }




}

public void drawBackground(Graphics g){

int w = getWidth();
int h = getHeight();
int iw = img.getWidth(this);
int ih = img.getHeight(this);


for(int i = 0; i
for(int j=0; j
g.drawImage(img,i,j,this);
}

}
}

protected void paintComponent(Graphics g){

super.paintComponent(g);
drawBackground(g);
}

}

Istaril
Istaril
I noticed that your Swing application is always running on the main thread. This is something a lot of people developing in Swing don't know, but you need to initialize your main JFrame in another thread otherwise you might get a lot of strange behavior from your Swing application.

Also all the Swing listeners (KeyboardListener for example) use the same thread for handling events, so you should avoid using too much logic in them otherwise your application will be less responsive, though you seems to be fine with your program right now. Just wanted to warn you about that.

For more info on the subject check out this part of the Swing tutorial :
http://java.sun.com/docs/books/tutorial/uiswing/concurrency/index.html

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.