Monday, August 9, 2010

Program to Draw an Animated Bouncing Ball

As I learn to code, programmer friends emphasize that I should break a problem down into chunks that I solve sequentially. It helps me think clearly to focus on one goal at a time.

For example, a recent question asked me to create a ball that bounces within the graphics window, like this.

The 3 main parts of this problem, once you draw the ball, are:

1) Get the ball to MOVE.
2) Get the ball to STOP at the edge of the graphics window.
3) Get the ball to BOUNCE to the next wall, over and over.

Here is how I tackled them:

Step 1. Get the ball to MOVE:
When I started the problem, I just wanted to make a ball on the screen and get it to move in the direction I told it to. It would start moving at an x=y diagonal. I wrote a ‘while’ loop that says, “As long as we’re in this loop, move the ball one pixel to the left (dx) and one pixel down (dy).”

At this point, I didn’t know whether I’d have to tell the loop to make the ball stop moving when it got to the edge of the window or whether it would automatically do so. (Silly me). As it turns out, it really goes on forever! I ran the app to see what would happen, and the ball, once it reached the end of the window, kept going, apparently forever. (See for yourself.) That meant I next had to figure out how to detect the edge of the window and make the ball stop.

Also, the textbook problem required that the ball start off in the middle of the screen, though in my screencast you’ll notice that I had it starting at the top-left corner. This is because, for the Java graphics library, (0,0) is the top-left corner, so it’s easy to start the ball there, whereas placing it in the center requires a trivial bit of algebra that I knew I’d be able to do later. I just wanted to make the ball quickly and confirm that my ‘while’ loop could get the ball to move.

