Results 1 to 7 of 7
  1. #1
    DeagleFace is offline Member
    Join Date
    May 2012
    Posts
    6
    Rep Power
    0

    Default Writing a Pong game - enhancing my default code.

    Hi :)

    If you read my introduction post then hello again, if not then hello anyway :)

    Basically, I am struggling with Java out of the 6 languages I am learning the most and getting fairly stressed about a piece of work I need to complete.

    I have a framework code for a game of pong which you will see below, all it includes currently is a ball moving across the screen and the position of the ball being displayed above.

    I am not expecting someone to use their time to write me a bunch of code, but need a real pointer in the right direction or some kind of decent tutorials that relate to the framework code I am supplied with; so I can build upon it.

    The code compiles as it is currently

    Java Code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.image.*;
    import java.awt.Color;
    /*
     * Note If you change S (Speed) collision detection will be
     *      more complex as the ball edge may be within the bat
     *      Ignores concurrency issues (x, y, x_inc, y_inc access)
     */
    
    class Main
    {
      public static void main( String args[] ) // 
      {                                        // 
        System.out.println("Application");
        Application app = new Application();
        app.setVisible(true);
        app.run();
      }                                        // 
    }
    
    class Application extends JFrame            // So graphical 
    {
      private static final int H = 600;         // Height of window 
      private static final int W = 800;         // Width  of window 
    
      public Application()
      {
        setSize( W, H );                        // Size of application 
        addKeyListener( new Transaction() );    // Called when key press 
        setDefaultCloseOperation(EXIT_ON_CLOSE);
      }
    
    
      public void update( Graphics g )          // Called by repaint 
      {                                         // 
        drawPicture( (Graphics2D) g );          // Draw Picture 
      }
    
      public void paint( Graphics g )           // When 'Window' is first 
      {                                         //  shown or damaged 
        drawPicture( (Graphics2D) g );          // Draw Picture 
      }
    
      private Dimension     theAD;              // Alternate Dimension 
      private BufferedImage theAI;              // Alternate Image 
      private Graphics2D    theAG;              // Alternate Graphics 
    
      public void drawPicture( Graphics2D g )   // Double buffer 
      {                                         //  allow re-size 
        Dimension d    = getSize();             // Size of curr. image 
    
        if (  ( theAG == null )  ||
              ( d.width  != theAD.width ) ||
              ( d.height != theAD.height ) )
        {                                       // New size 
          theAD = d;
          theAI = (BufferedImage) createImage( d.width, d.height );
          theAG = theAI.createGraphics();
          AffineTransform at = new AffineTransform();
          at.setToIdentity();
          at.scale( ((double)d.width)/W, ((double)d.height)/H );
          theAG.transform(at);
        }
    
        drawActualPicture( theAG );             // Draw Actual Picture 
        g.drawImage( theAI, 0, 0, this );       //  Display on screen 
      }
    
      // The ball position and how to increment to next position 
    
      private int x = W/2, x_inc = 1;
      private int y = H/2, y_inc = 1;
    
      // Called on key press  
    
      class Transaction implements KeyListener  // When character typed 
      {
        public void keyPressed(KeyEvent e)      // Obey this method 
        {
         // Key typed includes specials 
         switch ( e.getKeyCode() )              // Character is 
         {
           case KeyEvent.VK_LEFT:               // Left Arrow 
             x_inc = -1;
             break;
           case KeyEvent.VK_RIGHT:              // Right arrow 
             x_inc = 1;
             break;
           case KeyEvent.VK_UP:                 // Up arrow 
             y_inc = -1;
             break;
           case KeyEvent.VK_DOWN:               // Down arrow 
             y_inc = 1;
             break;
          }
          // x,y could send to a server instead of calling  
          repaint();                            // Call update method 
        }
    
        public void keyReleased(KeyEvent e)
        {
          // Called on key release including specials 
        }
    
        public void keyTyped(KeyEvent e)
        {
          // Normal key typed 
          char c = e.getKeyChar();              // Typed 
          repaint();                            // Redraw screen 
        }
      }
    
      private static final int B = 6;           // Border offset 
      private static final int M = 26;          // Menu offset 
      private static final int BALL_SIZE = 10;  // Ball diameter 
      private static final int HALF_BALL_SIZE = BALL_SIZE/2;
    
      // Code called to draw the current state of the game 
    
      public void drawActualPicture( Graphics2D g )
      {
        // White background 
    
        g.setPaint( Color.white );
        g.fill( new Rectangle2D.Double( 0, 0, W, H ) );
    
        Font font = new Font("Calibri",Font.BOLD,24); 
        g.setFont( font ); 
    
        // Blue playing border 
    
        g.setPaint( Color.blue );              // Paint Colour 
        g.draw( new Rectangle2D.Double( B, M, W-B*2, H-M-B ) );
    
        // Display state of game 
    
        g.setPaint( Color.blue );
        FontMetrics fm = getFontMetrics( font );
        String fmt  = "Bouncing Ball x=%4d y = %4d";
        String text = String.format( fmt, x, y );
        g.drawString( text, W/2-fm.stringWidth(text)/2, M*2 );
    
        // The ball at the current x, y position (width, height) 
    
        g.setPaint( Color.red );
        g.fill( new Ellipse2D.Double( x-HALF_BALL_SIZE, y-HALF_BALL_SIZE, 
                                      BALL_SIZE,     BALL_SIZE ) );
      }
        
    
      // Main program loop 
    
      public void run()
      {
        final int S = 1;                    // Speed 1 - 5 
        try
        {
          while ( true )
          {
            if ( x >= W-B-HALF_BALL_SIZE ) x_inc = -1*S;
            if ( x <= 0+B+HALF_BALL_SIZE ) x_inc = 1*S;
            if ( y >= H-B-HALF_BALL_SIZE ) y_inc = -1*S;
            if ( y <= 0+M+HALF_BALL_SIZE ) y_inc = 1*S;
      
            x += x_inc;
            y += y_inc;
      
            repaint();                      // Now display 
    
            Thread.sleep( 10 );             // 100 Hz 
          }
        } catch ( Exception e ) {};
      }
    
    }
    The minimum objectives I would like to achieve are
    - Insert 2 paddles that can be moved using W/S and UP/DOWN which the ball collides with
    - Insert a score for both players at top of screen rather than current text
    - Change the background image to something over than a basic colour.

    Thankyou for any replies.


    In the meantime I will work on my C program in arduino to take random numbers and display them in binary :)

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: Writing a Pong game - enhancing my default code.

    You might get a decent answer here, but my experience here has been that we do much better answering specific questions regarding your attempts to implement something. So why not try to implement these objectives first and then ask any specific questions regarding your attempts if they don't work as you desire?

  3. #3
    DeagleFace is offline Member
    Join Date
    May 2012
    Posts
    6
    Rep Power
    0

    Default Re: Writing a Pong game - enhancing my default code.

    Quote Originally Posted by Fubarable View Post
    You might get a decent answer here, but my experience here has been that we do much better answering specific questions regarding your attempts to implement something. So why not try to implement these objectives first and then ask any specific questions regarding your attempts if they don't work as you desire?

    More because I don't really have any idea where to start. What I would like to do first and foremost is place 2 bats either side of the game window. Once I have achieved that, I will hopefully advance on it with collision and movement.

  4. #4
    DeagleFace is offline Member
    Join Date
    May 2012
    Posts
    6
    Rep Power
    0

    Default Re: Writing a Pong game - enhancing my default code.

    I will be trying to help myself while doing this of course.

    The first thing I notice when thinking about trying to implement this is

    Java Code:
    g.setPaint( Color.blue );
        FontMetrics fm = getFontMetrics( font );
        String fmt  = "Bouncing Ball x=%4d y = %4d";
        String text = String.format( fmt, x, y );
        g.drawString( text, W/2-fm.stringWidth(text)/2, M*2 );
    
        // The ball at the current x, y position (width, height) 
    
        g.setPaint( Color.red );
        g.fill( new Ellipse2D.Double( x-HALF_BALL_SIZE, y-HALF_BALL_SIZE, 
                                      BALL_SIZE,     BALL_SIZE ) );
    So could I use this

    g.setPaint( Color. );
    g.fill( new Rectangle2D.Double());

    to create further shapes and position them on the page? I had a fiddle, but could not figure out how to set the positioning properties, and somehow turned my whole window green.
    Last edited by DeagleFace; 05-11-2012 at 06:14 AM.

  5. #5
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default Re: Writing a Pong game - enhancing my default code.

    Here is some code I used to make Pong a while ago. I'd recommend you read it and see if it can help you out.
    https://github.com/hegek87/Pong/tree/master/src/src

  6. #6
    DeagleFace is offline Member
    Join Date
    May 2012
    Posts
    6
    Rep Power
    0

    Default Re: Writing a Pong game - enhancing my default code.

    Quote Originally Posted by sunde887 View Post
    Here is some code I used to make Pong a while ago. I'd recommend you read it and see if it can help you out.
    https://github.com/hegek87/Pong/tree/master/src/src
    Cheers Ill take a look through, if I find any problems with specific parts ill throw a PM your way.

  7. #7
    DeagleFace is offline Member
    Join Date
    May 2012
    Posts
    6
    Rep Power
    0

    Default Re: Writing a Pong game - enhancing my default code.

    Hi guys, I have now got 2 rectangular shapes which I am calling my paddles on the screen with the following code.

    Java Code:
        //paddle1
        g.setPaint( Color.blue );
        g.fill( new Rectangle2D.Double(50, 250, 10, 100));
        
        //paddle2
        g.setPaint ( Color.blue );
        g.fill( new Rectangle2D.Double(750, 250, 10, 100));
    Is there someone that can show me how to add collision detection to the bats so that the ball will bounce off of them?

Similar Threads

  1. Pong game
    By hannes in forum Threads and Synchronization
    Replies: 4
    Last Post: 02-03-2011, 11:52 AM
  2. pong game with reinforcement learner
    By jackdalton in forum New To Java
    Replies: 7
    Last Post: 11-12-2010, 07:10 PM
  3. Ping pong game
    By adam405 in forum New To Java
    Replies: 8
    Last Post: 10-20-2010, 04:52 PM
  4. The bug in the Pong game
    By Phoeenix in forum New To Java
    Replies: 4
    Last Post: 07-21-2009, 08:13 PM
  5. Help with pong game
    By Eric in forum New To Java
    Replies: 2
    Last Post: 07-03-2007, 08:02 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •