473,757 Members | 10,007 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Help With Project Please. If statements

2 New Member
Ok I was doing this project but now Im halfway stuck. This project contains 3 class at the moment. Im mainly trying to make this applet like the game pong. I have the paddle and a ball and background and stuff.

Now my main problem is that I need to make the ball bounce back after it touches the paddle...Right now the ball goes through the paddle.

And the paddle is moved using arrow keys. So now I need like a code for me to make the ball bounce back when it touches the paddle. And I think this can be done using if statement..not sure. But any help will be greatly appreciated...b ut here are my classes and codes for them.

ImagePong

Expand|Select|Wrap|Line Numbers
  1. /**
  2.  * Balloon.java uses a PNG file that is displayed by the applet
  3.  * 
  4.  * @author Sulav
  5.  * @version 11/29/07
  6.  */
  7. //_________________import statements______________________________________
  8. import java.awt.*;
  9. import javax.swing.ImageIcon;  // needed to use image files from disk
  10.  
  11. public class ImagePong
  12. {
  13.  
  14.    //________________instance variables/properties_________________________
  15.    Image frame2;  //object holds the actual graphic
  16.    Image frame1;  //object holds the actual graphic
  17.  
  18.    int x=0, y=0, xSpeed=15, ySpeed=15, maxX=500,  maxY=500;
  19.     Color c;
  20.  
  21.    int x2=0, y2=0, x2Speed=15, y2Speed=15, max2X=500,  max2Y=500;
  22.  
  23.  
  24.  
  25.    //__________constructors_______________________________________________
  26.  
  27.    public ImagePong()
  28.    {   //pong.png must be in your project directory
  29.        frame1 = new ImageIcon("./paddle2.jpg").getImage();  //load the graphic
  30.        x = 190; y = 450;
  31.  
  32.        frame2 = new ImageIcon("./back.jpg").getImage();  //load the graphic
  33.        x2 = 1; y2 = 1;
  34.  
  35.  
  36.  
  37.     }  //end of Balloon() constructor
  38.  
  39.     //____________________methods___________________________________
  40.     // getImage() sends back the current image
  41.     public Image getImage()
  42.     {
  43.         return frame1;
  44.     } // end of getImage()
  45.  
  46.     public Image getImage2()
  47.     {
  48.         return frame2;
  49.     } // end of getImage()
  50.  
  51.  
  52.     // getX() sends back the x position
  53.     public int getX()
  54.     {
  55.         return x;
  56.     } // end of getX
  57.  
  58.     //get Y () sends back the y position )
  59.  
  60.     public int getY()
  61.     {
  62.         return y;
  63.     } // end of getY
  64.  
  65.  
  66.  
  67.  
  68.  
  69.     // getX() sends back the x position
  70.     public int getX2()
  71.     {
  72.         return x2;
  73.     } // end of getX
  74.  
  75.  
  76.    //get Y () sends back the y position )
  77.  
  78.     public int getY2()
  79.     {
  80.         return y2;
  81.     } // end of getY
  82.  
  83.  
  84.  
  85.     public void setXSpeed (int newXSpeed)
  86.     {
  87.         xSpeed=newXSpeed;
  88.         xSpeed=newXSpeed;
  89.     }
  90.     public void setYSpeed (int newYSpeed)
  91.     {
  92.         ySpeed=newYSpeed;
  93.         ySpeed=newYSpeed;
  94.     }
  95.     public void moveRight()
  96.     {
  97.         if(x<maxX + 12)
  98.         {
  99.             x+=xSpeed;
  100.         }
  101.     }
  102.  
  103.      public void moveLeft()
  104.     {
  105.         if(x<maxX + 12)
  106.         {
  107.             x-=xSpeed;
  108.         }
  109.     }
  110.  
  111. } // end of Balloon class


ImageMover(Appl et)

