CS U231 Fall 2004 and CS U232 Spring 2005

http://www.ccs.neu.edu/jpt/fhs-04-05/

This site contains materials from both semesters of the freshman honors seminar CS U231 and CS U232 in 2004-2005.

In Java Power Tools 2.4.0, the interface MutatablePaintable was merged into the base interface Paintable and the wrapper class MutatableWrapper was renamed Tile. Because of these changes, some code on this site will need to be revised in order to work with Java Power Tools 2.4.0.

For convenience, the prior release of JPT, 2.3.5, may be found in the archives:

JPT Archive

Links

September 14, 2004

September 21, 2004

September 24, 2004

September 28, 2004

October 12, 2004

October 16, 2004

November 16, 2004

November 17, 2004

December 13, 2004

January 17, 2005

January 27, 2005

February 10, 2005

March 17, 2005

March 25, 2005

Down to the Bottom

September 14, 2004

The plan or syllabus for the course as a Word document or PDF document.

Access to the Java Power Tools.

The main site: http://www.ccs.neu.edu/jpt/

The JPT 2.3.5 site: http://www.ccs.neu.edu/jpt/jpt_2_3/

The JPT 2.3.5 library file jpt.jar: http://www.ccs.neu.edu/jpt/jpt_2_3/lib/jpt.jar

The JPT 2.3.5 javadocs: http://www.ccs.neu.edu/jpt/jpt_2_3/docs/

The JPT 2.3.5 annotated source code: http://www.ccs.neu.edu/jpt/jpt_2_3/src/

Back to the Top

Down to the Bottom

September 21, 2004

The Cascading Style Sheet

The cascading style sheet for this web site: fhs.css

The JPF_Sample_01 Project

The project JPF_Sample_01 illustrates three simple uses of the Java Power Framework:

A method evaluate that evaluates a double precision number in an automatically generated GUI.

A method evaluate_in_console that evaluates a double precision number in the console window.

A method evaluate_many_in_console that evaluates one or more double precision numbers in the console window using a loop that is terminated if the user presses return on an empty line.

The files for the project JPF_Sample_01 are available at:

The Java source Methods.java

The Metrowerks project JavaPowerFrame.mcp

The bundled source and project in zip format

The bundled source and project in self-extracting exe format

Back to the Top

Down to the Bottom

The Picture Pages Project

The project Picture Pages illustrates the use of Java to generate html files for displaying a web site of digital pictures. Since one can examine the web site and the html files that were generated to build this site, it is possible to map the Java code to what it produces in a very direct manner. This allows you to understand Java topics such as member data, methods, building text strings in an incremental fashion, reading a directory to obtain a list of its existing image files, and building a corresponding set of html files to manage the web site.

Note:Subsequent to posting this information, improvements were made that are posted below as the Better Pages Project. The original code is being left on this site to allow a before-after comparison. Since I did not want two copies of the site on-line, the link below now shows the newer form of the site. The code immediately below is, however, the original posted Java code.

The sample web site is Oregon 2004.

The files for the project Picture Pages are available at:

The Java source PicturePages.java

The Metrowerks project PicturePages.mcp

The cascading style sheet pictures_style.css

The bundled source, project, and style sheet in zip format

The bundled source, project, and style sheet in self-extracting exe format

Back to the Top

Down to the Bottom

Reading Assignments

Below are the guidelines for intensely reading the Java code and web code for the PicturePages program as well as the web code for this site.

The reading assignment guidlines as a Word document or PDF document.

Back to the Top

Down to the Bottom

September 24, 2004

The Better Picture Pages Project

The project Better Picture Pages improves on the Picture Pages project introduced above. The key improvement is that the program automatically copies the standard style sheet into the folder with the images and generated html files. This avoids the need to do this file copy manually.

Other improvements include placing the page title in the page window as well as in the window title bar and doing a better job of extracting a useful picture caption from an image file name. The program now also supports reading png files in addition to jpg and gif files. A few cosmetic adjustments make the automatically generated html files easier for people to read.

