Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
* * * * - 2 votes

Game - A simple Pong

pong game java

  • Please log in to reply
31 replies to this topic

#13 cantinflat

cantinflat

    CC Lurker

  • Just Joined
  • Pip
  • 1 posts

Posted 26 January 2011 - 08:53 PM

hello friend, what key i need to press to play??? i press "w", and "s", "up" and "down", "enter" and "space" and nothing happens, its not moving, gracias
  • 0

#14 Tasman

Tasman

    CC Lurker

  • Just Joined
  • Pip
  • 1 posts
  • Learning:Java, C#, PL/SQL

Posted 28 January 2011 - 05:22 PM

Great
  • 0

#15 Whur

Whur

    CC Lurker

  • Just Joined
  • Pip
  • 2 posts

Posted 04 February 2011 - 05:46 AM

hello friend, what key i need to press to play??? i press "w", and "s", "up" and "down", "enter" and "space" and nothing happens, its not moving, gracias


w s up down are right but did you remove the semicolons ( ; ) at the end of the 2 lines marked in the post above
  • 0

#16 MadScientist

MadScientist

    CC Lurker

  • Just Joined
  • Pip
  • 1 posts

Posted 28 May 2011 - 12:18 AM

No offense, but you have a lot of useless things in your code. All those keylisteners in your main class aren't even used. It works fine without them. Also, you used a lot of extra lines making methods that return simple things.
  • 0

#17 are-lynn

are-lynn

    CC Lurker

  • Just Joined
  • Pip
  • 1 posts

Posted 24 February 2012 - 11:06 PM

can i know what data structure that u use in this game~
or this game doesnt have any data structure?
  • 0

#18 NeonSoda

NeonSoda

    CC Lurker

  • Just Joined
  • Pip
  • 2 posts

Posted 26 February 2012 - 05:34 PM