Expand|Select|Wrap|Line Numbers
  1. /**
  2.  * ImageMover.java animates an image in the applet window.
  3.  * It uses double buffering to provide nice smooth animation
  4.  * 
  5.  * @author Sulav
  6.  * @version 11/29/07
  7.  */
  8.  
  9. import java.applet.*;
  10. import java.awt.*;
  11. import java.awt.event.*;
  12.  
  13. public class ImageMover extends Applet implements Runnable, KeyListener
  14. {
  15.  
  16.    private Image buffer;  //holds  a copy of the applet window
  17.    private Graphics gBuffer;  // the copy's graphics page
  18.    private ImagePong back; //create a paddle object to be animated
  19.    private ImagePong paddle; //create a background object to be animated
  20.    private Thread t;  //create the thread to do it
  21.    private Ball pingpong; //thing being bounced
  22.  
  23.    public void init()
  24.    {
  25.        // create graphics buffer, the size of the applet
  26.        buffer=createImage(this.getWidth(),this.getHeight());
  27.        gBuffer=buffer.getGraphics();
  28.  
  29.  
  30.          // Initialize drawing colors
  31.         setBackground(Color.black);
  32.         setForeground(Color.white);
  33.  
  34.         pingpong = new Ball(this.getWidth(), this.getHeight(), Color.red);
  35.         addKeyListener(this);  // register the KeyListener with the applet
  36.        // create the Balloon object and thread to control animation
  37.  
  38.        paddle = new ImagePong();
  39.        back = new ImagePong();
  40.  
  41.        t = new Thread(this);
  42.        t.start();
  43.     } // end of init()
  44.  
  45.    // run() is used by the Thread T to keep the balloon moving
  46.    public void run()
  47.    {
  48.        // run this loop forever
  49.        while(true)
  50.        {
  51.            pingpong.move(); 
  52.            // move the balloon given the size of the applet window
  53.            //pong.move(this.getWidth(), this.getHeight());
  54.            repaint();
  55.            try {t.sleep(20);}  //pause a little to slow things down
  56.            catch (Exception e) {}
  57.  
  58.  
  59.  
  60.     }
  61.  
  62.     }   //end of run
  63.  
  64.       // method to stop the thread from going. will cause a warning when compiled
  65.     public void stop()
  66.     {
  67.         t.stop();
  68.     } // end of stop() method
  69.  
  70.     // update() needs to run paint() so Java doesnt erase the window
  71.     public void update(Graphics g)
  72.     {
  73.         paint(g);
  74.     } // end of update()
  75.  
  76.     // paint() paints the applet window
  77.     public void paint(Graphics g)
  78.     {
  79.         pingpong.draw(g);
  80.         // set the drawing color and cover the buffer witha  gilled rectangle
  81.         gBuffer.setColor(Color.black);
  82.         gBuffer.fillRect(0, 0, this.getWidth(), this.getHeight());
  83.  
  84.         //draw the balloon image in the BUFFER at its own coordinates
  85.         //gBuffer.drawImage(paddle.getImage(), paddle.getX(),
  86.                        //  paddle.getY(), this);
  87.  
  88.  
  89.  
  90.         // draw the balloon image in the BUFFER at its own coordinates
  91.         gBuffer.drawImage(back.getImage2(), back.getX2(),
  92.                           back.getY2(), this);
  93.  
  94.          // draw the balloon image in the BUFFER at its own coordinates
  95.  
  96.          gBuffer.drawImage(paddle.getImage(), paddle.getX(),
  97.                           paddle.getY(), this);                  
  98.         // now draw the iamge to the applet window
  99.         g.drawImage (buffer, 0, 0, this);
  100.  
  101.      } // end of paint()
  102.  
  103.  
  104.      public void keyPressed(KeyEvent event) {
  105.         int keyCode = event.getKeyCode();  //get the key hit
  106.  
  107.         if (keyCode == KeyEvent.VK_D)
  108.         {
  109.            paddle.moveRight();
  110.         }
  111.  
  112.  
  113.         if (keyCode == KeyEvent.VK_A)
  114.         {
  115.            paddle.moveLeft();
  116.         }
  117.  
  118.         event.consume();  //keep anything else from using the key
  119.         repaint();  // signal Java to redraw the window
  120.     }
  121.     public void keyReleased(KeyEvent event) {
  122.         event.consume();  // ignore keyReleased
  123.     }
  124.     public void keyTyped(KeyEvent event) {
  125.         event.consume();  // ignore keyTyped
  126.     }
  127.   } // end of ImageViewer class   

Ball

Expand|Select|Wrap|Line Numbers
  1. /**
  2.  * Ball.java is the object that will get bounced around
  3.  * 
  4.  * @author Sulav
  5.  * @version 11/16/07
  6.  */
  7. import java.awt.*;
  8. import java.awt.geom.*;
  9.  
  10. public class Ball
  11. {
  12.      // set constants for colors
  13.      final Color blue = Color.black, green = Color.white;
  14.  
  15.      // variables for location, speed, and direction of ball size of window
  16.      int x, y, horVel = 13, vertVel = 16, maxX, maxY;
  17.      Color c;
  18.  
  19.      public Ball(int mx, int my, Color c)
  20.      {
  21.          maxX = mx; // set the max variables
  22.          maxY = my;
  23.          this.c = c;
  24.  
  25.          //frame2 = new ImageIcon("./pong.jpg").getImage();
  26.  
  27.          // give the ball a random starting position
  28.          x = (int) (Math.random() * maxX) + 1;
  29.          y = (int) (Math.random() * maxY) + 1;
  30.  
  31.         }
  32.  
  33.         public void draw(Graphics g)
  34.         {
  35.             Graphics2D g2 = (Graphics2D) g;  //supersize the drawing page
  36.  
  37.             GradientPaint grad = new GradientPaint(x+20, y-20, green, x+20, y+60, blue);
  38.             //g2.setPaint(grad);
  39.             g2.setPaint(c);
  40.             g2.fill (new Ellipse2D.Double(x, y, 40, 40));
  41.         } // end of draw()
  42.  
  43.         public void move()
  44.         {
  45.             y+=vertVel;  // add the horizontal velocity to x
  46.             x+=horVel;
  47.  
  48.             if ((y > maxY) || (y < 1)) //checking left, right boundaries
  49.             {
  50.                 vertVel = -vertVel;  //reverse direction if at left/right edge
  51.             }
  52.  
  53.              if ((x > maxY) || (x < 1)) //checking left, right boundaries
  54.             {
  55.                 horVel = -horVel;  //reverse direction if at left/right edge
  56.             }
  57.  
  58.         } // end of move() method
  59.     } //end of Ball class
