Mobile apps with App Inventor
Catch the Ball
Make a phone game: a ball bounces round the screen, getting faster with every catch, and you have 30 seconds.
Time for a game. A red ball bounces round the screen, and you tap it to catch it. Every catch sends it somewhere new, a little faster than before, and a clock counts down the 30 seconds you have to get the best score you can.
You will learn
- Animate a Ball with its Speed, Heading and Interval
- Bounce off the edges of a Canvas
- Use a Clock as a timer
- End a game by switching things off
You will need
- A computer with a web browser
- A phone or tablet with the MIT AI2 Companion app
- Days 2 and 4, for random numbers and global variables
Words to know
- sprite
- A moving object on a Canvas, such as a Ball.
- heading
- The direction a sprite moves, in degrees: 0 is right and 90 is up.
- Clock
- A non visible timer whose Timer event happens again and again.
- Enabled
- A property that switches a component on or off.
Step by step
Step 1: Score and time
Start a new project called
CatchTheBall, with the TitleCatch the Balland AlignHorizontal Center. Add a HorizontalArrangement with two Labels in it,LabelScoresayingScore: 0andLabelTimesayingTime: 0, both bold, size 18.App InventorMy ProjectsGuidePaletteSearch Components...User InterfaceButton?CheckBox?DatePicker?Image?Label?ListPicker?ListView?Notifier?PasswordTextBox?Slider?Spinner?Switch?TextBox?TimePicker?WebViewer?LayoutMediaDrawing and AnimationMapsSensorsSocialStorageConnectivityLEGO® MINDSTORMS®ExperimentalExtensionViewerDisplay hidden components in Viewer9:41Catch the BallScore: 0Time: 0ComponentsScreen1HorizontalArrangement1LabelScoreLabelTimeRenameDeletePropertiesLabelTime (Label)BackgroundColorNoneFontBoldFontItalicFontSize18FontTypefacedefaultHTMLFormatHasMarginsHeightAutomaticWidthAutomaticTextTime: 0TextAlignmentleft : 0TextColorDefaultVisibleThe score and the time, side by side. Step 2: A canvas and a ball
Add a Canvas from Drawing and Animation: Width Fill parent, Height 320 pixels, and a pale blue BackgroundColor, which is under Custom in the colour list. Then drag a Ball onto the canvas. Set its Radius to
20and PaintColor to Red. Set Speed to10, Heading to45and Interval to50: now it moves on its own, 10 pixels every 50 milliseconds, towards the top right.App InventorMy ProjectsGuidePaletteSearch Components...User InterfaceLayoutMediaDrawing and AnimationBall?Canvas?ImageSprite?MapsSensorsSocialStorageConnectivityLEGO® MINDSTORMS®ExperimentalExtensionViewerDisplay hidden components in Viewer9:41Catch the BallScore: 0Time: 0ComponentsScreen1HorizontalArrangement1LabelScoreLabelTimeCanvas1Ball1RenameDeletePropertiesBall1 (Ball)EnabledHeading45Interval50OriginX0.0OriginY0.0PaintColorRedRadius20Speed10VisibleX100Y100Z1.0A red ball on a pale blue canvas. Step 3: Bounce off the edges
Test it now and the ball flies off and sticks at the edge. In Blocks, add when Ball1.EdgeReached, which tells you which edge it hit, and call Ball1.Bounce with that edge.
App InventorMy ProjectsGuideBlocksBuilt-inControlLogicMathTextListsDictionariesColorsVariablesProceduresScreen1HorizontalArrangement1LabelScoreLabelTimeCanvas1Ball1Any componentRenameDeleteShow Warningswhen Ball1.EdgeReachededgedocall Ball1.Bounceedgeget edgeHit an edge, bounce off it. Step 4: Catch it!
Make a global
score. when Ball1.Touched: add 1 to the score, show it, jump the ball to a random place with call Ball1.MoveTo, and make it 2 faster. The better you get, the harder it gets.App InventorMy ProjectsGuideBlocksBuilt-inControlLogicMathTextListsDictionariesColorsVariablesProceduresScreen1HorizontalArrangement1LabelScoreLabelTimeCanvas1Ball1Any componentRenameDeleteShow Warningsinitialize global score to 0when Ball1.Touchedxydoset global score to get global score + 1set LabelScore.Text to join“ Score: ”get global scorecall Ball1.MoveToxrandom integer from 0 to 250yrandom integer from 0 to 250set Ball1.Speed to Ball1.Speed + 2Each catch scores, moves the ball and speeds it up. Step 5: Thirty seconds
A Clock from Sensors is a timer: its Timer event happens every 1000 milliseconds, once a second. Add one, then count the seconds in a global
time. At 30, stop the clock, stop the ball by switching off its Enabled, and say Game over!App InventorMy ProjectsGuidePaletteSearch Components...User InterfaceLayoutMediaDrawing and AnimationMapsSensorsAccelerometerSensor?BarcodeScanner?Barometer?Clock?GyroscopeSensor?LightSensor?LocationSensor?OrientationSensor?Pedometer?ProximitySensor?SocialStorageConnectivityLEGO® MINDSTORMS®ExperimentalExtensionViewerDisplay hidden components in Viewer9:41Catch the BallScore: 0Time: 0Non-visible componentsClock1ComponentsScreen1HorizontalArrangement1LabelScoreLabelTimeCanvas1Ball1Clock1RenameDeletePropertiesClock1 (Clock)TimerAlwaysFiresTimerEnabledTimerInterval1000Clock1, a non visible timer. App InventorMy ProjectsGuideBlocksBuilt-inControlLogicMathTextListsDictionariesColorsVariablesProceduresScreen1HorizontalArrangement1LabelScoreLabelTimeCanvas1Ball1Clock1Any componentRenameDeleteShow Warningsinitialize global time to 0when Clock1.Timerdoset global time to get global time + 1set LabelTime.Text to join“ Time: ”get global timeif get global time = 30thenset Clock1.TimerEnabled to falseset Ball1.Enabled to falseset LabelTime.Text to “ Game over! ”Count the seconds, and stop at 30. Step 6: Play it
Connect the Companion and play. How many can you catch in 30 seconds?
9:41Catch the BallScore: 7Time: 18Tap the ball to catch it, before time runs out.
Test it
Tick each one when it works. If one does not, look back at the step it comes from.
Stretch challenges
Finished early? Try these. Each one has a hint if you get stuck.
Play again
Add a Play again button.
Show a hint
Set
scoreandtimeto 0, update both labels, set the ball's Speed back to 10, and switch Enabled back on for the ball and TimerEnabled for the clock.A bad ball
Add a second, black ball that loses a point when caught.
Show a hint
A Ball2 with its own EdgeReached and Touched events. Take 1 away from the score instead of adding.
Sound effects
Play a sound on every catch, and buzz when the game ends.
Show a hint
A Sound component can play a sound file you upload in Media, and
call Sound1.Vibratebuzzes.
Notes for the teacher
Timing
- 15 minutes: steps 1 and 2.
- 20 minutes: steps 3 and 4. Watch the ball stick at the edge before adding the bounce block: it makes the point.
- 15 minutes: step 5, then play.
Mistakes to look out for
- The ball does not move: Speed is 0, or the Ball is not on the Canvas.
- The score label shows the score before adding 1, because the blocks are in the wrong order.
- The game never ends: the test is
time = 30in the Math compare block, and the Clock's Timer is enabled. - A Ball's X and Y are its top left corner, so MoveTo up to 250 keeps a ball of radius 20 inside a 300 pixel wide canvas on most phones.
Going further
The Clock's Timer is the game loop, like setInterval in the web track and while True: on the micro:bit. Every game needs one.