Lab 2
Etch-a-Sketch

Out September 8, due by 5pm, Thursday, September 15

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 continue to think about breaking problems down into interacting sup-parts.

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. If you did not collaborate with anyone, you must explicitly write no collaborators on your writeup.

This assignment emphasizes the following topics

You should read through this entire assignment and complete the Lab preparation sectionbefore you come to lab. Some portions of the post-lab writeup also require you to think about questions before and during the laboratory portion of the assignment.

This assignment is due at 5pm on Thursday, September 15th, 2005. You may turn in an electronic representation via sd-psets@lists.olin.edu or as a paper copy to Mike's mailbox on the third floor of Olin Center.

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 v and 4 a through e; Chapter 6 exercises 4 a through 8 (don't ask) and 5. Exercises are at the end of each chapter.

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

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....

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.)

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.

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, wil 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 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 names 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 Using Names and Advanced Environment sections 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

  1. Write Horizontal and Vertical rules that will place the ball in position (10, 20). Try other coordinates as well, including negative ones.
  2. Use the Horizontal rule for both rules. What do you expect would happen?
  3. 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.

  1. 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.
  2. 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.)
  3. What happens if the horizontal and vertical rules have different effective velocities? (How do you make this happen?)
  4. 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

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.

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


  2. Challenge: Can you make the dot bounce when it hits the end?

Other cool stuff

Using Velocity and Acceleration Controls

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.

  1. Play around with the velocity and acceleration-control mode. Play around with the bouncing edge mode too.
  2. Try the different position rules you wrote above (in particular, the static positioning, velocity, and acceleration)
  3. 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 created and typing your code into it.

Etch-a-Sketch has been packaged into a Java Web Start application. Java Web Start got installed when you installed Java 1.5 in Lab 1. To start Etch-a-Sketch, just click on the following link: start it!

The running program displays two windows. 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.)

If there are no syntax errors in your code, the phrase "<not compiled>" should become "<compiled>" underneath your recipe. Otherwise, error messages from the Java compiler will be displayed in the error console at Drawing->Error Console.... 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. Press the "Start" button with this bad code. (Be prepared to dismiss an error dialog and hit the "Stop" button.)

What is wrong with the latter return statement?

How is the behavior you just saw not like real java? Recall the styles of code execution we talked about in the first lecture. Can you guess what's going on behind the scenes?

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 Q from the prelab. Can you make an asterisk?

Keep making more arms on the asterisk until something odd happens. Can you explain the triangle shape?
HINT: There are actually three instruction followers operating in this program: one for the horizontal axis, one for the vertical axis, and one that paints the location of the point.

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:

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;

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 specified 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.

Control Mode

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

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:

Lab assignments are due on Thursday at 5pm at sd-psets@lists.olin.edu or Mike's mailbox on the third floor of Olin Center. They may, of course, be turned in earlier.