Results 1 to 4 of 4
  1. #1
    itweaq is offline Member
    Join Date
    Apr 2014
    Posts
    2
    Rep Power
    0

    Default Add color to ball in Pong, Add speed

    Hello, new to the thread. I wrote a code from our text book for Pong. Im trying to figure out how to fill the ball with color. Im also wondering how to speed the ball up once there is contact with the paddle. The initial speed is ok but once contact is made with the paddle, it slows down. Makes it too easy to play. Thanks

    Here is my code so far. As far as the game goes, it works and is good. Just wanted to add a couple customizations. Thanks for all your help

    Java Code:
    package pong;
    
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.FontMetrics;
    import java.awt.Graphics;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionAdapter;
    import java.util.Random;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.Timer;
    
    /*
     * Program plays a variation of the game Pong.
     * The paddle is at the bottom of the screen,
     * controlled  by the mouse.
     * A ball  drops from the top and the goal
     * is to hit the ball with the paddle.
     */
    public class Pong extends JFrame {
            public static int W = 400;
            public static int H = 400;
            
        public Pong() {
            JPanel canvas = new PongCanvas();
            add(canvas);
        }
    
        class PongCanvas extends JPanel {
        
            double radius = 10; //  ball radius
            double ballX = W / 2; // initial ball position (top middle)
            double ballY = radius;
            //Initial ball speed:
            double dx = 3 * Math.random() - 1;
            double dy = 4 * Math.random() + 4;
            //Size of the paddle:
            double padH = 10;
            double padW = 35;
            //Initial paddle position:
            double padX = getWidth() / 2;
            double padY = getHeight() - padH / 2;
            //Timer to keep redrawing the screen:
            private Timer timer = new Timer(10, new TimerListener());
          
            int groundCount = 0;//number of balls that hit the ground (misses)
            int paddleCount = 0;//number of ball-paddle hits
    
            public PongCanvas() {
                double ballX = getWidth() / 2;
                timer.start();
                //Mouse Motion Listener
                //Sets the x-ccord of the paddle to the mouse x-coord:
                this.addMouseMotionListener(new MouseMotionAdapter() {
                    public void mouseMoved(MouseEvent e) {
                        padX = e.getX();
                    }
                });
            }
    
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                groundHit(); //see if ball hit the ground (bottom of the screen)
                wallHit(); //check for ball hitting wall (L or R of screen)
                topHit(); //check for ball hitting top of screen
                paddleHit(); //check for ball hitting paddle
                updateBall(); // give the ball its next position
                drawBall(g); // draw the ball
                drawPaddle(g); // draw the paddle
                //Long attempt to print numbers to the screen:
                Font font = new Font("Quartz MS", Font.BOLD, 18);
                g.setFont(font);
    
                // get metrics from the graphics
                FontMetrics metrics = g.getFontMetrics(font);
                // get the height of a line of text in this
             
                int hgt = metrics.getHeight();
                // get the advance of my text in this font
                       
                String text;
                int adv;
                
                text = "Contact = " + paddleCount;           
                adv = metrics.stringWidth(text);
                // calculate the size of a box to hold the
                // text with some padding (2).
                Dimension size = new Dimension(adv + 2, hgt + 2);          
                g.drawString(text, 
                        getWidth()/2 - size.width/2 , 
                        getHeight()/2 + size.height/2 
                        ); 
                
                text = "Miss = " + groundCount;
                adv = metrics.stringWidth(text);
                size = new Dimension(adv + 2, hgt + 2);
                       
                g.drawString(text, 
                        getWidth()/2 - size.width/2,
                        getHeight()/2 + size.height/2 + size.height
                        );
                           
            }
    
            //If the ball hits the ground, start a new ball (resetBall()).
            private void groundHit() {
                if (ballY >= getHeight() - radius) {
                    groundCount++;
                    resetBall();
                }
            }
    
            //Some randomness added to reseting the ball:
            private void resetBall() {
                ballX = getWidth() / 2;
                ballY = radius;
                dx = getRandomInt(-2, 3);
                dy = getRandomInt(4, 8);
            }
    
            private void wallHit() {
                if (ballX - radius <= 0 || ballX + radius >= getWidth()) {
                    dx = -dx;
                }
            }
    
            private int getRandomInt(int a, int b) {
                //returns a random integer between a and b.
                //including a but not b.
                Random rand = new Random();
                return a + rand.nextInt(b - a);
            }
    
            //Not an exact calculation, but good enough:
            //(calculating the intersection of a rectangle
            //and a circle is a little more involved than
            //what I have here.
            //And, I added some randomness to the "bounce".
            private void paddleHit() {
    
                if ((ballX > padX - padW / 2 - radius)
                        && (ballX < padX + padW / 2 + radius)
                        && (ballY > getHeight() - (padH + radius))) {
                    paddleCount++;
                    dx = getRandomInt(-2, 3);
                    dy = -getRandomInt(4, 8);
                }
            }
    
            private void drawBall(Graphics g) {
                g.drawOval((int)(ballX - radius), 
                        (int)(ballY - radius), 
                        (int)(2*radius), 
                        (int)(2*radius)
                        );
            }
    
            private void drawPaddle(Graphics g) {
                g.fillRect((int)(padX - padW/2), 
                        (int)(getHeight() - padH), 
                        (int)padW, 
                        (int)padH
                        );
            }
    
            private void updateBall() {
                ballX += dx;
                ballY += dy;
            }
    
            private void topHit() {
                if (ballY < radius) {
                    dy = -dy;
                }
            }
    
            class TimerListener implements ActionListener {
    
                public void actionPerformed(ActionEvent e) {
                    repaint();
                }
            }
        }
    
        public static void main(String[] args) {
            JFrame frame = new Pong();
            frame.setTitle("Pong");
            frame.setSize(W, H);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    }

  2. #2
    itweaq is offline Member
    Join Date
    Apr 2014
    Posts
    2
    Rep Power
    0

    Default Re: Add color to ball in Pong, Add speed

    Im using NetBeans IDE 7.2 if that makes a difference.

  3. #3
    SurfMan's Avatar
    SurfMan is online now Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    1,095
    Rep Power
    4

    Default Re: Add color to ball in Pong, Add speed

    On line 157, use fillOval() instead of drawOval().
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  4. #4
    Nozz is offline Member
    Join Date
    Apr 2014
    Posts
    49
    Rep Power
    0

    Default Re: Add color to ball in Pong, Add speed

    dx = getRandomInt(-2, 3);
    dy = -getRandomInt(4, 8);
    You get some random values in "speed" while ball restars and bounce. So change these random values to static ones and it will go with same speed everytime. Or if you want to speed it up but keep randomness, just incrase numbers and it should work.
    You just should adjust values to make it works as you want.

    You can also remove few imports and one double variable, because these aren't used anywhere. Ofc if you won't use these in future.
    Last edited by Nozz; 04-23-2014 at 08:01 PM.

Similar Threads

  1. Help with pong
    By aortell24 in forum New To Java
    Replies: 4
    Last Post: 07-07-2012, 10:15 AM
  2. Pong help
    By jsobel in forum New To Java
    Replies: 3
    Last Post: 04-03-2012, 04:33 PM
  3. Pong! But missing ball...
    By ResidentBiscuit in forum New To Java
    Replies: 2
    Last Post: 11-15-2011, 10:00 AM
  4. Pong Paddle Not Stopping Ball At Certain Speed
    By JDCAce in forum Java Applets
    Replies: 2
    Last Post: 10-12-2008, 06:15 AM
  5. Problem deleting ball from bouncing ball app
    By adlb1300 in forum New To Java
    Replies: 2
    Last Post: 12-03-2007, 10:08 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
  •