Dec 13 '07 #1
1 1960
BigDaddyLH
1,216 Recognized Expert Top Contributor
So now I need like a code for me to make the ball bounce back when it touches the paddle.
You know how to make the ball bounce, because it is bouncing off the edges, right? Do you know how to detect if the ball is touching the paddle?
Dec 13 '07 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

5
3494
by: duikboot | last post by:
Hi all, I'm trying to export a view tables from a Oracle database to a Mysql database. I create insert statements (they look alright), but it all goes wrong when I try to execute them in Mysql, because the dates must have quotes on each side. I just don't know how make the dates right. Well I'll just show you the code and some insert statements it generates. Could anyone please help me?
4
1522
by: dwight0 | last post by:
I am having a problem with a query, I am not sure if i would use a join or a subquery to complete this problem. I have two queries, and i need to divide one by the other, but i cant seem to get any type of join to work with them. Here is the situation. I have a projectDB table that has a list of different projects for each employee to work on. Each project has an employee assigned to it.
2
1930
by: m3ckon | last post by:
Hi there, had to rush some sql and am now going back to it due to a slow db performance. I have a db for sales leads and have created 3 views based on the data I need to produce. However one o the views, which has subqueries to the other views is VERY slow and it needs to be speeded up, but am unsure how, can anyone help... below is the sql?
4
2670
by: Colin McGuire | last post by:
Hi, this is a really simple question I have been banging my head on a brick wall over. The program below changes the background colour of a form depending on whether the cursor is inside a rectangle drawn on the form or not. It works perfectly as shown below. But it won't work if I change the values of scaleFactor, rotateFactor, translateFactorX, translateFactorY in the program. I would like to 'correct' the values of e.X and e.Y in...
4
4619
by: jon f kaminsky | last post by:
Hi- I've seen this problem discussed a jillion times but I cannot seem to implement any advice that makes it work. I am porting a large project from VB6 to .NET. The issue is using the combo box bound to a table as a lookup, drawing values from another table to populate the available selections. This all worked fine in VB6. I have distilled the problem down to a simple form drawing data from the Northwind database for a representative...
7
1481
by: phillip.s.powell | last post by:
Now I have another SQL query for MySQL I can't figure out!! This is overwhelming me completely and I also must have this figured out today and I can't figure it out!! UPDATE student_db.student SET has_letter1 = ( SELECT i.letter1 FROM olddb.student i, student_db student s WHERE s.unique_key = i.unique_key )
17
2537
by: Student | last post by:
Hi All, I have an assignment for my Programming language project to create a compiler that takes a C++ file as input and translate it into the C file. Here I have to take care of inheritance and operator overloading and virtual functions. I mean it should not hamper the C++ meaning. In frank and simple terms i need to implement a small C++ compiler in C++, and i want the intermediate representation to be C. Please help me in this....
13
2872
by: Ilias Lazaridis | last post by:
I have implemented a simple schema evolution support for django, due to a need for a personal project. Additionally, I've provided an Audit: http://case.lazaridis.com/wiki/DjangoAudit As a result, I was censored ('banned' from the development list) My initial non-public complain about censorship on django devel, sent to six relevant project recipients remained unanswered.
1
1810
by: atombee | last post by:
Hi- this is the project that will not end! (sure you've all been there). I had originally purchased a php/css nav bar for the client, but it was buggy as hell, so I decided to do in css, in which I am still a novice, I am afraid. You can see the sample nav bar at www.tangerine-sky.com/horizontal_nav.html (I am pasting source code below) It's very simple, has the css included in the page ... works fine on a mac, okay on firefox on a PC but...
0
9489
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9298
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9737
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8737
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7286
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6562
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5329
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3399
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2698
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.