The sample web site is Oregon 2004.

The files for the project Better Picture Pages are available at:

The Java source PicturePages.java

The Metrowerks project PicturePages.mcp

The cascading style sheet pictures_style.css

The bundled source, project, and style sheet in zip format

The bundled source, project, and style sheet in self-extracting exe format

Back to the Top

Down to the Bottom

September 28, 2004

The Guessing Game Project

In the Guessing Game, the user is asked to guess a number chosen randomly by the program. The user can control the range from which this value is chosen via the initial Make Game window:

When the user clicks on one the options in this window, a new game is initiated with the desired range. The Guessing Game window shows the state of the game and manages the user input of a new guess.

The snapshot above shows a game that began with a range from 1 to 1000000 and now is ready for the third guess by the user.

In the Make Game window, the user can request that the range be selected randomly or can choose to input a precise initial range interactively. The latter is done in the input window for a User Defined Range.

As the Guessing Game proceeds, the range remaining is updated automatically based on whether the user guess was too low, too high, or absolutely correct. In this way, the user is always forced to make a valid guess based on the information learned during the game.

To satisfy an impatient user, the Reveal Answer button will give away the answer with no further ado.

The files for the project Guessing Game are available at:

The Java source GuessingGameTester.java

The Metrowerks project GuessingGame.mcp

The bundled source and project in zip format

The bundled source and project in self-extracting exe format

Back to the Top

Down to the Bottom

October 12, 2004

Tic Tac Toe

This project implements the Tic Tac Toe game.

The first screen snapshot shows a game in which X wins.

The next screen snapshot shows the dialog box that announces X as the winner.

The third screen snapshot shows a game that ends in a tie.

The next screen snapshot shows the dialog box that announces the tie.

The files for the project Tic Tac Toe are available at:

The Java source TicTacToeTester.java

The Metrowerks project TicTacToe.mcp

The bundled source and project in zip format

The bundled source and project in self-extracting exe format

Back to the Top

Down to the Bottom

October 16, 2004

Concentration

This project implements the Concentration game. In this game, the user clicks on a pair of tiles. The images (photos, shapes, letters, or numbers) that are hidden within the tiles are made visible. If the images match, the tiles remain visible on the next move. If not, the tiles are once again hidden. The object of the game is to make all tiles visible by matching all pairs in the minimum number of moves. For the impatient user, a button to reveal all images is provided. This button was also quite useful in testing the game.

The first screen snapshot shows a game with photos.

The next screen snapshot shows a game with shapes.

The final screen snapshot shows the dialog that allows the user to choose the images and to decide on the size of the game board.

Notice that in addition to photos and shapes, the game also permits the option of letters of the alphabet from A to Z and numbers from 0 to 99.

The files for the project Concentration are available at:

The Java source ConcentrationTester.java

The Java source ConcentrationGame.java

The Java source ImageTile.java

The Java source ImageTools.java

The Java source GameShapes.java

The Java source ProbStatTools.java

The Metrowerks project Concentration.mcp

The bundled source, project, and photo images in zip format

The bundled source, project, and photo images in exe format

The directory of photo images alone in zip format

The directory of photo images alone in exe format

The images should be placed in a sub-directory /Images of the directory from which the Java application is launched. You may add or replace images but keep in mind that the game assumes that the images have size 100 by 100. Furthermore, in a 6 by 6 game, there should be 18 or more distinct images or else image pairs will be repeated.

Subsequent to the posting of Concentration on this site, further development of the program took place including the option to run Concentration as an applet from the web rather than as a stand-alone Java application. For this code and access to the applet, see the Concentration area on the main JPT site:

http://www.ccs.neu.edu/jpt/jpt_2_3/concentration/

Back to the Top

Down to the Bottom

November 16, 2004

BitDisplay and BitDisplayTester

The class BitDisplay is a class wired to display bits as black (1) and white (0) paint swatches. The code as presented here is incomplete since the following methods are unfinished:

    public void setBitsFromInteger(int value) {
        // to do
    }
    
    public int getIntegerFromBits() {
        // to do
        return 0;
    }