I know this threads a few years old but i spent a few minutes changing all of the spanish to english, I know its more than likely the first thing english reading programmers will do so the "Main":

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Main extends JFrame {

	private static final long serialVersionUID = 1L; // Eclipse added this automatically

	private JPanel jContentPane = null;
	
	private PanelBall panel = null; // This is the panel of the game class
	
	private PanelBall getPanel() {
		if (panel == null) {
			panel = new PanelBall(); // The panel is created
		}
		return panel;
	}

	/**
	 * This is the default constructor
	 */
	public Main() {
		super();
		initialize();
        // Listeners for the keyboard
        this.addKeyListener(new KeyAdapter() {
        	//Method for the key pressed
            public void keyPressed(KeyEvent evt) {
                formKeyPressed(evt);
            }
            // Method for the key released
            public void keyReleased(KeyEvent evt) {
                formKeyReleased(evt);
            }
        });
		
	}
	
    //	Here i'm stating the method that will send the key pressed to the game class
	private void formKeyPressed(KeyEvent evt)
    {
        panel.keyPressed(evt);
    }
    
    //	Here i'm stating the method that will send the key released to the game class
    private void formKeyReleased(KeyEvent evt)
    {
        panel.keyReleased(evt);
    }

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		this.setResizable(false);
		this.setBounds(new Rectangle(312, 184, 250, 250)); // Position on the desktop
		this.setMinimumSize(new Dimension(250, 250));
		this.setMaximumSize(new Dimension(250, 250));
		this.setContentPane(getJContentPane());
		this.setTitle("Pong");
	}

	/**
	 * This method initializes jContentPane
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getJContentPane() {
		if (jContentPane == null) {
			jContentPane = new JPanel();
			jContentPane.setLayout(new BorderLayout());
			jContentPane.add(getPanel(), BorderLayout.CENTER);
		}
		return jContentPane;
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				Main thisClass = new Main();
				thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
				thisClass.setVisible(true);
			}
		});
	}
}

and "PanelBall":

import java.awt.*;
import java.awt.event.KeyEvent;
import javax.swing.*;


public class PanelBall extends JPanel implements Runnable {
	
	private static final long serialVersionUID = 1L;
        // Positions on X and Y for the ball, player 1 and player 2
	private int ballX = 10, ballY = 100, player1X=10, player1Y=100, player2X=230, player2Y=100;
	Thread thread;
	int right=5; // to the right
	int left= -5; //to the left
	int up=5; // upward
	int down= -5; // down
	int width, alto; // Width and height of the ball
	// Scores
	int contPlayer1=0, contPlayer2=0;
	boolean player1FlagArr,player1FlagAba, player2FlagArr, player2FlagAba;
	boolean game, gameOver;
	
	public PanelBall(){
		game=true;
		thread=new Thread(this);
		thread.start();
	}
	
	// Draw ball and ships
	public void paintComponent(Graphics gc){
		setOpaque(false);
		super.paintComponent(gc);
		
		// Draw ball
		gc.setColor(Color.black);
		gc.fillOval(ballX, ballY, 8,8);
		
		// Draw ships
		gc.fillRect(player1X, player1Y, 10, 25);
		gc.fillRect(player2X, player2Y, 10, 25);
		
		//Draw scores
		gc.drawString("player 1: "+contPlayer1, 25, 10);
		gc.drawString("player 2: "+contPlayer2, 150, 10);
		
		if(gameOver)
			gc.drawString("Game Over", 100, 125);
	}
	
	// Positions on X and Y for the ball
	public void drawball (int nx, int ny)
	{
		ballX= nx; 
		ballY= ny; 
		this.width=this.getWidth();
		this.alto=this.getHeight();
		repaint();
	}
	
    // Here we receive from the game container class the key pressed
	public void keyPressed(KeyEvent evt)
    {
        switch(evt.getKeyCode())
        {
            // Move ship 1
            case KeyEvent.VK_W :
            	player1FlagArr = true;
            	break;
            case KeyEvent.VK_S : 
            	player1FlagAba = true;
            	break;
                        
            // Move ship 2
            case KeyEvent.VK_UP:
            	player2FlagArr=true;
            	break;
           case KeyEvent.VK_DOWN:
        	   player2FlagAba=true;
            	break;
        }
    }
	
    //	Here we receive from the game container class the key released
    public void keyReleased(KeyEvent evt)
    {
        switch(evt.getKeyCode())
        {
	        // Mover Nave1
	        case KeyEvent.VK_W :
	        	player1FlagArr = false;
	        	break;
	        case KeyEvent.VK_S : 
	        	player1FlagAba = false;
	        	break;
	                    
	        // Mover nave 2
	        case KeyEvent.VK_UP:
	        	player2FlagArr=false;
	        	break;
	        case KeyEvent.VK_DOWN:
	    	   player2FlagAba=false;
	        	break;
        }
    }
    
    // Move player 1
    public void moverPlayer1()
    {
        if (player1FlagArr == true && player1Y >= 0)
            player1Y += down;
        if (player1FlagAba == true && player1Y <= (this.getHeight()-25))
            player1Y += up;
        drawPlayer1(player1X, player1Y);
    }
    
    // Move player 2
    public void moverPlayer2()
    {
        if (player2FlagArr == true && player2Y >= 0)
            player2Y += down;
        if (player2FlagAba == true && player2Y <= (this.getHeight()-25))
            player2Y += up;
        drawPlayer2(player2X, player2Y);
    }
    
    // Position on Y for the player 1
    public void drawPlayer1(int x, int y){
    	this.player1X=x;
    	this.player1Y=y;
    	repaint();
    }
    // Position on Y for the player 2   
    public void drawPlayer2(int x, int y){
    	this.player2X=x;
    	this.player2Y=y;
    	repaint();
    }
	
	public void run() {
		// TODO Auto-generated method stub
		boolean derLeft=false;
		boolean arrAba=false;
		
		while(true){
			
			if(game){
			
            // The ball move from left to right
           	if (derLeft) 
			{
				// Move Right
				ballX += right;
				if (ballX >= (width - 8))
                    derLeft= false;
			}
			else
			{
				// Move Left
				ballX += left;
				if ( ballX <= 0)
                    derLeft =  true;
			}
           	
           	
            // The ball moves from up to down
           	if (arrAba) 
			{
				//Move Up
				ballY += up;
				if (ballY >= (alto - 8))
                    arrAba= false;
					
			}
			else
			{
				// Move Down
				ballY += down;
				if ( ballY <= 0)
					arrAba =  true;
			}
           	drawball(ballX, ballY);
           	
            // Delay
			try 
			{
				Thread.sleep(50);
			}
			catch(InterruptedException ex)
			{
				
			}
			
			// Move player 1
			moverPlayer1();
			
            // Move player 2
			moverPlayer2();
			
            // The score of the player 1 increase
			if (ballX >= (width - 8))
				contPlayer1++;
                			
            // The score of the player 2 increase
			if ( ballX == 0)
				contPlayer2++;
                            			
			// Game over. Here you can change 6 to any value
                        // When the score reach to the value, the game will end
			if(contPlayer1==6 || contPlayer2==6){
				game=false;
			    gameOver=true;
			}
			
			// The ball stroke with the player 1
			if(ballX==player1X+10 && ballY>=player1Y && ballY<=(player1Y+25))
				derLeft=true;
			
            // The ball stroke with the player 2
			if(ballX==(player2X-5) && ballY>=player2Y && ballY<=(player2Y+25))
				derLeft=false;
			}
		}
	}
	
}

It might save someone 5 minutes but none the less. :D

Edited by NeonSoda, 27 February 2012 - 02:26 AM.

  • 0

#19 philipp333

philipp333

    CC Lurker

  • Just Joined
  • Pip
  • 1 posts

Posted 10 April 2012 - 04:06 AM

I have spotted an error in this program. If the score is 5-3 and the player on the left(or right 3-5) ends the game, the program doesn't change the score to 6-3(3-6) but the score remains the same 5-3(3-5). The score will eventually change after 5 minutes, but i don't think that it should be working that way....
Anybody knows how to fix this?
  • 0

#20 Starwarsfrog

Starwarsfrog

    CC Lurker

  • New Member
  • Pip
  • 8 posts
  • Programming Language:Java
  • Learning:Java

Posted 01 November 2012 - 07:37 PM

if you are doing this in notepad what do you save each file as?
  • 0

#21 Chall

Chall

    CC Addict

  • Senior Member
  • PipPipPipPipPip
  • 349 posts
  • Location:Cedar Rapids, IA
  • Programming Language:Java
  • Learning:C, Java, C++, C#, Python, JavaScript, Assembly

Posted 01 November 2012 - 07:40 PM

if you are doing this in notepad what do you save each file as?

You save each file as <Name of file>.java, without the < >'s of course. Main would be saved as Main.java, etc. :)
  • 0
Speaks fluent Java

#22 SethChun

SethChun

    CC Lurker

  • New Member
  • Pip
  • 4 posts

Posted 15 June 2014 - 01:53 PM

Why is it that when I try to javac Main, It has 3 errors in it? 

It says:

 

Main.java:13: error: cannot find symbol

                  private PanelBall panel = null; // This is the panel of the game class

                              ^

                      symbol: class  PanelBall

                      location: class  Main

Main.java:15:error: cannot find symbol

                  private PanelBall getPanel() (

                              ^

                      symbol: class  PanelBall

                      location: class  Main

Main.java:17: error: cannot find symbol

                                                    panel = new PanelBall();// The panel is created

                                                                        ^

                      symbol: class  PanelBall

                      location: class  Main

3 errors


Edited by SethChun, 15 June 2014 - 01:54 PM.

  • 0

#23 Chall

Chall

    CC Addict

  • Senior Member
  • PipPipPipPipPip
  • 349 posts
  • Location:Cedar Rapids, IA
  • Programming Language:Java
  • Learning:C, Java, C++, C#, Python, JavaScript, Assembly

Posted 15 June 2014 - 04:06 PM

Why is it that when I try to javac Main, It has 3 errors in it? 

It says:

 

Main.java:13: error: cannot find symbol

                  private PanelBall panel = null; // This is the panel of the game class

                              ^

                      symbol: class  PanelBall

                      location: class  Main

Main.java:15:error: cannot find symbol

                  private PanelBall getPanel() (

                              ^

                      symbol: class  PanelBall

                      location: class  Main

Main.java:17: error: cannot find symbol

                                                    panel = new PanelBall();// The panel is created

                                                                        ^

                      symbol: class  PanelBall

                      location: class  Main

3 errors

Means it can't find PanelBall/ Doesn't realize it's an object.


  • 0
Speaks fluent Java

#24 SethChun

SethChun

    CC Lurker

  • New Member
  • Pip
  • 4 posts

Posted 15 June 2014 - 07:14 PM

Means it can't find PanelBall/ Doesn't realize it's an object.

do you know how to fix it?


  • 0





Also tagged with one or more of these keywords: pong, game, java