Computer Science 120
Introduction to Programming

Spring 2012, Siena College

Lab 1: Laundry Sorting Simulator
Due: the start of your next lab session

For our first regular lab assignment, you will work through some practice exercises using conditionals and random numbers, then use these techniques and other things we have seen in class to build a simple "laundry sorting simulator".

You may work alone or with a partner on this lab.

Getting Set Up

Follow these steps to get your BlueJ environment set up for this week's lab assignment.

  1. Create a folder in which you will develop your programs for this lab. A good name might be "Lab1". Avoid spaces in this name.
  2. Start BlueJ and choose "New Project" from the "Project" menu. Navigate to your folder for this lab and choose a name for the project. "Lab1" would work again.

Working with Conditionals

Write a Java program that draws a medium-sized FilledRect on the canvas and which implements the following behaviors:

A working solution for this part will appear below. Click inside the applet to interact with it.



To create the Java source file for this program:

  1. Click the "New Class..." button in your BlueJ project for this lab.
  2. Enter "MovingRect" as the "Class Name" and make sure the "Class Type" is selected as "Class" and Click OK.
  3. Double click on the new "MovingRect" object in the main BlueJ window to open the file in the editor. You will see that BlueJ fills in the skeleton of a class. You will need to remove most of it and add some other things:
    1. Add the standard import statements we use for objectdraw programs at the top:
      import objectdraw.*;
      import java.awt.*;
      
    2. Modify the class comment to include a description of this program and to have your name(s) and assignment information.
    3. Add "extends WindowController" after "public class MovingRect".
    4. Delete everything inside the class and replace it with your own instance variables and methods (e.g., begin, onMousePress, etc.).

Develop your program one step at a time. First, have your program draw the rectangle, compiling and testing as you add statements. Then make it change color when the mouse moves, again testing this and getting it to work before moving on. Then, add the movements when the mouse is pressed.

One thing you will need that we have not yet covered in detail in class is the if .. else statement. We saw if statements which look like this:

  if (condition) {
     // do this stuff
  }

When the "condition" is true, we do the things in the body of the if statement. However, we often need to do one thing if the condition is true then something else if the condition is false. Here, we need something of the form:

  if (condition) {
     // stuff to do when condition is true
  }
  else {
     // stuff to do when condition is false
  }

Working with Random Numbers

Write a Java program that draws a square or a circle on the canvas each time the mouse is pressed. The program should choose randomly one of a FilledRect, FilledOval, FramedRect, or FramedOval to draw with its upper left corner at the location of the mouse press. When the mouse exits the canvas, all shapes drawn should be removed.

A working solution for this part will appear below. Click inside the applet to interact with it.



To get started, add a "New Class" to your BlueJ project and create a class called RandomShapes. Follow the same procedure as above to prepare this source file to be used for an objectdraw program.

Objectdraw provides a very convenient way to generate random integer values. We can construct a RandomIntGenerator object, giving it the range of values we would like it to generate. In our case, we'll create one that can generate numbers in the range 1 through 4, and save it in an instance variable:

    private RandomIntGenerator pickAShape = new RandomIntGenerator(1, 4);

We can then call the method nextValue of our RandomIntGenerator to get a randomly-generated value of 1, 2, 3, or 4, and save it in a variable.

    int nextShape = pickAShape.nextValue();

This is a local variable, a name we introduce to Java for use only within a method. In this case, since it's already "private" to the method in which we declare it, we omit the "private" that we need to use in front of our instance variables.

Then, pick the shape based on the number generated (i.e., make the shape be a FilledRect if the number is 1, a FilledOval if the number is 2, etc.) using a conditional.

    if (nextShape == 1) {
        new FilledRect(.....);
    } else if (nextShape == 2) {
        new FilledOval(.....);
    } else if (nextShape == 3) {
        new FramedRect(.....);
    } else {
        new FramedOval(.....);
    }

Laundry Sorting Simulator

Your task here is to write a laundry sorting simulator to aid next year's freshmen class in learning how to sort their laundry into "whites", "darks", and "colors". You are to develop this simulator in a new class in your project for this lab, called Laundry.