The class BitDisplayTester is a class wired to test the class BitDisplay. It brings up a frame as follows:

One can verify that the BitDisplay object responds to mouse clicks since each time a swatch is clicked the swatch changes color and the click count is updated in the tester frame. However, the link to the text view does not work properly since the methods mentioned above do not yet work.

As soon as setBitsFromInteger is working, you will see that when an integer is typed into the view and return is pressed then the bits will be updated to match the integer.

As soon as getIntegerFromBits is working, you will see that when a swatch is clicked then the corresponding integer will be displayed in the view. At the moment, since the code is not correct, when a swatch is clicked then zero is displayed in the view no matter what bit pattern is present. This is because of the incorrect return 0 code in the method.

The two classes BitDisplay and BitDisplayTester are found in a Java Power Framework test file Methods.java.

Some experiments:

Complete the two methods above and test that they work using the given tester code.

Using the two methods above, create corresponding methods to work with the bits for float data. See the Java class Float for important helper methods.

Extend the tester code to experiment with float data. Indeed, it would be interesting to have two text views so that both the integer interpretation and float interpretation of the same bits are visible simultaneously. A tricky question in the design is how to continue to guarantee than when one item is modified (a swatch, the integer view, or the float view) then the other two items update automatically. You must design the actions in a clever fashion.

Think about how to extend things for long and double.

Aside from the specific things you can learn about bits, ints, and floats, this code more generally illustrates how to build graphics views that respond to the mouse and that interact with other views such as text fields and annotations. You may want to use the ideas in code for other purposes.

Back to the Top

Down to the Bottom

November 17, 2004

Timer Sample

Today I was working with a student who wanted to be able to use a timer so that access to some object in a GUI such as a text field would only be available while a timer was running. For example, the user might be permitted to type into the text field just for the duration of the timer. The default timer duration would be 60 seconds but this value could be changed in the constructor or, perhaps, by calling a method. No changes to the timer behavior would be permitted while the timer was executing. It would be possible for some other part of the program to force the timer to stop if the timed activity was completed early by the user.

Here is a screen snapshot of the test timer. When the Count Down button is clicked, the timer starts. During the time when the timer is executing, the user may type into the text field. This is how the text Hello World was entered. As you can see from the snapshot, the timer had 3 seconds left when the snapshot was taken. When the timer runs out, the text field is no longer editable by the user. The demo is set up so that the timer may be restarted multiple times but if it is restarted while it is already running then the new invocation exits immediately and does nothing.

The class TimerSample may be found in the Java Power Framework test file Methods.java.

Back to the Top

Down to the Bottom

December 13, 2004

Useful Image Files

Today I have posted some image files that may be useful for some students in their final projects for the term. These images include public-domain playing cards, dice, coins, and images for a rock-paper-scissors project that one pair of students is working on.

The main directory for all images is:

http://www.ccs.neu.edu/jpt/images/

In each subdirectly, a file imagelist.txt has been provided so that the images may be read with the tools used in the Concentration game program.

Public-domain playing cards

Using Google, I have located two sets of playing cards that may be freely used. In a copy of each card deck on the JPT site, I have set up the file imagelist.txt so that the 52 cards are organized by suit in the order hearts, diamonds, spades, clubs. Within each suit, the order is Ace, 2, 3, ..., Jack, Queen, King. These cards will load as images 0, ..., 51. After these 52 cards, there are one or two card backs and jokers.

The GNU Playing Cards

This card deck was downloaded from the site:

http://www.waste.org/~oxymoron/cards/

The URL of this card deck on the JPT site is:

http://www.ccs.neu.edu/jpt/images/gnu_cards/

The image list file is: imagelist.txt

In the GNU deck, image 52 is a card back and image 53 is a joker.

The JFitz Playing Cards

This card deck was downloaded from the site:

http://www.jfitz.com/cards/

The URL of this card deck on the JPT site is:

