Go to notes and algorithms index. ~ Go to home page.

A Simple Bouncing Ball Program


This is just a simple bouncing ball program written in Yabasic. It may provide a good starting point to a beginner who is using Yabasic or similar. It uses the bit mapped graphics in Yabasic by opening a graphics window.

Unfortunately the version of Yabasic I used only allowed one colour in the graphics window (not that it mattered for this program).

Yabasic can be down-loaded free from www.yabasic.de.

The ball bounces for a while travelling from left to right, then when it slows right down the program closes the graphics window and ends.






#!/usr/bin/yabasic

rem   A bouncing ball prog.

rem   A demo by Jon P written for Jenny     Feb 2005


clear screen

graphic_win_width = 300
graphic_win_height = 200

open window graphic_win_width, graphic_win_height

radius = 10
x = 20
old_x = x
y = 20
old_y = y
velocity_x = 5
velocity_y = 0

keep_going = 1
while ( keep_going )

   clear fill circle old_x, old_y, radius + 2
   fill circle x, y, radius
   pause 0.02


   rem  Remember the old X and Y position so that we can erase the ball from its
   rem   old position next time round...
   old_x = x
   old_y = y

   rem Add gravity...
   velocity_y = velocity_y + 0.3

   rem Add velocity to position...
   x = x + velocity_x
   y = y + velocity_y

   rem Abate the velocity to take into account air resistance...
   velocity_x = velocity_x * 0.98
   velocity_y = velocity_y * 0.98

   if y + radius > graphic_win_height then
      rem Bounce ball off bottom (by reversing it's sign and reducing its speed a bit)...
      velocity_y = velocity_y * -0.9
      if y + radius > graphic_win_height then
         y = graphic_win_height - radius
      endif
   endif

   rem  If ball has slowed right down then end the program...
   if abs( velocity_x ) + abs( velocity_y ) < 0.2 then
      keep_going = 0
   endif

wend

pause 1

close window

exit

end