PI: Laboratory 1: Expressions, Statements, and Interactions

Overview

This lab will allow you to get some practice writing simple expressions
and statements in Java. It will also give you an opportunity to experiment
with interactions among entities and how these generate a variety of basic
behaviors. Portions of this lab assignment are also designed to help you
build a background in thinking the PI way.

Be sure to read through the PI general information handout, and in
particular the collaboration
policy. For this assignment, you may discuss the project in as
much detail as you like with your classmates, but you should do the
writeup on your own. You may also get comments from other students on
all portions of your writeup before turning it in, if you wish. Please
include the names of anyone with whom you collaborate, in any way, on
this assignment, and indicate the nature of the collaboration. [Failure
to include this information is a violation of the collaboration
policy.]

This assignment emphasizes the following topics

Java expressions and statements

Thinking in terms of interactions

You should read through this entire assignment and complete the Lab preparation sectionbefore you come to
lab. Some portions of the PostLab writeup also require your thinking about
them before and during the laboratory portion of the assignment.

Contents

Pre-Lab

This week's pre-lab has two parts: finger exercises and lab
preparation. You should complete both of these in writing before
coming to lab.

B. Finger exercises

Chapter 5 exercise 1 a through t and 4 a through e; Chapter 6 exercises
3 and 5.

C. Lab Preparation

The application that you'll be playing with this week is a simple
drawing application. It actually resembles a child's toy called an
Etch-A-Sketch. In case you are not familiar with an Etch-A-Sketch,
here is a brief description:

An Etch-A-Sketch is a rectangular frame (generally red) with a silver
screen in the center and two white knobs, one in each of the lower corners.
Inside the silver screen is a point of darker gray. As you turn the knobs,
the darker gray point moves around the screen, leaving a darker gray trail
behind it. By controlling the knobs carefully, you can draw pictures.

Each knob controls one direction of motion of the darker grey dot.
Rotating the left knob moves the dot from side to side. Rotating the right
knob moves the dot up and down. By rotating just one knob -- by leaving the
position of the other knob fixed, or constant -- you can draw a straight
(horizontal or vertical) line. By rotating both knobs at appropriately
coupled velocities, you can draw diagonal lines of varying slope.

In this exercise, we will perform similar operations on a similar (though
less brightly colored) display. The position of each knob will be represented
by a single number. Behind the scenes, an instruction-follower will
continually check the position of each knob and update the position of the
dot correspondingly. Note that there is one instruction follower for each
knob, and they're not guaranteed to operate at precisely the same speed.

Your job will be to write the instructions for the dot position.The trick
is that whatever instruction you write will be read (and executed)
repeatedly. If your instruction always gives the same value, it will be as
though that knob is stuck in one position. If your instruction changes the
value, the same change will be made to the knob's position over and over
again. (To keep the knob moving, you'll have to make this change relative to
the knob's current position. We'll discuss how to do this below.)

Another interesting feature of our program is that the same rule may be
used to control both knobs. The knob-rules don't have any way to tell which
knob they're controlling. You can experiment with this to see how a rule
behaves when it's being used by both knobs, or by one or the other knob.

But on to the details....

In your application, as in the Etch-a-Sketch, there is a blank screen with
a dot on it. When the dot moves, it leaves behind a trail. The motion of the
dot is controlled by two entities, one for each axis (horizontal and
vertical). Each of these entities follows a particular control rule, which
you will write. This rule tells the entity how to behave. The control rule is
automatically invoked by the application system; your job is simply to write
down appropriate control rules.

The form of a control rule is a sequence of Java statements ending in a

returndouble;

where double is some Java expression with type
double. The value returned by your control rule will be used as the
new position of the dot.

The following are thought questions that you should be able to answer
when you come to lab. You need not write the answers to these
explicitly, but you should be ready and able to answer them at
check-in. This may mean discussing them with one of us or with your
classmates to better understand the lab before you begin....

Q. How would you hold the dot in the same
position?

The Etch-a-Sketch Drawing window uses a standard cartesian
coordinate frame with (0,0) in the center and positive horizontal and
vertical coordinates in the upper right-hand quadrant. Although its
size varies as you resize the window, you can refer to the coordinate
at the edge of the window using the predefined name
maxPos. (The lower and leftmost edges are at
-maxPos.)

Q. How would you position the dot almost in
the upper right-hand corner?

You will be able to see where the dot has moved because every time that
the instruction follower moves the dot, it leaves a (red) trail behind it.
You can use this feature to draw pictures.

You will also be able to move the dot using the mouse. By clicking in a
particular point, you put the dot there. But the instruction followers
immediately go back to checking their rules, which may reposition the dot.

Q. Combining these two observations --
leaving trails and "jumping" the dot around using the mouse -- can you figure
out how to create an asterisk (a bunch of line segments intersecting in the
center)?