http://www.ccs.neu.edu/jpt/images/jfitz_cards/

The image list file is: imagelist.txt

In the JFitz deck, image 52 is a blue card back, image 53 is a red card back, image 54 is a black joker, and image 55 is a red joker.

Dice

These 6 images of the 6 faces of one die were scanned from an old die I had about the house. Interestingly, the imperfections on each die face add to the realism of the images.

The URL of the dice images on the JPT site is:

http://www.ccs.neu.edu/jpt/images/dice/

The image list file is: imagelist.txt

Coins

This area provides scanned images of the heads and tails of a US quarter. The files with 100 in their name use 100-by-100 images and the files with 200 in their name use 200-by-200 images. In my opinion, the 200-by-200 images are much clearer than the 100-by-100 images and should be used if you have sufficient room in your GUI for images of this size.

The URL of the coin images on the JPT site is:

http://www.ccs.neu.edu/jpt/images/coins/

The image list file is: imagelist.txt

Rock-Paper-Scissors

These images are provided for a pair of students who are working on a rock-paper-scissors game. Once again, I have provided both 100-by-100 and 200-by-200 versions.

The URL of the rock-paper-scissors images on the JPT site is:

http://www.ccs.neu.edu/jpt/images/rps/

The image list file is: imagelist.txt

Back to the Top

Down to the Bottom

January 17, 2005

Image Viewers

Many of the image classes developed during the Fall semester of this course were enhanced and then included in the Java Power Tools. In particular, there are now two image viewers that permit you to see the images in a local directory or the images in a web directory. Here are screen snapshots of the GUI interfaces to these viewers.

The CardFun Example

In the class meeting of January 13, 2005, an example class was built live to illustrate the more fundamental image tools added to JPT including ImagePaintableLite. This class, named CardFun shows a hand of 5 playing cards chosen randomly from a standard 52 card deck. Here is a screen shapshot of a sample frame from this demo.

The CardFun example does not do anything other than show the card images but its code may be adapted to purposes you may have in your own projects. Therefore have fun with CardFun.

Java Source

The JPF test class:

Methods.java

A stand-alone class to bring up the image viewers:

RequestViewers.java

The CardFun class that illustrates the image tools:

CardFun.java

For more information on the image tools, see the Annotated JPT Java Source Files.

Follow the links there:

edu.neu.ccs.gui

Graphics Classes

Image Tools

Back to the Top

Down to the Bottom

January 27, 2005

Variations of the CardFun Example

In the class meeting of January 13, 2005, an example class was built live to illustrate the more fundamental image tools added to JPT including ImagePaintableLite. This class, named CardFun shows a hand of 5 playing cards chosen randomly from a standard 52 card deck.

In the class meeting of January 20, 2005, I attempted variations on the CardFun example but, frankly, these did not work well. I ran into design snags and got trapped.

In advance of the class of January 27, 2005, I am posting variations that have been more carefully worked out. The aim is to be able to drag cards around the window using the mouse.

CardFun Variation 1

This variation defines a collection of shuffled cards as follows:

This variation permits the card sequence to be displayed in a panel that is larger than the bounds of the sequence. This sets the stage for mouse movement which is, however, left to the next variation.

The source code follows:

The JPF test class for Variation 1:

Methods.java

The CardFun class for Variation 1:

CardFun.java

CardFun Variation 2

This variation defines a collection of shuffled cards exactly as Variation 1.

Instead of inserting the sequence into the panel directly, the sequence is explicitly wrapped with a PaintableComponent. This makes explicit a step that is otherwise done automatically. The reason for this explicit step is to be able to access the MouseActionAdapter associated with the PaintableComponent.

The mouse behavior is then installed by adding mouse actions to the mouse action adapter. A tricky step is to realize the the natural coordinates of the component are not identical to those of the paintable sequence since a component always starts with (0, 0) as its upper-left corner. The mouse code therefore adjusts for this. To make the issues clear, a little panel is added to the display to track the mouse. This panel serves no other purpose than to provide feedback about the adjusted mouse coordinates.

