Basics: Project 107h
Project name: Building your second game app with MIT App Inventor 2
Tags: MIT App Inventor 2, Second game app
We will learn how to build another simple game app Mole Mash with the MIT App Inventor 2 software. You will learn about animation in MIT App Inventor 2. In this game a mole pops up at random positions on a playing field, and the player scores points by hitting the mole before it jumps away.
In this game the mole moves once every half-second. If it is touched, the score increases by one, and the phone vibrates. Pressing restart resets the score to zero.
This project introduces:
- image sprites
- timers and the Clock component
- picking random numbers between 0 and 1
- text blocks
We assume that you have read our previous projects about MIT App Inventor 2.
Step By Step instruction
1.Go to appinventor.mit.edu and click on Create Apps! orange button.
2.Click on Start new project and give your project a name. As we’re just exploring the MIT App Inventor 2, you can name it as MoleMash. Click on OK button. Your project will be saved.
3.Go to Designer editor tab.
4.Select components to design your app. From the Drawing and Animation drawer, drag out a Canvas component and drop it onto the Viewer.
5. The default setting for MIT App Inventor 2 is that the screen of your app will be “scrollable”, which means that the user interface can go beyond the limit of the screen and the user can scroll down by swiping their finger (like scrolling on a web page). Set the Screen1’s Title field to “MoleMash”.
6. Change the name of Canvas1 to “MyCanvas” and put it on top and set its dimensions to 300 pixels wide by 300 pixels high.
7.Download the picture of a mole – mole.png (see in Attachments on the beginning of this project) and save it on your PC.
8. Drag out a Label component from User Interface drawer under Pallete and drop it onto the Canvas . Name it “ScoreLabel” that shows the score, i.e., the number of times the player has hit the mole.
9. Set the Text field of ScoreLabel to “Score: —“.
10. Drag out a Button component from User Interface drawer under Pallete and drop it onto the Canvas . Name it as ” ResetButton “. Set the Text field of ResetButton to “Reset”.
11. Drag out a Sound component from Media drawer under Pallete and drop it onto the Canvas. It will go into the Non-visible components area. Name it as “Noise”. We will use Noise to make the phone vibrate when the mole is hit.
12.You need to arrange for the mole to jump periodically, and you’ll do this with the aid of a Clock component. The Clock component provides various operations dealing with time, like telling you what the date is. Here, you’ll use the component as a timer that fires at regular intervals. The firing interval is determined by the Clock ‘s TimerInterval field. Drag out a Clock component from Sensors drawer and drop it onto the Canvas; it will go into the Non-visible components area. Name it “MoleTimer”. Set its TimeInterval to 500 milliseconds to make the mole move every half second. Make sure that TimerEnabled is checked.
13.To add the moving mole we’ll use a sprite. Sprites are images that can move on the screen within a Canvas. Each sprite has a Speed and a Heading, and also an Interval that determines how often the sprite moves at its designated speed. Sprites can also detect when they are touched. In MoleMash, the mole has a speed zero, so it won’t move by itself. Instead, you’ll be setting the mole’s position each time the timer fires. Drag an ImageSprite component onto the Viewer. You’ll find this component in the Drawing and Animation drawer under Palette. Place it within MyCanvas area.
14. Name it as “Mole”. Set these properties for the Mole sprite:
- Picture: Use mole.png
- Enabled: checked
- Interval: 500 (The interval doesn’t matter here, because the mole’s speed is zero: it’s not moving by itself.)
- Heading: 0 (The heading doesn’t matter here either, because the speed is 0).
- Speed: 0.0
- Visible: checked
- Width: Automatic
- Height: Automatic
You should see the x and y properties already filled in. They were determined by where you placed the mole when you dragged it onto MyCanvas. Go ahead and drag the mole some more. You should see x and y change. You’ve now specified all the components. The Designer should look like this. Notice how Mole is indented under MyCanvas in the component structure list, indicating that the sprite is a sub-component of the canvas.
15.Now you’ll specify the component behavior. This introduces some new MIT App Inventor 2 ideas. The first is the idea of a procedure. A procedure is a sequence of statements that you can refer to all at once as single command. If you have a sequence that you need to use more than once in a program, you can define that as a procedure, and then you don’t have to repeat the sequence each time you use it. Procedures in MIT App Inventor 2 can take arguments and return values. This project covers only the simplest case: procedures that take no arguments and return no values. Let’s define two procedures: MoveMole – moves the Mole sprite to a new random position on the canvas; UpdateScore – shows the score, by changing the text of the ScoreLabel.
16. Go to Blocks editor tab. So far you have been arranging your app’s screen and components in the Designer, which is in a web browser window. To start programming the behavior of the app, you need to go to the Blocks editor. Click the Blocks button in the upper right of your screen to go to the Blocks Editor.
17.In the Blocks editor, under Built-In, open the Procedures drawer. Drag out a to procedure do block and change the label “procedure” to “MoveMole”. The to MoveMole block has a slot labeled “do”. That’s where you put the statements for the procedure. In this case there will be two statements: one to set the mole’s x position and one to set its y position. In each case, you’ll set the position to be a random fraction, between 0 and 1, of the difference between the size of the canvas and the size of the mole. You create that value using blocks for random fraction and multiplication and subtraction. You can find these in the Math drawer under Built-In.
The completed MoveMole event handler should look like this:
MoveMole does not take any arguments so you don’t have to use the mutator function of the procedure block. Observe how the blocks connect together: the first statement uses the Mole.X set block to set mole’s horizontal position. The value plugged into the block’s socket is the result of multiplying:
- The result of the call random fraction block, which a value between 0 and 1.
- The result of subtracting the mole’s width from the canvas width.
The vertical position is handled similarly.
18. The next step is to define a variable called score to hold the score (number of hits) and give it initial value 0. In the Blocks editor, under Built-In, open the Variables drawer. Drag out a initialize global name to block and change the label “name” to “score”. Got to Math drawer under Built-in and drag out the value 0 block.
19. Define a procedure UpdateScore that shows the score in ScoreLabel. In the Blocks editor, under Built-In, open the Procedures drawer. Drag out a to procedure do block and change the label “procedure” to “UpdateScore”.
20. Select ScoreLabel drawer and drag out a set ScoreLabel.Text to block and insert in to UpdateScore do block.
21. The actual contents to be shown in ScoreLabel will be the text “Score: ” joined to the value of score. In the Blocks editor, under Built-In, open the Text drawer. Use a join block to attach this to a block that gives the value of the score variable. You can find a join block in the Text drawer. Drag out a join block. To create the “Score: ” part of the label, drag out a text block from the Text drawer. Change the block to read “Score: ” rather than ” “.
22.In the Blocks editor, under Built-In, open the Variables drawer. Drag out a get block and insert to the join block. Then in the get block select global score.
23.Here’s how UpdateScore should look:
24. Add a Timer. The next step is to make the mole keep moving. Here’s where you’ll use MoleTimer. Clock components have an event handler called when MoleTimer.Timer do that triggers repeatedly at a rate determined by the TimerInterval. Set up MoleTimer to call MoveMole each time the timer fires.
25. In the Blocks editor, under Built-In, open the Procedures drawer. Drag out a call MoveMole block and insert to the when MoleTimer.Timer do block. Notice how the mole starts jumping around on the phone as soon as you define the event handler. This is an example of how things in App Inventor start happening instantaneously, as soon as you define them.
26. Add a Mole Touch Handler. The program should increment the score each time the mole is touched. Sprites, like canvases, respond to touch events. You can use typeblocking: typing to quickly create blocks. For example, to create a value block containing 100, just type 100 and press return; to create a MoveMole block, just type MoveMole and select the block you want from the list.
So create a touch event handler for Mole that:
- Increments the score.
- Calls UpdateScore to show the new score.
- Makes the phone vibrate for 1/10 second (100 milliseconds).
- Calls MoveMole so that the mole moves right away, rather than waiting for the timer.
From Mole drawer drag out when Mole.Touched x y do block. Then from Variables drawer drag out set to block and get block, select global score.
Go to Math drawer and drag out two blocks and join them as shown below. The value block “0” value change to “1”.
From Noise drawer drag out call Noise.Vibrate millisecs block. Then from Math drawer drag out value block. Change the value “0” to “100”.
From Procedures drawer drag out call UpdateScore and call MoveMole blocks.
The when Mole.Touched do event handler will looks like that:
27. One final detail is resetting the score. That’s simply a matter of making the ResetButton change the score to 0 and calling UpdateScore.
28. Your final blocks should look like this. Try it out on your device or with the emulator! Congratulations, your second game app is running!
29.While your device (emulator or phone/tablet) has been connected to App Inventor, your app has been running in real time on your device. If you disconnect the emulator/device from the Blocks Editor, the app will vanish. You can always make it return by reconnecting the device. To have an app running without being connected to App Inventor, you must “package” the app to produce an application package (apk file). To “package” the app to install on your device or to send to someone else, click the Build tab at the top of the screen. Under Build, there are two options available for you to choose from:
- App (provide QR code): You can generate a Barcode (a QR Code), which you can use to install the app on a mobile device that has a camera, with the aid of a barcode scanner, like the ZXing barcode scanner (freely available in Google Play). This barcode is only good for two hours. If you want to share your app with others via barcode over a longer period, you’ll need to download the .apk file to your computer and use a third-party software to convert the file into a barcode. More information can be found here.
- App (save to my computer): You can download the app to your computer as an apk file, which you can distribute and share as you like by manually installing it on other devices. (sometimes called “side loading“).
We have successfully built the second game app with MIT App Inventor 2. There are some ideas which you can explore:
- Make the game vary the speed of the mole in response to how well the player is doing. To vary how quickly the mole moves, you’ll need to change the MoleTimer’s Interval property.
- Keep track of when the player hits the mole and when the player misses the mole, and show a score with both hits and misses. To do this, you’ll need do define touched handlers both for Mole, same as now, and for MyCanvas. One subtle issue, if the player touches the mole, does that also count as a touch for MyCanvas? The answer is yes. Both touch events will register.
We have learned that:
- Sprites are touch-sensitive shapes that you can program to move around on a Canvas.
- The Clock component can be used as a timer to make events that happen at regular intervals.
- Procedures are defined using to procedure blocks.
- For each procedure you define, App Inventor automatically creates an associated call block and places it in the Procedures drawer.
- Making a random-fraction block produces a number between 0 and 1.
- Text blocks specify literal text, similar to the way that number blocks specify literal numbers.
- Typeblocking is a way to create blocks quickly, by typing a block’s name.