Design

Before you do any coding, read through this section in its entirety to make sure you fully understand what you are being asked to do.

Prepare a handwritten design for your program. In order to facilitate this step, a design template is provided below. You may use this template to help you organize your ideas for the program. When designing a program, you should think about its behavior in general, the instance variables you will need to store information, and the event-handling methods you will need to implement the program's behavior properly.

As part of the design, you should also draw the layout for your graphical objects on the screen with important positions and object sizes defined as named constants.

Get your design approved (and graded) by your instructor before you start doing any coding in BlueJ for this part.

To give you an idea about the expectations for what to include in a design document (which will be a pre-lab task for many of our lab assignments), here are a couple of designs that could have been used for Dr. Teresco's "SunAndMoon" example (modified to use some appropriate named constants) and Dr. Small's "ClassPlay" example. A good design would also include a simple drawing showing the initial placement of the objects in the scene, labelled with key coordinates.

public class SunAndMoon extends WindowController {

    private FilledRect field;        // lower 1/3rd of window
    private FilledRect sky;          // top 2/3rds of window
    private FilledOval heavenlyBody; // the sun or the moon

    // constants to use in scene layout
    private static final int HORIZON_Y = 260;
    private static final int ORB_DIAMETER = 80;
    private static final double RISE_OR_SET_SPEED = 1.5

    /* Create the sky, field and orb and set their colors */
    public void begin() {
        // create sky (FilledRect), field (FilledRect),
        //  heavenlyBody (FilledOval)
        // set colors to "daytime colors"
    }

    /* Make it look like night by using black, white and gray */
    public void onMousePress(Location point) {
       // set sky, field, heavenlyBody colors to "nighttime colors"
    }

    /* Make it look like a bright sunny day */
    public void onMouseRelease(Location point) {
       // set sky, field, heavenlyBody colors to "daytime colors"
    }

    /* Move the sun-like circle down a little bit */
    public void onMouseMove(Location point) {
       // move heavenlyBody down by one unit
    }

    /* Move the moon-like circle up a bit */
    public void onMouseDrag(Location point) {
       // move heavenlyBody up by one unit
    }
}
public class ClassPlay extends WindowController
{

  private FilledRect myFilledRect1;    //UPPER LEFT RECTANGLE
  private FilledRect myFilledRect2;    //MIDDLE LOWER RECTANGLE
  private FilledRect myFilledRect3;            //UPPER RIGHT RECTANGLE


  public void begin(){
     //CREATE THE ACTUAL INSTANCES OF THESE THREE NEW RECTANGLE OBJECTS


  }

  public void onMouseClick(Location point){
      //CHANGE myFilledRect1 TO GREEN WHEN THE MOUSE IS CLICKED
  }

  public void onMouseDrag(Location point){
      //CHANGE myFilledRect3 TO RED WHEN THE MOUSE IS DRAGGED
  }

  public void onMouseRelease(Location point){
      //CHANGE myFilledRect2 TO myColor WHEN THE MOUSE IS RELEASED
  }

  public void onMouseEnter(Location point){
     //RESET ALL RECTS BACK TO BLACK WHEN THE MOUSE ENTERS THE CANVAS
  }
}

Program Description

The simulator should begin with three wash baskets on the screen and the item to be sorted, or the "swatch" (a sample piece of fabric). For our purposes, the baskets will simply be squares, and they will be labeled "whites", "darks", and "colors."

A working solution for the simulator will appear below. Click inside the applet to interact with it.



When the program starts, a color swatch will appear on the screen. The user ("laundry trainee") should then click on the basket corresponding to the color of the swatch. If the user clicks on the correct basket, the program should randomly select a new color for the next item and display it on the screen. For this part of the assignment, you should select among the three colors Color.white, Color.red, and Color.black when creating swatches. If the user clicks on an incorrect basket, the original item remains in position for another try.

Warning: because swatch selection is random, it sometimes picks the same color twice in a row. When this happens and you click on the correct basket for the first item, you will get the feeling that the program did not do anything. Even though it has actually displayed a new item, the new item looks identical to the old one, so you may think nothing happened. Don't let this trick you into thinking that your version of the program (or the demo above) isn't working correctly.