These questions should give you some things to think about. Also read
through the "in the lab" section, below, to get more ideas. You should plan
to complete the lab work up to the portion marked "target exercise".

Things to Try

Your job, in lab, WILL BE to try to write a series of behaviors
that cause the application to display certain kinds of pictures. We
will suggest a few to begin, but we hope that you will find the
environment interesting enough to try a few of your own. You
should read through the exercises in the tasks
section below and come up with preliminary designs for the
code that will solve them. There are also several places where you are
asked to predict what your code will do. Be sure to write up your
predictions as well as your designs. Bring these notes with you to
lab.

Note: There is far more in the lab section than you should expect
to do in lab. Do not worry about designing solutions to all of them!
One exercise is marked as the target exercise. You should try to get
as far as that exercise in lab.

The Etch-a-Sketch application has some advanced features that you
will use. For example, you can move the dot around (with your mouse)
so that it begins from a different position. Some of these features
are described below; some are mentioned in the lab handout; and others
are left for you to discover for yourself. One specific feature
involves a distinction that you will need to make in lab: You can
declare two different kinds of names in your code. One is a temporary
name that can be used during a single application of your rule. These
names can be declared anywhere in your code. They are called
variables. The other kind of name sticks around from one
use of your rule to another. These names must be declared in a special
box, separate from your rule code, but can be used freely in your rule
code. These names are called fields. You can also use
name that have been pre-defined for you, like maxPos; these
are called parameters. You must declare any fields or
variables that you wish to use. We will provide a set of parameters.
All of these features and their uses are described in the "In The Lab"
section of this handout.

Tasks

This section walks you through a series of exercises of increasing
complexity. In future labs, you will have increasing responsibility for
designing the progression from simpler cases to more complex ones. It is
always a good idea to build and test a simple version before
going on to add many features. Testing should be thorough, and designing good
test suites (sets of test cases) is a significant skill. Each time that you
add a feature, you should test your code again.

There is more listed here than you can reasonably get through in one
three-hour lab.

Static Positioning

Write Horizontal and Vertical rules that will place the ball in
position (10, 20). Try other coordinates as well, including negative
ones.

Use the Horizontal rule for both rules. What do you expect would
happen?

Use the Horizontal and Vertical rules separately again. Use the mouse
to manually move the ball to another position. Do this several
times. What happens? Explain. [In lab: Can
you "fix" this behavior?]

Implementing Velocity
We have pre-defined the name pos to hold the current position of the
dot (along the relevant dimension). Each time your rule is used,
pos will have the value at that time. (What value will pos
have if you assign to it?) Using this name and only this name, solve the
following problems.

Write a pair of rules to make the ball move horizontally from left to
right. Can you control how fast the ball moves (i.e., velocity) by
changing your code? Motion will be smoother if you move the dot only a
small amount at a time.

Use the horizontal rule for both rules. What do you expect would
happen? Explain. (When you get to lab, try it out and see if you're
right.)

What happens if the horizontal and vertical rules have different
effective velocities? (How do you make this happen?)

Use the mouse to move the dot to a different position. What happens?
Explain.

[Note: although the Etch-a-Sketch application may indicate the
availability of velocity name parameters -- myVel and other Vel --,
these names cannot be used in position-control mode.]

Implementing Acceleration

Now that you can implement velocity using position controls, implement
acceleration. (Hint: use fields.) Write your
code so you can change the initial velocity and acceleration by changing
the code.

Implementing basic acceleration is this week's target
exercise. Once you have completed it, you have done all of the
coding that you need to do for this week. If you do not get to it,
you need not do more coding; we will evaluate what you turn
in. However, you should make a point of speaking with a staff assistant.

Can you make the dot go in a parabolic path? (Hint: what accelerations
does it need?)

You should try to prepare the lab up to this point. If you get
stuck, please bring questions to our attention, work with peers, or at
least have a couple of specific questions available for us at
check-in. You should read through the exercises below to see what
else this application can do.

Wraparound Mode

Try running the code you have so far in wrap-around mode and
no-wrap-around mode (using File->Advanced Options...), and observe its
behavior.

Modify your code to make it emulate the behavior of wrap-around mode
while using no-wrap-around mode.

Although you can implement velocity and acceleration using position
controls alone, Etch-a-sketch is capable of doing this for you, and makes it
easier for you to play around with the effects of different code. In the
case of acceleration controls, you can think of the ball as a robot with
independent horizontal and vertical motors, and your rules as the controls
for its motors.

Play around with the velocity and acceleration-control mode. Play
around with the bouncing edge mode too.

Try the different position rules you wrote above (in particular, the
static positioning, velocity, and acceleration)

Write code that will draw a parabola.