The source code follows:

The JPF test class for Variation 2:

Methods.java

The CardFun class for Variation 2:

CardFun.java

A screen snapshot of a test of Variation 2.

These two variations establish the user interface code for working with a deck of cards. However, more abstract issues such as defining classes for Card, Deck, Suit, and Rank, and for handling cards being dealt sequentially over time are not yet addressed in these variations. These require more design and programming effort.

Back to the Top

Down to the Bottom

February 10, 2005

Experiments with Tracking Ball Motion

This week I had two visits from a student who wanted to show the motion of a projectile under gravity. At first, this seemed simple enough, in particular, if we simplified the projectile shape to be a circle. On further examination, however, there were some real issues.

The problem arises because as a programmer you really want to think in a coordinate system that suits mathematics, that is, with the origin (0, 0) at the lower left and with y increasing as you move upward. This goal conflicts with the standards of computer graphics that place the origin (0, 0) at the upper left and with y increasing as you move downward.

I began to stumble around with various approaches to the change of coordinates from the computer graphics world to the world of mathematics. Part of the source of confusion came from the fact that there were two objects in play:

I showed the student how to set up a Java AffineTransform object to represent the flip of the coordinates that swaps the upper left, (0, 0), with the lower left, (400, 0), and reverses the direction-of-y. This was an annoying bit of technical stuff that I would have preferred to avoid. Later, I will explain how to in fact avoid this transform object.

The immediate question was: To what object should the transform be applied? ... to the ball or to the graphics context object?

I first applied the transform to the ball. This succeeded in moving the ball from the upper left corner to the lower right corner. Unfortunately, by applying the transform to the ball, the direction-of-y did not reverse in general. If I used the move method on the ball, it merrily moved downward off of the screen.

The next attempt was to apply the transform to the graphics context, that is, change the entire way that the context thinks of how to plot graphics. This worked beautifully for the ball. The six ball images moved upward and to the right very nicely.

I was suspicious however. I decided to plot a character string, Graphics Sample, at (200, 300) in the window. What I got is shown in the snapshot below.

This is clearly a disaster. By applying the transform to the graphics context everything is plotted upside down!!!!! This is surely not what we want.

Before I go further, here is the bad code: Methods.java.

It took a long while to figure out what was wrong. The heart of the answer is that the transform should not be applied to either the ball or the graphics context but rather to the mathematical coordinate position at which you want the ball ... or the string to be painted.

In a way, a narrow focus on the objects I could see, the ball and the graphics context, made me miss the fact that there is a third object in play, namely, the point at which the ball is to be painted. Because the point was unnamed, it was unnoticed.

The key is to leave both the ball and the graphics context alone and transform the point. Of course, it is then necessary to have methods for painting that explicitly mention the plot point.

The next snapshot shows the result of this strategy which is clearly successful. The balls are plotted in the sequence planned in the code and the text string is right side up in the right spot.

Here is the correct code: Methods.java.

Let's look at some code extracts.

First, I decided to get rid of the affine transform and write a simple flip method to flip the coordinates. Although I only need the window height here, I extract the window width as well for later use.

    // window dimensions
    
    int width = window.getWidth();
    int height = window.getHeight();
    
    // direct transform to flip coordinates
    
    Point2D flip(Point2D point) {
        if (point == null)
            point = new Point2D.Double(0, 0);
        
        double x = point.getX();
        double y = point.getY();
        
        return new Point2D.Double(x, height - y);
    }

This code accepts a Point2D object whose coordinates are to be flipped vertically but not horizontally. The height of the window is represented by a variable of that name. In the specific example, the height is 400. Thus, in this case, the transform is:

    (x, y) ---> (x, 400 - y)