You will need to design an extension of the WindowController class which will display the wash baskets and the item to be sorted. Begin by laying out where all the items go on paper. The default canvas dimensions - 400x400 - should work well. The picture should look like what you see when you run the demo, but with the coordinates labeling where the baskets, text and swatch will go.

When the program begins, draw all the wash baskets (with labels) on the screen. Then draw the item of clothing that is to be sorted. For simplicity, you may always make the first item have color red. The item should actually consist of two rectangles, a FilledRect which is the appropriate color and a FramedRect which is the same size, but lays on top of the filled rectangle to form a border. (Otherwise it will be awfully difficult to see a white item!)

Think Constants

Use constants (private static final CONSTANT_NAME) for all the relevant location and size information. This makes it easier to change the layout and also makes your program much, much easier to read (presuming you give constants good names). Constant names are by convention written with all capital letters and underscores, e.g. THIS_IS_A_CONSTANT.

      private static final int SWATCH_X = 150;

You may declare Location constants as well by initializing the constant variable with the results of a constructor:

      private static final Location SOME_LOCN = new Location(100,200);

However, you cannot initialize constants whose definition uses canvas (e.g., no FramedRect constants), since Java does not yet know about the canvas when it is initializing the constants.

The widths and heights of wash baskets and the item to be sorted, coordinates of the upper left corner of each of these, etc., are all good candidates for constants.

Note that the constructors for our graphics objects can take a Location object to specify its upper left corner instead of separate numbers for x and y, in cases where that is more convenient, e.g.:

  new FilledRect(SOME_LOCN, WIDTH, HEIGHT, canvas);

After writing the code to draw the baskets and item to be sorted, run the program to see if it does what you expect.

Identifying the Correct Basket

Once you have done the layout, you should next figure out how to generate new items. (Generating the random color is discussed below.) Because you will initially be generating the item in one method (begin) and checking to see if the user clicked in the appropriate basket in a different method (the onMouseClick method), you will need to associate some information with an instance variable that will enable onMouseClick to determine which is the correct basket.

An appropriate way to do this is to use an instance variable of type FramedRect that stores the basket in which the user should click. When you generate a new item (either initially in begin or thereafter in onMouseClick), you will associate the instance variable with the rectangle/basket in which an item of the swatch's should be placed. That way, to determine if the user clicks on the correct basket, onMouseClick can simply check to see if the rectangle currently associated with the instance variable contains the point where the mouse was clicked. Then, onMouseClick will either select a new color for the item (if the user was correct) or wait until the user clicks again (if incorrect).

Picking a random color

To pick a random color, use the RandomIntGenerator class as described in the textbook. Since there are three colors to select from, you should create your random number generator to return random numbers in the range of 1 to 3. Then, pick the color based on the number generated (ie., make the laundry be Color.white if the number is 1, Color.black if the number is 2, and Color.red if the number is 3).

Recycling

Because your program only uses one laundry item at a time, you can (and should!) reuse the same rectangle for each new laundry item by simply changing its color rather than creating a new rectangle. In general, it is a good strategy to reuse objects when possible rather than creating new ones because it uses less memory and makes the code more clear.

Submitting Your Work

Before the start of your next lab session, submit your Java programs for grading. There are three things you need to do to complete the submission: (i) place a copy of your Java programs into your csis120/hw folder under hw2, (ii) print a copy of each of your programs and hand it to your lab instructor, and (iii) demonstrate the execution of your programs for your instructor.

Grading

This assignment is worth 100 points, which are distributed as follows:

> FeatureValueScore
MovingRect
Correctness 10
Appropriate comments 5
Good variable names 3
Appropriate formatting 2
RandomShapes
Correctness 10
Appropriate comments 5
Good variable names 3
Appropriate formatting 2
Laundry
Design document, including labelled sketch 10
Initial layout of simulator 7
Generate random swatch colors 10
Generate new color only on correct placement of previous 10
Appropriate comments 10
Good variable names 5
Good use of constants 5
Appropriate formatting 3
Total 100