Challenge: Write code that will draw a circle (given an appropriate
initial position and velocity). (Hint: remember a = v^2/r from
Physics.)

Laboratory

What to Bring to Lab

You should bring your finger exercises and a plan of action for the
laboratory (including some thoughts on how to solve the various
problems described above). You should have read the
entire problem set before you arrive. Your notes from
lab will form the basis for your post-lab writeup.

Getting Started

Running Etch-a-sketch

Since you will not be editing the Etch-a-sketch code, you will not
need to be compiling the source code for this problem set. Instead,
you'll be running the Java application we have creating and typing
your code into it.

Browse to \\stufps01\stufac\pi\Etchasketch and COPY
the folder named Etchasketch to your local PI directory. Then
double-click the etch.bat file therein contained (on your
local drive; attempting to run the BAT file off the network drive will
result in a window flashing up on your screen and immediately
disappearing). Linux people will want to download the JAR
file and then type
java -jar etchasketch.jar.

When you run the program, two windows will be displayed. The
Etch-a-Sketch Controls window is the code editing area, in which you
will write statements that will control the Etch-a-sketch. The
Etch-a-sketch Drawing window with the dot in the center is where the
output of your rules is displayed. You may want to move the windows
so that you can see both windows at the same time.

Editing Code: The Basics

If you press the Start button in the Etch-a-sketch window, you will
notice that nothing happens. This is because the motion rules of the
Etch-a-sketch have not been loaded yet. To create a rule, type into
the appropriate text box in the Code Editor, and then click
Recipe->Compile This will compile the code snippet you have
written and then use this code as the corresponding motion rule for
the Etch-a-sketch. (Note: the Etch-a-sketch has been designed so you
can load new code even while it is running. However, for more
reliable operation, we recommend that you press the "Stop" button
before compiling, and then press "Start" again after compiling.)

Messages during compilation are displayed in the DOS-like window
that initially pops up when you run the BAT file. If there are no
errors in your code, a message should appear that says, "New
Accelerator." Otherwise, error messages from the Java compiler will
be displayed. You can then edit your code, and try again.

Try typing a simple statement such as return 10; and compiling
it. Try typing an erroneous statement such as return "Ten" and
observe what happens.

Q. What is wrong with the latter
return statement?

Load simple rules for both axes, and start the Etch-a-sketch. Can you make
the dot go to position (10, 20)?

Using the Etch-a-sketch

At this point you should be ready to write your own code to control
the Etch-a-sketch. Try to write code that will produce interesting
patterns, and see if you can predict ahead of time what the results of
your code will be. To use the Etch-a-sketch, make sure you have
loaded your code, and compiled it successfully. Then, press the
"Start" button on the Etch-a-sketch window, and watch the dot move.
You may stop the dot by pressing the "Stop" button. The "Reset"
button allows you to do such things as clear the lines drawn by the
Etch-a-sketch, and/or put the ball back in the center.

Try the exercises labeled Qfrom the
prelab. Can you make an asterisk?

Using the Horizontal and Vertical Rules

The tabbed panes allow you to select which recipe you are
currently working on. In the lower right corner of the Controls
window is a label that indicates whether the displayed recipe is
being used as the Vertical rule, the Horizontal rule, Both rules, or
not used at all. Under the Recipe menu are a pair of
check-boxes that control how the current recipe is used. The "New
Recipe" button creates a new pane for entering a recipe. You are
still limited to only one recipe being used for each of the
horizontal or vertical rules.

Complete the static positioning exercises from the prelab. How do
your lab experiences compare to the predictions you made? Make notes
for your post-lab writeup.

Using Names in Your Code

System-Provided Names (Parameters)

In your code, you may make use of the following names, which are of
type double:

pos - contains the position of the dot along the axis
where this rule applies.

vel - contains the velocity of the dot along the axis
where this rule applies.

otherPos - contains the position of the dot along the other
(perpendicular) axis.

otherVel - contains the velocity of the dot along the
axis.

maxPos - contains the maximum and minimum allowable positions for the
dot along the axis where this rule applies. +maxPos represents
the rightmost (or topmost) edge of the Etch-a-sketch, and -maxPos
represents the leftmost (or bottommost) edge of the Etch-a-sketch.

For example, if a rule is being used as the horizontal rule, then
pos would return its x coordinate, and vel
would return its velocity in the x direction. You can use
these names to return values that depend on your position. However,
you cannot change these values; these names are pre-assigned values
each time that your recipe is called.

These names, as well as other features, are all documented, with an
example, under the Help menu of the Controls window.

Complete the Implementing Velocity exercises from the prelab.
Remember that vel and otherVel are always 0 in position mode, so these
names cannot be used to solve these exercises.

Temporary Storage Names (Variables)

