Skip to content

Eight Ball

Zach Kysar edited this page Mar 24, 2016 · 5 revisions

Overview

In this lesson we will be using a canvas component to draw text on an image background to emulate a magic eight ball. We will trigger these changes via sensors built into the phone.

New Concepts

Lists:

Add these block components to your code to create a list of variables. Many apps use lists of data. For example, a game may keep a list of high scores and your Facebook app keeps a list of your friends. Lists are a type of data structure used in every programming language, not just App Inventor. We use lists to create and manipulate different sets of values/elements.

### Random: Given a list of elements we can select a random element with a simple call to this list procedure. ![random](https://raw.githubusercontent.com/cppignite/lessons/master/EightBall/img/random.png ) ### Sensors: Sensors are devices that are built into smartphones that detect certain important information about the phone. A full list of the sensors we have access to in App Inventor is on the left.

Using the accelerometer we can detect shaking and measures acceleration in three dimensions. Acceleration is measured in SI units (m/s 2 ). If the device is a rest lying flat on its back, the Z acceleration will be about 9.8. We can use various procedures to get the exact speed of the device, but in our case we just need to check if its shaking. App Inventor provides us with a procedure to handle this detection, see the image on the right.

Canvas:

A canvas is basically a big white board. We can draw anything we can think of on this whiteboard by specifying the location where we would like to draw and what we want to be drawing.

canvas

Any location on the Canvas can be specified as a pair of (X, Y) values, where X is the number of pixels away from the left edge of the Canvas Y is the number of pixels away from the top edge of the Canvas.

Try using the procedures above to draw various objects onto your canvas.

Let's Get Started:

User Interface Designer:

We will need a canvas with a background image (see the media and assets section). We will also add an accelerometer sensor here.

ui

Block Logic Editor:

Using the tools provided:

  1. Create a list and fill it with text copies of each response you’re eight ball will give
  2. Draw text in the center of the canvas when the screen is loaded using the 'when screen initialize procedure' giving the user instructions to shake the phone.
  3. Using your sensor, change the text in the center to a random response selected from your list when the device is shook.

Media and Assets

  1. 8_ball.png

External References:

  1. Lists
  2. Sensors
  3. Canvas
Clone this wiki locally