Title: Alice in Action with Java
1Alice in Action with Java
2Objectives
- Use the Boolean type and its basic operations
- Use the if statement to perform some statements
while skipping others - Use the for and while statements to perform
(other) statements more than once - Use Boolean variables and functions to control if
and while statements - Use the wait()message to temporarily suspend
program execution
3Flow Control
- Flow sequence of steps for performing a user
story - Flow control statement structure for managing
flow - Flow control statements used in previous chapters
- doInOrder produces a sequential execution
- doTogether produces a parallel execution
- Control statements introduced in the current
chapter - if directs program flow along one of two paths
- for directs flow into a fixed number of loops
- while directs flow into an arbitrary number of
loops
4Flow Control (continued)
5The Boolean Type
- A basic Alice type used to define Boolean
variables - A Boolean variable holds a value of true or false
- Other basic types Number and Object
- Condition (Boolean expression)
- Produces a value of true or false
- Basis for decision-making in programs
6Boolean Functions
- Return a value of true or false
- Can act as a condition in an if or while
statement - Many refer to an objects bounding box
- Example obj.isBehind(obj2)
- true, if objs position is beyond obj2s rear
edge - false, otherwise
7Boolean Variables
- Used to store a value of true or false
- Can be used in condition for if or while
statement - How to create a Boolean variable
- Click create new variable (or parameter) button
- Specify Boolean as variable (or parameter) type
8Relational Operators
- Produce true or false values
- Six relational operators , !, lt, lt, gt, gt
- Located in functions pane of worlds details area
- Most often used to compare Number values
- Example hoursWorked gt 40
- hoursWorked is a Number variable
- true when more than 40 hours have been worked
9Relational Operators (continued)
10Boolean Operators
- Used to modify or combine relational operations
- Three Boolean operators AND, OR, NOT
- Located in functions pane of worlds details area
- Example age gt 12 age lt 20
- age is a Number variable
- Teen number compared to condition returns true
11Boolean Operators (continued)
12Introducing Selective Flow Control
- Summary of a scene with a princess and a dragon
- Princess meets a mute dragon and asks questions
- Dragon shakes its head to respond yes or no
- Objective write a shakeHead()method
- Requirements for shakeHead()
- Parameter yesOrNo, a String
- If yesOrNo yes, dragon shakes head up and
down - If yesOrNo no, dragon shakes head sideways
- Use an if statement to produce conditional
behavior - The if control structure is at bottom of editing
area
13Introducing Selective Flow Control (continued)
14if Statement Mechanics
- Value of a condition determines direction of flow
- Structure of an if statement
- if (Condition )
Statements1
else
Statements2 - if statement behavior is also called selective
flow - If Condition is true, Statements1 are selected
- If Condition is false, Statements2 are selected
15if Statement Mechanics (continued)
16Building if Statement Conditions
- Coding the condition of the if statement
- Click on the yesOrNo parameter
- Drag parameter into the editing area
- Drop the parameter onto the conditions
placeholder - Choose other and then type yes
- Overview for coding the remainder of shakeHead()
- Add headMovement variable for amount of turn
- Add turn()statements for up and down motion
- Add turn()statements for sideways motion
17Building if Statement Conditions (continued)
18Building if Statement Conditions (continued)
- Building a scene method that uses shakeHead()
- princess greets dragon using a say()message
- princess asks four questions
- shakeHead()is called in response to each question
- Click the Play button to test the program
19Building if Statement Conditions (continued)
20Building if Statement Conditions (continued)
21The wait()Statement
- Pauses a program for specified number of seconds
- Form of wait()statement wait(numSecs)
- Use of wait()scene with dragon and princess
- Inserted between princesss first and second
lines
22Validating Parameter Values
- if statement can be used to guard set of
statements - Flow enters only if parameter values are valid
- Example check distance value passed to jump()
- Check for positive value with condition distance
gt 0 - Check jump length with distance lt MAX_DISTANCE
- Combine two conditions with the AND () operator
- distance gt 0 distance lt MAX_DISTANCE
- How to incorporate validating logic using if
structures - Place original jump()logic onto true path (outer
if) - Place validating logic in the false path (nested
if)
23Validating Parameter Values (continued)
24Validating Parameter Values (continued)
25Validating Parameter Values (continued)
26Introducing Repetition
- Refer to flapWings()method from Figure 2-16
- Enhancement use for loop to flap wings numTimes
- Overview for implementing the enhancement
- Open the flapWings()method
- Adjust the duration values for the wing movements
- Drag loop control to the top of the method and
drop - Select numTimes for number of iterations
- Drag the doInOrder statement into the for
statement
27Introducing Repetition (continued)
28Introducing Repetition (continued)
29Mechanics of the for Statement
- Repeat statement execution a fixed number of
times - Example pass 3 to flapWings()for 3 flaps
- Structure of the simple for statement
- for(int index 0index lt limitindex) Stateme
nts - The for statement is also known as a counting
loop - First statement in ( ) initializes the index
- Second statement in ( ) checks index against
limit - Third statement in ( ) increments the index
30Mechanics of the for Statement (continued)
31Mechanics of the for Statement (continued)
- To test a for loop, trace the behavior with
values - Statements are executed while index lt numTimes
- Example send flapWings(3)to the dragon object
- Simple version of for lets you modify limit value
- Purpose of show complicated version button
- Change initial value of index and/or update to
index - Example change update to index2
- Note neither version of for allows you to count
down
32Mechanics of the for Statement (continued)
33Mechanics of the for Statement (continued)
34Nested Loops
- Three shots enhancing Scene 1 of dragon animation
- Dragon flies toward a castle in the countryside
- As dragon nears castle, it circles the tower
three times - Dragon then descends and lands on the drawbridge
- One way to build the first shot
- Go to go into the Add Objects window
- Position the dragon above the castles drawbridge
- Move dragon up until it is even with the castles
tower - Drop a dummy and then drag the dragon off-screen
- Use setPointOfView()to properly position dragon
35Nested Loops (continued)
- One way to build the second shot
- Use for statement to control other flying
statements - Understanding the mechanics of Shot 2
- Outer for controls inner (nested) for in
flapWings() - AsSeenBy()attribute revolves dragon around castle
- Increase duration of turn()to synchronize moves
- Set style to smooth the animation
- The third shot is discussed in Section 4.4
36Nested Loops (continued)
37The while Statement
- limit value in for loop must be set to a fixed
value - Circumstance when the for loop is appropriate
- Statements are to be executed a fixed number of
times - Problem looping when the limit value is unknown
- Solution use a while statement
38Introducing the while Statement
- Strategy for building third shot of dragon
animation - Repeatedly have dragon flap its wings
- Move dragon downward while it is above drawbridge
- Overview for building the third shot
- Place doTogether statement in doInOrder statement
- Use setPointOfView()to move camera closer
- Send flappingWings()message to the dragon
- Drag the while statement to the editing area
- Drop the while statement below doInOrder
- Insert placeholder value into the while condition
39Introducing the while Statement (continued)
40Introducing the while Statement (continued)
- Building the third shot (continued)
- Drag dragons isAbove()over condition and drop
- Add castle.bridge argument to isAbove()
- Insert doTogether statement in the while loop
- Add move() method to cause dragon to descend
- Send another flapWings()message to dragon
- Use setPointOfView()to zoom in for a close-up
- Infinite loop occurs if loop lacks falsifying
condition - In third shot, move()eventually terminates loop
41Introducing the while Statement (continued)
42Introducing the while Statement (continued)
43while Statement Mechanics
- Provides for both definite and indefinite looping
- Structure of a while loop
- while ( Condition )
Statements
- The while loop is more general than the for loop
- Flow enters while structure if Condition is true
- One statement must eventually falsify Condition
44while Statement Mechanics (continued)
45Comparing the for and while Statements
- while statement can produce any type of
repetition - for statement is used for fixed number of
repetitions - Loop selection question to ask Am I counting?
- If yes, use a for statement otherwise, use while
- Both loops test conditions before flow enters
structure - Both loops are bypassed if initial condition is
false
46A Second Example
- Setting up the scene
- Use shebuilder to create a soccer player (Jane)
- Place soccerBall object in Janes hands
- Writing a dropBounce()method for soccerBall
- Move the ball down distanceToGround meters
- Change distanceToGround by bounce factor (2/3)
- Move ball up reduced distanceToGround meters
- Bouncing continues while distanceToGround gt 0
- Writing a janeDropsBall()method
- Send roll()messages to forearms
- Send dropAndBounce()message to soccerBall
47A Second Example (continued)
48A Second Example (continued)
49A Second Example (continued)
50Flow-Control Functions
- Functions can be defined to answer questions
- Complex questions are asked by flow-control
functions
51Spirals and the Fibonacci Function
- User story
- Scene 1 girl finds an old book and reads
contents - Scene 2 girl uses the map to locate a palm tree
- Scene 3 girl follows spiral from tree to
treasure site - Coding spiral motion in Scene 3 is greatest
challenge - Many natural spirals are based on Fibonacci
numbers - Fibonacci numbers (sequence)
- Number gt 1 is found by adding two preceding
numbers - Example 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,
144, ... - Spiral inscribed in rectangles built from the
sequence
52Spirals and the Fibonacci Function (continued)
53Spirals and the Fibonacci Function (continued)
- Approximating Fibonacci spiral in playScene3()
- Have girl move 6 times
- Distance of each move equals next Fibonacci
number - While moving forward, girl also turns left 1/4
revolution - playScene3()requires a fibonacci()function
- To be designed and implemented in the next
section - Save girl as fibonacciGirl for possible reuse
54Spirals and the Fibonacci Function (continued)
55The Fibonacci Function
- Defining the outline of fibonacci()function
- Select girl and create a function named fibonacci
- Create a Number parameter named n
- Formula if n gt 1, f(n) sum of two preceding
numbers - Designing an algorithm to generate the nth number
- Create local variables result, nextToLast, last
- Add if statement to the function
- If n 1 or n 2, result 1
- Otherwise calculate nth value using formula in
for loop - fibonacci()calls in playScene3() specify spiral
56The Fibonacci Function (continued)
57Summary
- Flow control statement controls the flow of
statement execution - Condition Boolean expression producing a true or
false value - Boolean function returns true or false value
- Boolean variable holds value of true or false
- Relational operators , !, lt, lt, gt, gt
58Summary (continued)
- Boolean operators AND, OR, NOT
- if statement directs flow along one of two paths
based on evaluation of a condition - for statement repeats execution of a group of
statements a fixed number of times - while statement repeats execution of a group of
statements an arbitrary number of times - wait()statement a statement that pauses program
flow for a specified number of seconds