You can also create your own names by declaring them in your code. These
names can be used to hold values throughout a single application of a rule.
The next time the rule is applied, however, the values of these variables are
lost. These types of names (also called variables or local
variables) are useful for providing temporary storage during
computations.

e.g., double nextPos; nextPos = pos * 2; return nextPos;

Long-Term Storage Names (Fields)

Etch-a-sketch also allows you to create names whose values are
preserved across different applications of a rule. These are called
fields. To edit the fields associated with a recipe, click on
the "Add Fields" button. Another small text area should appear in the
Code Editing window. You can declare and/or define fields there. (If
your window gets messed-up, just resize it by dragging a side or
corner of the window, and it should fix itself.) Note that you can
initialize a field by using a definition (a declaration combined with
an assignment). In general, it is considered good practice to
initialize your fields to a reasonable initial value.

Example:

Fields: int myInt = 5;

Rule: myInt = myInt + 1; return myInt;

Q Can you predict what this code would
do? Think about it first, then try it. Include your prediction and
the actual result in your writeup.

Now implement basic acceleration as in the prelab. This is the target
stage of your lab and, once you have completed that step, further work
is required only as it interests you. Of course, there are still many
cool aspects of this tool to explore.

Using the Advanced Environment Options

The Etch-a-sketch has several Advanced Environment Options. You can
ignore this section, as it does not contain anything you need to know
for lab. If you want to investigate further, though, some of these
options do neat things.

Wall Properties

You can enable or disable certain properties of the Etch-a-sketch window's
edge.

When bouncing is turned on, a dot "hitting" a wall (i.e., going beyond
the boundaries of the Etch-a-sketch) will be sent back with its velocity
negated.

When wraparound is turned on, a dot "hitting" a wall will "wraparound"
to the other side of the window and continue moving with the same
velocity. Wraparound mode cannot be used together with bouncing or
circular mode.

By default, none of these is turned on. In this case, a dot
hitting a wall be stopped by the wall (i.e., it will not be allowed to
have coordinates outside the interval (-maxpos,+maxpos), but it
does not wraparound and its velocity is unchanged).

Control Mode

You can select whether the values returned by the rules are used to
determine position, velocity, or acceleration. Note the following:

Selecting Position control will set the velocity, and acceleration of
the ball to 0. (However, this does not mean that you cannot implement
velocity and acceleration by using the rules themselves to move the
ball.

Selecting Velocity control will set the acceleration to 0. (Again it
does not mean that you cannot implement acceleration.)

In order to keep the ball from flying off the screen, there is an
imposed "speed limit" of 60. If the ball is in velocity or acceleration
control mode, and the velocity exceeds the speed limit, then its velocity
will be automatically adjusted to a level below the limit.

By default, Etch-a-sketch starts in Position control mode.

Delay

These entry boxes allow you to set the speed of the Etch-a-Sketch
simulation. Move the slide or enter a value on the right for the new
delay. Remember that a lower delay means the adjusted subsystem will
run faster.

Managing Your Code

Etch-a-sketch does not have explicit File management features.
Thus, to save your work, you must copy and paste the recipe code from
Etch-a-Sketch into a text editor of some sort. Emacs, Notepad, and
CodeWarrior will all work. Due to the lack of an Edit menu on
the Controls window, you should use C-x to cut, C-c
to copy, and C-v to paste.

Before you leave

Before you leave lab, you will need to have your code checked off by a
course staff member. You should allow time for an adequate demonstration and
discussion of what you have done. Please do not wait until the last minute to
be checked off.

Post-Lab, AKA What
To Turn In

Your completed assignment should include:

on the front page, how much out-of-class time (approximately)
you've spent on reading, on preparation of the homework, in lab, and
on other non-class-time course-related activities (and what).
These times should include work from last Wednesday 5pm to this
Wednesday at 5pm

a brief description of your expectations before coming to lab. (This
may be a version of your notes for check-in.)

a discussion of how you spent your time in lab.

your observations concerning

what actually happened.

how this compares with what you expected prior to lab.

any interesting behaviors you may have developed.

a brief description of the check-off interaction, who checked out your laboratory
work, and answers to any specific issues s/he may have asked you to
address.

the names and roles of any collaborators in any parts of the project.

also note the following:

How long did this lab take you?

Did you work with other students? If so, how helpful was it?

Did you have problems writing code for this lab?

Did you have problems running/using this lab?

Do you like the clicker, or do you feel it's just a waste of
class time? Please select your answer from "Yes/Agree/A",
"No/Disagree/B", "C", "D", "Huh?", or "Cheese Rules!".

The complete lab writeup should not be more than 2 pages of
English text, though it may actually be longer if you include
significant notes not formatted as prose. You may wish to summarize
your lab writeup in prose and then simply append any raw notes to
this.

Lab assignments are due on Wednesdays at 5pm in AC312. They
may, of course, be turned in earlier.