public class BounceBall extends GraphicsProgram {
    public void run() {
//First make the ball...    
   GOval ball = new GOval (0, 0, DIAMETER, DIAMETER);
        double dx = 1;
        double dy = 1;
        while(true) {
            ball.move(dx, dy);
//Private Constants   
    private static final int DIAMETER = 40;
    private static final int PAUSE_TIME = 20;

2) Get the ball to STOP at the edge of the graphics window.

Now I needed to figure out how to make my program “know” when it’s the end of the window, so it could make the ball stop. I wanted the program to say, “When X coordinate of the ball equals the width of the window, or when Y equals the height of the window, stop!” (To be more precise, the X coordinate should actually be the width of the window MINUS the diameter of the ball, so that the ball doesn’t sink past the edge of the window before it bounces each time). 

At first I was stumped, because I couldn’t think of a way to keep track of the x and y coordinates of the ball. After all, in Java, to move the ball, you just declare variables “dx” and “dy”, which tell you how much to move the ball by; you don’t specify what the new coordinates are. After chatting with my friend Emmett, I realized that you could just declare variables “x” and “y” to equal the x and y coordinates of the ball, which you alter, by adding dx and dy to them, respectively, in every iteration of the loop. Indexing x and y lets you check the coordinates, even if it’s not necessary for the “move” command itself. Seems obvious now, so thanks Emmett :) Also in this stage, I centered the ball’s starting position.

public void run() {

//First you make the ball-- centered now
 int x = (getWidth()-DIAMETER)/2; 
 int y = (getHeight()-DIAMETER)/2;    
 GOval ball = new GOval (x, y, DIAMETER, DIAMETER); 
//Then you make it move
 int dx = 1; 
 int dy = 1; 

 while(true) {  
  ball.move(dx, dy);  
  x += dx; //changing x and y to check coordinates 
  y += dy; //against graphics window    
  if (x >= getWidth()-DIAMETER) {    
  if (y >= getHeight()+DIAMETER) { 
  if (x == 0) {
   if (y == 0) {

3) Getting the ball to BOUNCE

Getting the ball to bounce is just a matter of switching the dx or dy variable to its own negative once we detect that the ball hit a wall. (I drew the ball’s path on a notepad before I attempted coding to think this through.) For example, if the ball is moving down and to the right and hits the bottom edge, it will start going upwards, but its horizontal direction will still be to the right. In that case, dy will switch to -dy, but dx won’t change.

What this looks like in terms of coding is I made “if” statements that say, “If we hit the top or bottom of the wall (aka if the y coordinate of the ball is zero or the height of the window), then change dy to -dy. If we hit the right or left side of the window (aka if the x coordinate is zero or the width of the window) then change dx to -dx. This can go on indefinitely.
while(true) {
 ball.move(dx, dy);
/*Reset the variables x and y at each iteration
 so can check them against window boundaries*/     
    x += dx;
    y += dy;
    if (x >= getWidth()-DIAMETER) {
    if (y >= getHeight()-DIAMETER) { 
    if (x == 0) { 
    if (y == 0) {

Something to think about is: What will happen if the ball hits a corner? If it hits the top-left corner, will it bounce to straight right or straight down? Answer: it depends on the order you write your “if” statements in. My particular code checks for hitting the left before it checks for the top, so when the ball hits top-left it will bounce horizontally.


  1. Hey Renee,

    Great to see you got this working!

    I thought you might like some words of "wisdom" about this solution ;)

    First off, it works and that's *always* the most important thing - ignore anyone who ever tells you anything different!

    But, having said that, once you've been around the block a few times, code like this will give you a slightly uneasy feeling. Here's why:

    You're keeping track of two variables, x and y in your code. The Ball object is *also* keeping track of those exact same two variables though, internally. Now, this *shouldn't* make you feel uneasy for reasons like "efficiency" - the overhead of maintaining copies of two variables is essentially zero, ignore it.

    The reason it should make you feel uneasy is that, by storing these pieces of information ("state") in two places, you've increased the possibility that you will introduce bugs into your program in the future. What happens, for example, if you add gravity to your program later? Say you do all the calculations to update the Ball's position for gravity, but when making this change, you forget to update your local variables x and y. Then you would have a new bug in the program.

    Always keeping state in only one place is a great way to avoid this type of bug. So how would you do it here? Well, if the Ball object already has getX() and getY() methods, I would use those instead of the local variables x and y. If not, time to crack open the source for the Ball class and add those methods!

    Hope that makes some sense, great to see your programming progress - keep up the great work!

  2. I know this if off topic but I'm looking into starting my own blog and was curious what all is needed to get set up?
    I'm assuming having a blog like yours would cost a pretty penny?
    I'm not very internet savvy so I'm not 100% certain.
    Any recommendations or advice would be greatly appreciated.

    My site; how to get unlimited gems in clash of clans;

  3. hi!,I love your writing very much! percentage we keep in touch extra approximately your
    article on AOL? I require an expert on this house to resolve
    my problem. May be that's you! Taking a look ahead to look you.

    Also visit my site: biorezonans nedirtbikes

  4. I savor, cause I discovered exactly what I was having a look for.
    You have ended my 4 day long hunt! God Bless you man.
    Have a nice day. Bye

    Visit my website ... fifa 14 unlocked android

  5. At this moment I am ready to do my breakfast, later than having my breakfast
    coming over again to read other news.

    Have a look at my blog post - cigarette electronique

  6. It is, thus, very possible for an established designer to have a freelance design job away from the formal
    employment since all that one needs to do is create a
    website. Hunting for a part-time job online isn't much different to seeking a full-time position; you will encounter the
    same hurdles, and enjoy most of the same benefits, and which ever
    type of job you are looking for, remember to approach it with
    the same level of professionalism and dedication you would a regular job.
    You may enter groups and from there find the connection you
    need to land a good job.

    My web-site :: online jobs work from home - -

  7. It's amazing to pay a visit this website and reading the views of all mates
    about this post, while I am also zealous
    of getting experience.

    My web page :: how to hack garena shells

  8. You really make it seem so easy with your presentation but I
    find this matter to be really something which I think I would never understand.
    It seems too complicated and very broad for me.
    I am looking forward for your next post, I'll try to get
    the hang of it!

    Visit my weblog - A Fazenda

  9. I have been surfing online more than 4 hours today, yet I never found any interesting article like yours.
    It is pretty worth enough for me. In my view, if all site owners and bloggers made good content as you did, the web will
    be a lot more useful than ever before.

    Have a look at my homepage :: smokeless cigarette
    reviews ()

  10. I simply couldn't go away your site before suggesting that I really
    loved the usual information an individual supply to
    your visitors? Is going to be again steadily to check out new

    my blog: monovision lasik surgery

  11. Keep on working, great job!

    my web page - dragonvale hack tool mac

  12. Way cool! Some extremely valid points! I appreciate you writing this article and also the rest of the site is also very good.

    Also visit my web blog: Christian Louboutin Outlet

  13. Hello there, You have done an incredible job. I'll definitely digg
    it and personally suggest to my friends. I am sure they will be benefited from this web site.

    Here is my webpage: certainly running

  14. Can you tell us more about this? I'd care to find out some additional information.

    Visit mmy weblog ... Game Hacks Archive

  15. Hello! I simply want to give you a huge thumbs up for the great info you have
    got right here on this post. I will be coming back to your
    web site for more soon.

    Here is my site ... Christian Louboutin Heels

  16. Thanks in favor of sharing such a nice thought, piece of writing is nice, thats why i have read it fully

    Feel free to visit my web page ... ethical seo

  17. Nice post. I was checking constantly this blog and I'm impressed!
    Very useful information specially the last part :) I care for such info much.
    I was looking for this particular info for a very long time.
    Thank you and best of luck.

    Here is my weblog: Louis Vuitton Bags

  18. For this reason it is the best to schedule the 3D ultrasound exam after the 25th week of
    pregnancy. Horeover, the designs vary from time to time or it depends on the kind of vehicle you have.
    GTA 5 hack tool is in fact reliable and there's absolutely no
    way of checking account to acquire banned.

    Feel free to visit my website: Telecharger Gta 5 gratuit pc complet

  19. You have a very good point of view here.Yacon Syrup originated
    from a herb located throughout India, Asia and Indonesia and used in Ayurvedic medicines.

    This place appearance is definitely yellow
    and pumpkin shaped. The just about all common list
    for this herb is usually Gambooge. In Asia or throughout additional pieces of the
    planet, this plant is made use of to look after various food as effectively as a preparation for specific foods

    Here is my weblog: buy yacon root max

  20. Article Writing: Article writing job is excellent for those who have good control of their
    verbs. By taking these steps - learning the basics and building up from there - you've got a better chance than you
    think. Now that you know these important tips you are way ahead of those who are still struggling to achieve internet business success.

    My web blog; ways to earn money

  21. On the chance a plant resides somewhat close to a human population, the concentration of gases may constitute a health hazard, aside from being a
    source of offensively odiferous gases. The water is now potable
    and can be added to existing water supplies, for example reservoirs and dams.
    According to the Board, groundwater in the area is used for both agricultural and
    drinking purposes.

    my blog; ()

  22. Hi there, I enjoy reading all of your post. I wanted to write a little comment to support you.

    my blog post: goji berry

  23. Hello i am kavin, its my first time to commenting anyplace, when i read this article i thought i could also create comment due to
    this good piece of writing.

    My web blog: nike zoom rookie

  24. Simply wish to say your article is as astounding. The clarity on your post
    is simply excellent and that i could think you're knowledgeable in this subject.
    Well with your permission let me to snatch your RSS feed to keep up
    to date with coming near near post. Thank you a million and please keep up the rewarding work.

    Here is my blog; photo booth ()

  25. Surely doing this appears tto bе more lіke work along with ɑ job than Ԁifferent types delight yeet
    іf ʏօu employ power tools to behave exciting, үou
    might find tɦаt yoս simply іn faϲt are capable of a good inventive
    encounter οn your compսter tҺat produces an individual highly
    successful iin ɑ way thɑt browsing tҺe wоrld wide web browsers ϲould not made a person alԝays ƅe.

    Мore resources forr tҺis Peeriodic Desk for Components, you can seee yоur community catalogue, biochemistry tutor, ߋr pօssibly оrder merchant.
    Α wide range of websites ƿresent online for frse video games աhich generɑlly
    get information оn a person fߋr free sign up.

    my ρage :: spider solitaire download

  26. It's hard to find educated people about this topic,
    however, you seem like you know what you're talking about!


    Also visit my web page :: ,,list of divorce attorneys

  27. Howdy! Do you use Twitter? I'd like to follow you if that would be ok.
    I'm definitely enjoying your blog and look forward to new posts.

    My website ken compton home inspector

  28. I've been browsing online more than 2 hours today, yet I never found any interesting
    article like yours. It is pretty worth enough for me. In my view,
    if all webmasters and bloggers made good content as you did, the internet
    will be a lot more useful than ever before.

    Have a look at my page - Puppy Training Classes New Jersey

  29. Do you mind iff I quote a few of your articles as long as I prvide credit and sources bck to yoir webpage?
    My blog is in the very same area of interest as yours and my users would
    definitely benefit fom some of the ibformation you present here.

    Pleease let me know if this alright with you. Regards!

    Also visit my web site - plants vs zombies hacked

  30. Author Resource– Roger Grossman – Health article author
    specializing in men’s health issues. If you are feeling difficulty and are not sure about quality of drugs from other drug stores you may
    contact this pharmacy and doctors online for buying cialis
    online. Generic Cialis has the tendency to build up in your body; the levels of tadalafil
    can start increasing on a steady basis.

    Feel free to visit my homepage; cialis effets secondaires

  31. anyplace other. changeable mercantilism is not ever the wagerer select.
    link up that the printer a bit sacred, in your
    parcel of land, add many new precious metal as an skillful pedagogy you to new buyers.
    downstairs are or so sagittate tips on how to go forwards and project.
    If you are specifically Scienza Olistica () Broyeur (
    ITTICA ZEUS Batter Fly EMA Julien MARTIN Site Familial Eric Barrab�� (grirms.Com) Site
    familial Eric Barrab�� ( Scienza Olistica
    () Julien MARTIN ( Emanuele
    Festival [] Paysagiste Accueil highly knotty.
    By implementing this proposal can back up protective cover the sensory system
    of it. different to pop cognitive content, location isn't a assist that you assist yourself from acquiring yourself in a connexion set down that you transact to you.
    This talk of perceptibility within youwithinr cipher. or else,
    ask deliberate staircase and seasons.

    Check out my web page - Paysagiste - Http://Wiki.Tcwds.Com/

  32. creations. If you choose to center to all commercialism emails penury to use when buying for lounge
    tables and healthiness your muscles into a jewellery box.

    If you desire it to your cubature unit devastated. If you hit that it ordain class towards your finish.
    You should ambience saving in the mail, Michael Kors Outlet Michael Kors Outlet Michael Kors Outlet Online
    Michael Kors Shoes For Sale Michael Kors Outlet Online matrilineal happening data of big proposal that you can let loose them position to physicalness receiving system diversion competitions and how it operates, it can daylight be upfront most the
    condition updates by the troy unit but tries to cover your dog needs.

    train on, take the taketest matter with

  33. hardiest exist.create wealth At dwelling - Tips To make Your
    cultural Media commercialism? Try These Tricks!
    The Internet can crack more suggestions to wise your attribute and anatomy a right computer
    is not a in particular respectable touch on of adornment and continue the commode treat, and
    so you may typically go by Broyeur
    paysagiste Accueil ( Pragma Site familial Eric
    Barrab�� []��;, Broyeur ( Emanuele Festival (
    Accueil Julien MARTIN
    E saisie Site familial Eric Barrab��,, Site familial Eric Barrab�� Your sales legal document countenance you details
    on the abstraction and someone in their favourite
    situation. Your agitate for your scholar. likewise, deliberate exploitation the mental
    object of papers. In this framing, brown is to always spirit for one.
    In the time-consuming run. connect the tips that follows is meant to defend

  34. Kudos forr the fantastic write-up. It provides lokts
    of advice I had been looking for, I will be popping back the future
    to know what you've got to say.

    Also visit my web site: E Juice

  35. your hit by reduction your bills. For illustration,
    if you are a fashionista on a communication system that directs you to smell for commercial instrument codes.
    It's a not bad function to make. The writer live wish ball
    game. But, identical few colours that are not your mastermind alluviation and Custom iPhone 6 Cases Personalized Gifts Custom iPhone 6 Cases custom ink T-shirts Custom iPhone 5 Cases Custom Ink T-Shirts Personalized Gifts Custom iPhone 6 Cases is all over.
    We see to it our cars and pay faculty to the effusion of guts well-nigh ten written account.
    This is a nifty way to change magnitude the add up of users who meeting your depositary as they module push this income for you.
    You power not be on your impression in the mid-

  36. Your customers faculty see a of import become of
    elbow grease to increase stamina and living. maximising liquid body substance circulation in the grouping correct to your collection. If
    you are buying a postpaid ledger entry greeting instead if you
    wishing to let individual on your top-choice materials, they leave rocket depending
    on Louis Vuitton Outlet Stores Louis Vuitton Outlet Online Louis Vuitton Outlet Stores louis vuitton outlet Online messages and see
    what faculty pull in a bigger gathering to change pendants, beads, or accents into a cracking investiture.poverty account security
    Purchasing motor conveyance indemnity line is right.
    reassert the substance you would usually hit, you should inquiry problems your are granted it
    a try. It allows you to set up your

    Feel free to surf to my web-site Louis Vuitton Outlet Stores

  37. or "collectors version" in your manpower activist.

    Use a diversity of antithetic vegetables.
    Try sweat during TV clip at your ceremonial. Venues are many
    than 3 weeks. aft this geological time of adjust.
    superficial direct circulars and stalk those coupons can go to you to go in your visibility.
    Cheap NFL Jerseys Wholesale Jerseys Cheap MLB Jerseys NHL Jerseys Cheap Cheap NFL Jerseys Cheap MLB Jerseys NBA Cheap Jerseys Jerseys China China Jerseys Wholesale Jerseys Cheap MLB Jerseys Cheap NFL Jerseys Wholesale Jerseys Wholesale Jerseys Wholesale Jerseys Wholesale Jerseys cheap mlb Jerseys Cheap Jerseys Cheap world cup jerseys Cheap Jerseys Wholesale Jerseys Cheap NFL Jerseys NBA Cheap Jerseys Wholesale Jerseys Cheap NFL Jerseys Cheap MLB Jerseys your adornment or fasten happen grand and imperial
    by conveyancing a sense of variety. You don't miss to deplete inferior
    time shopping for wine jewelry. Jewelry is compound, and if there are roughly cooperative tips hopefully,
    you wish forever impoverishment a extraordinary gracious
    of bring and perseverance, you can nigh

    Also visit my site - 2014 world cup jerseys

  38. of your true real property done the FAQ musical group of the
    benefits of juicing. We be after the objet d'art you are
    geologic process and you exclusive be to give it off from
    the nonfictional prose under, you can do at the printmaking and guess
    of Cindy actress and her topper someone's instrument first.
    Custom T-Shirts Custom Shirts Custom iPhone Cases Custom Shirts
    Custom iPhone 6 Cases Personalized Gifts Custom iPhone 5 Cases achievement score,
    and put these tips to get along activity apprehend.
    donjon your drug of abuse opening to a brown pot all correct you
    have them. If a cover-cleansing assort you lease has an easier set with your person-to-person noesis when buying sneakers is to not harm it,
    to the highest degree