The next step was to write the code to paint a Paintable at a given point in a graphics context. Here I do not do any flip. I want the pure code first.

    // paint a paintable at x, y
    // without needing a mutatable wrapper
    
    void paintAt
        (Graphics g, Paintable p, double x, double y)
    {
        if ((g == null) || (p == null))
            return;
        
        Graphics2D h = (Graphics2D) g;
        
        h.translate( x,  y);
        p.paint(h);
        h.translate(-x, -y);
    }
    
    
    // paint a paintable at a point
    // without needing a mutatable wrapper
    
    void paintAt
        (Graphics g, Paintable p, Point2D point)
    {
        if (point == null)
            return;
        
        paintAt(g, p, point.getX(), point.getY());
    }

Notice that I give 2 versions, one with the point expressed as a Point2D object and one with the point expressed in coordinates. This is a useful practice: one method express the object view and one method provides a convenient coordinate view to make things simpler for the programmer.

It is then easy to provide parallel methods that introduce the flip.

    // flip the point and then paint the paintable
    
    void paintWithFlipAt
        (Graphics g, Paintable p, double x, double y)
    {
        Point2D point = new Point2D.Double(x, y);
        paintWithFlipAt(g, p, point);
    }
    
    
    // flip the point and then paint the paintable
    
    void paintWithFlipAt
        (Graphics g, Paintable p, Point2D point)
    {
        if (point == null)
            return;
        
        paintAt(g, p, flip(point));
    }

Here is how the code is used in the test.

    public void Ball()
    {
        window.clearPanel();
        Graphics2D g = window.getBufferGraphics();
        
        // set ball displacement
        // as  40 in x-direction
        // and 20 in y-direction
        
        int dx = 40;
        int dy = 20;
        
        // paint ball 6 times
        for (int i = 0; i <= 5; i++)
            paintWithFlipAt(g, sp, i*dx, i*dy);
        
        // locate text and line at
        // 1/2 of width  in x-direction
        // 3/4 of height in y-direction
         
        int x = width / 2;
        int y = (height * 3) / 4;
        
        paintWithFlipAt(g, tp, x, y);
        paintWithFlipAt(g, lp, x, y);
        
        
        window.repaint();
    }
}

The data objects are defined earlier in the code as Paintable member data with the red ball represented as sp, the blue text string represented as tp, and an extra cyan line represented as lp. You can look up these data definitions in the source.

The point is that the code is clean and can clearly be adapted to other problems. To summarize, if you want to apply a coordinate transform, apply it to the point at which you will paint and not to the object or the graphics context.

Back to the Top

Down to the Bottom

March 17, 2005

Card Sampler Applet

The Card Sampler applet displays cards one at a time from a card deck, prints the card rank and suit as a string, and marks in a table that the card has been selected. Once all cards have been displayed the deck is shuffled. The user can also shuffle at any time or force the deck into a standard order hearts, diamonds, spades, clubs, with the card rank from ace up to king.

The Java files:

Card.java

CardDeck.java

CardImages.java

CardSampler.java

CardSamplerApplet.java

CardTracker.java

The JPF test file:

Methods.java

Back to the Top

Down to the Bottom

March 25, 2005

Canvas Phrase Panel

Let’s start with a screen snapshot.

CanvasPhrasePanel sample image

The screen snapshot is 75% of full size. To see a full size version, click on the snapshot.

The idea of this demonstration program is create a GUI in which you can make text phrases in a desired font, font size, choice of italic or bold if desired, foreground color, and background color. The phrases are then previewed in the text view.

When you like the phrase, you may click “Make Phrase” or press return to drop the phrase into the graphics canvas. By default, the phrase is placed in the center of the canvas. Then, using the mouse, you may move the phrase to whatever position in the canvas you desire.

Note that, in this implementation, the background color of the phrase is not actually used. This is left to a “future” implementation.

The code illustrates:

The Java files:

The class to create and preview the text phrases:

PhraseMaker.java

The class that collects paintable objects and enables mouse dragging:

PaintableCanvas.java

A simple panel class that combines a canvas and a phrase maker:

CanvasPhrasePanel.java

The JPF test class:

Methods.java

The test class whose code was adapted to build the phrase maker:

FontSampler.java

A zip archive of all files:

PhraseMakerFiles.zip

Back to the Top