19.04.2017 Views

Learn to Program with Small Basic

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Animated Squares<br />

Let’s write a program that creates a 4×8 grid of randomly colored squares<br />

and then animates these squares <strong>to</strong> fly <strong>to</strong> the upper-left corner of the<br />

graphics window, as shown in Figure 17-4.<br />

Before animation<br />

During animation<br />

Figure 17-4: Illustrating the output of AnimatedSquares.sb<br />

The complete application is shown in Listing 17-2.<br />

1 ' AnimatedSquares.sb<br />

2 ' Creates a 4x8 grid of randomly colored squares<br />

3 For r = 1 To 4 ' 4 rows<br />

4 For c = 1 To 8 ' 8 columns<br />

5 clr = GraphicsWindow.GetRandomColor()<br />

6 GraphicsWindow.BrushColor = clr<br />

7 box[r][c] = Shapes.AddRectangle(20, 20) ' Adds a square<br />

8 Shapes.Move(box[r][c], c * 20, r * 20) ' Positions it<br />

9 EndFor<br />

10 EndFor<br />

11<br />

12 ' Animates the squares <strong>to</strong> the upper-left corner of the window<br />

13 For r = 1 To 4<br />

14 For c = 1 To 8<br />

15 Shapes.Animate(box[r][c], 0, 0, 1000)<br />

16 <strong>Program</strong>.Delay(400) ' A small delay (in milliseconds)<br />

17 EndFor<br />

18 EndFor<br />

Listing 17-2: Using a matrix <strong>to</strong> s<strong>to</strong>re shape IDs<br />

The program uses a nested For loop <strong>to</strong> create the squares (lines 3–10).<br />

The outer loop (which creates the rows) runs four times, and the inner<br />

loop (which creates the columns) runs eight times (lines 3–4), for a <strong>to</strong>tal of<br />

32 iterations (4×8). In each pass of the inner loop, the square’s color is set<br />

by changing the BrushColor property (lines 5–6), and a square is created by<br />

calling AddRectangle(). We save its identifier in box[r][c] (line 7) and then<br />

move the created square <strong>to</strong> its position on the square grid (see Figure 17-4).<br />

Let’s take a closer look at lines 7–8.<br />

At line 7, the AddRectangle() method takes the width and the height of<br />

the desired rectangle and returns an identifier of the created shape. In this<br />

example, we pass 20 for both arguments <strong>to</strong> create a square, and we save<br />

the returned identifier in box[r][c].<br />

Expanding <strong>to</strong> Higher-Dimension Arrays 245

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!