Freshman Honors Seminar
CS U231 Fall 2008
http://www.ccs.neu.edu/jpt/fhs/
Materials from previous years are at:
Links to Course Materials
Introductory Links
The plan or syllabus for the CCIS Freshman Honors Seminar as a PDF document.
Access to the Sun Java site
Access to the Eclipse site
At this site, choose “Eclipse IDE for Java Developers (85 MB)”.
Alternative: Access to Eclipse 3.2 for Windows (an older version that I like to use)
Access to the Java Power Tools
The JPT 2.7.0 annotated source and tutorial
The template methods class
Methods.java
for the Java Power Framework
The template methods applet class
MethodsApplet.java
for the Java Power Framework Applet
Setting up Eclipse with Java Power Tools
Note that the screen snapshots in the above instructions are for Eclipse 3.2 but the current version of Eclipse is quite similar.
Access to cascading style sheets
The main cascading style sheet for this web site:
fhs.css.
The screen cascading style sheet for this web site:
fhs_screen.css.
The applet cascading style sheet for this web site:
applet.css.
Back to Top.
Down to Bottom.
Introductory Links
Links to Course Materials
9/12/08: First Applet
9/14/08: First Sample Application
9/14/08: Homework #1
9/18/08 Tic Tac Toe
9/23/08: Homework #2
10/7/08 Tic Tac Toe Revisited
10/9/08 15 Puzzle
10/10/08 Homework 3: 15 Puzzle Enhancements
10/16/08 Homework 3: Comments
10/23/08 Playing Cards
11/15/08 Picking Cards
11/6/08 Homework 4: Blackjack
11/15/08 IntVector
10/30/08 Sketch #1
11/15/08 Sketch #2
11/6/08 Spinning Animation
11/18/08 Text Sample using Annotation
11/18/08 Text Sample using MultiLineTextPaintable
12/4/08 Parcheesi
Course Materials
9/12/08: First Applet
To execute the first applet, click on the snapshot below.
The applet source will be available from the applet page.
The applet extends JPFApplet which is a class
that automatically creates the graphical user interface (GUI)
that you see above and automatically defines the green buttons
that execute the simple public methods defined in the extending
class.
In particular, the one green button “Test” that you see is created based on the following simple method:
public void Test() {
Shape shape1 = new XRect(100, 100, 100, 50);
Paintable paintable1 =
new ShapePaintable
(shape1, PaintMode.FILL_DRAW, Colors.red);
Shape shape2 = new XOval(150, 125, 100, 50);
Paintable paintable2 =
new ShapePaintable
(shape2, PaintMode.FILL_DRAW, Colors.yellow, Colors.blue);
window.clearSequence();
window.appendPaintable(paintable1);
window.appendPaintable(paintable2);
window.repaint();
}
The button executes the method which:
- Creates 2
Shapeobjects.
The rectangle has top-left corner at (100,100), width 100, and height 50.
The oval has top-left corner at (150,125), width 100, and height 50. - Uses them to create 2
Paintableobjects with paint colors specified or given by default.
The rectangle has fill color red and the default border color black.
The oval has fill color yellow and border color blue. - Clears the graphics
windowand then installs the 2Paintableobjects. - Repaints the graphics
window.
The sample applet is set up so that you can drag the shapes in the window using the mouse.
Back to Top.
Back to Links to Course Materials.
Back to Start of First Apple.
Down to Bottom.
9/14/08: First Sample Application
The sample application must be compiled in a development environment such as Eclipse and run on your local machine rather than through a browser. This is your task in Homework 1 below.
The first sample application is defined in the file
Methods.java
.
The file Methods.java contains a
public class named Methods. It
is a Java requirement that the name of the public class
and the name used in its file name be the same. This is
a historical requirement which now seems unfortunate but
that is the way things are. We often use a file with the
name Methods.java to run experiments. This
is fine as long as the files belong to different
projects and are in different folders on the machine.
In the sample application, class Methods
extends JPF. Therefore, as with the sample
applet above, there will be an automatic GUI with green
buttons to execute the simple public methods defined in
Methods.
The first public method defined is:
public double EvalDouble(double x) {
return x;
}
Since this method has both a parameter x of
type double and a return type which is also
double, it is necessary to
bring up an auxiliary GUI to allow the user to enter the
input parameter and see the return value. Here is a
snapshot of this auxiliary GUI:
Notice that the input parameter on the right may be entered with mathematical expressions including function calls. The evaluation of such mathematical expressions is built into the I/O system of Java Power Tools.
The second public method defined is:
public void Plot() {
new FunctionsPlotter().frame();
}
This method uses the sophisticated FunctionsPlotter
class that is built into JPT. After creating a new
object of this class, the method call frame() asks
the functions plotter object to put itself into a frame, that
is, a new top-level window on the system.
Here is a snapshot of the function plot tab of the functions plotter. This snapshot is reduced to 75% of its original size. To see the full size snapshot, click on the snapshot.
As you see, two functions are plotted. The sine function
denoted sin is built into Java and JPT. The other
function f is user-defined.
Here is a snapshot of function definition tab of the functions
plotter with the definition of function f illustrated.
This snapshot is reduced to 75% of its original size. To see the
full size snapshot, click on the snapshot.
Back to Top.
Back to Links to Course Materials.
Back to Start of First Sample.
Down to Bottom.
9/14/08: Homework #1
The purpose of Homework 1 is simply to get Java, Eclipse, and the JPT
library jpt.jar installed and then to test that everything
is working correctly. To do that, you will test using the
First Sample Application
discussed above. For convenience, we repeat the link:
The First Sample Application is defined in the file
Methods.java
.
Here are the steps. Note that the download links are given above.
Step 1: Unless you are using Mac OS X, download and install Java.
Step 2: Download and install Eclipse.
Step 3: Download jpt.jar. Place
this file in an easily accessible folder on your system so
that when an update is available you may easily do the
replacement.
Step 4: Open Eclipse. Either accept the default “workspace” or choose a folder for the workspace that is also easily accessible.
Step 5: Following the directions and screen snapshots on the JPT site, set the Eclipse defaults so that they are convenient for student programming. Note that the screen snapshots are from an earlier version of Eclipse but the settings for the current version should be similar.
Step 6: In the compiler settings of Eclipse,
be sure to define a variable named “JPT” that
refers to your copy of jpt.jar.
Step 7: Create a new Java project and name it “FirstSample”. Make sure you do both of the following:
- Choose separate
srcandbindirectories for the source files and compiled binary files. - Choose “Next” rather than “Finish” and then add the variable “JPT” so that the JPT library can be referenced.
- Then select “Finish”.
Step 8:Download the first sample application
Methods.java and place it on the desktop. Then
with the Eclipse window covering only part of the screen,
drag the file Methods.java into the
src directory of the “FirstSample”
project. This drag operation will make a copy of the file
so the original is unchanged.
Step 9: Run and test the first sample application and try the 2 examples discussed above. Use these experiments to see some of the possibilities in JPT.
Back to Top.
Back to Links to Course Materials.
Back to Start of Homework #1.
Down to Bottom.
9/18/08: Tic Tac Toe
The Tic Tac Toe game is elementary and so provides a simple setting in which to illustrate several ideas in building graphical user interfaces (GUIs) using the Java Power Tools. Consider two screen snapshots from the Tic-Tac-Toe program. In the first screen snapshot, player X has won the game and the winning sequence is highlighted in yellow. In the second screen snapshot, the game has been played to a tie since neither X nor O has won and no more moves are possible.
Click on either snapshot above to go to the JPT 2.6.0 Applets Page where there is a more complete dicussion of Tic-Tac-Toe together with access to the applet and the source code. When you reach that page, click on the snapshots there to launch the applet and get to the source code.
You will see that the
Tic-Tac-Toe
source code is
structured into 2 Java classes in 2 files.
The class TicTacToe defines
Tic-Tac-Toe
as an application.
The class TicTacToeApplet uses TicTacToe
to define
Tic-Tac-Toe
as an applet.
It is very convenient to build an application class in such a way that
it can easily be utilized to create a corresponding applet.
Back to Top.
Back to Links to Course Materials.
Back to Start of Tic Tac Toe.
Down to Bottom.
9/23/08: Homework #2
In last week's class (9/18/09), I asked you to "look at" the code for:
Actually, I would like you to do a bit more before the next class (9/25/08).
Please print these two files.
Then “annotate” these printouts with comments that explore a number of questions:
- what do the constant definitions accomplish?
- how is the size and spacing of the tic-tac-toe tiles specified?
- how are the tic-tac-toe tiles geometrically positioned?
- how are the objects blank, X, and O constructed?
- where is the mouse click behavior defined?
- how is the mouse click behavior installed?
- where is the new game behavior defined?
- how is the new game behavior installed?
- how does the program determine if X or O has won?
- when is a game over?
- how are the game board and the new game button inserted into the GUI?
- what makes everything appear in a window on the screen?
You may not be able to fully understand the Java details but you should be able to locate where things happen.
In class, I will go over questions like this and use them as a means for explaining lots of Java principles.
In my opinion, it is far easier to explain how something works if you see what it is good for.
I will ask you to hand in your printout of TicTacToe.java signed with your name at the end of the class.
Back to Top.
Back to Links to Course Materials.
Back to Start of Homework #2.
Down to Bottom.
10/7/08: Tic Tac Toe Revisited
On 9/18/08, I posted a discussion of a TicTacToe program and applet that was originally posted on the JPT 2.6.0 site. As I have described this program in lecture, I have realized that:
- The code structure could be better
- Certain member data objects could actually be static
- The comments could be improved
The purpose of this posting is to present these improvements.
Here is a link to the applet for the revised program:
Here are the links to the revised code:
The code in TicTacToe.java is now structured into
7 sections that provide a good model for organizing the code in
Java programs:
- Static Data
- Static Initialization
- Member Data
- Constructors
- Member Methods
- Static Methods
- The
mainmethod
Note: All Java classes may be organized into these 7 sections. Most Java classes will need only some of the sections.
The inspiration for the change in structure was the realization
that the 3 Paintable game blocks blank,
X, and O may be defined as static
data that is shared among all instances of TicTacToe.
In order to use this idea, it is necessary to perform
static initialization of the 3 game blocks since it is not
possible to define these objects using a single line of code.
The technique for doing this is to use a
static initialization code block:
static { makeBlocks(); }
As a matter of style, this static initialization code block makes a call to a single static method so the necessary code does not interrupt the flow of the data definitions in the program.
To illustrate the idea of a derived class, we also supply the following Java files:
The class TicTacToeWithDialog extends the class
TicTacToe by overriding the method
checkForWinner() to insert a step that causes a
dialog to pop up when X or O wins
the game. This example shows that once a class builds some
basic functionality, it is often easy to introduce variants
with only a small amount of code.
Here is a link to the variant applet.
Back to Top.
Back to Links to Course Materials.
Back to Start of Tic Tac Toe Revisited.
Down to Bottom.
10/9/08: 15 Puzzle
The 15 Puzzle is a classic puzzle with 15 tiles numbered 1 to 15 in a 4-by-4 framework that has one empty slot. The goal of the puzzle is to use the empty slot to push the tiles around until the tiles are in order from left to right and from top to bottom.
In the applet version of this puzzle, if you click on a tile in the same row or column as the empty slot, the tiles will move so that the empty slot ends up in the place you have clicked. This convention is faster than having you move a tile at a time.
To execute the applet, click on the image.
Here are the links to the code:
There is a variation of the puzzle in which the numbers are replaced by blocks in an image.
To execute the variant applet, click on the image.
Here are the links to the code:
Here is the original image:
The 15 Puzzle programs are built using the basic framework described in Tic Tac Toe Revisited. Here is a quick summary of the similarities and differences.
- Much of the structure and many of the data items and methods in the
new programs imitate what is done in
TicTacToe. - The new programs use a square array of
TileBoxobjects, just as inTicTacToe, to store the puzzle pieces which arePaintable. TheseTileBoxobjects are collected in aPaintableSequencewhich is in turn embedded in aPaintableComponent. - The puzzle pieces must be constructed just as the shapes need to be
built in
TicTacToe. One difference, however, is that the puzzle pieces are member data which permits the constuction method to be overridden in a derived class. This is how the version using the image blocks is built mainly on the version that uses the number blocks. - The program
FifteenPuzzleusesTextPaintableobjects to hold the 15 number puzzle pieces rendered in a 72-point font. Hence the program illustrates techniques for using text in a GUI. - The program
FifteenPuzzleUsingImageusesImagePaintableobjects in two ways. First the large image of the yellow rose is downloaded from the web and stored in a 400-by-400ImagePaintable. Then the program makes 15 smallerImagePaintableobjects, each 100-by-100, and copies sections of the original image onto these puzzle pieces. In this way the image is broken up into fragments that may be moved around the puzzle. - The code that handles the mouse click takes basic elements from
TicTacToe. However, to permit the movement of several blocks at once, the code use awhileloop which is in many ways more elegant than the more traditionalforloop.
Back to Top.
Back to Links to Course Materials.
Back to Start of 15 Puzzle.
Down to Bottom.
10/10/08: Homework 3: 15 Puzzle Enhancements
Due Date: 10/23/08
Submit the Java files in a zip file and make sure that your name is part of the file name of the zip file. This is the main way I will have to keep the submissions from being confused. The Java files will be your revisions to:
FifteenPuzzle.javaFifteenPuzzleUsingImage.java
Homework 3 Tasks
The fundamental enhancement that you must do is to provide a reward to the user when the user completes the 15 puzzle. This reward will be to provide the missing 16th block:
- In the case of the number puzzle, the 16th block will be a block with the number 16.
- In the case of the image puzzle, the 16th block will be a block with the lower right corner of the image.
For snapshots, see below.
In order to provide this reward, you will need to construct all
16 puzzle pieces when the program begins not just the 15 used
when the puzzle is initialized. The program has a static
variable count set to 15 which holds the number of
pieces used in initialization. I suggest a second static
variable total set to 16 to be used to initialize
the array pieces and to do other work that involves
all 16 pieces. Clearly, as you modify the original program, you
need to consider when to use count and
when to use total.
The next requirements concern my ability to test and grade your programs.
When each of you submits your files, I will end up with more than
30 pairs of Java files with the same names! I will certainly put
these files into separate projects but I want an immediate way to
tell whose program I am running. Therefore, I want each of you
to put your name in a TextPaintable that sits on top
of the puzzle board in the mainPanel. Use a 24 point
serif font which is both bold and italic. To get the latter, use
the expression below as the middle argument to the Font
constructor:
Font.BOLD | Font.ITALIC
The next question is testing which is always a concern when writing programs. The reward enhancement can be tested only when the user finishes the puzzle. Starting with a random puzzle, it may take many mouse clicks before the puzzle is complete. Therefore, testing will be very tedious for you and for me if a random puzzle is the only possibility.
Therefore, I want everyone to add a button Test Puzzle that starts the puzzle in a standard configuration that is not far from a finished puzzle. Specifically:
- The first 3 rows of the puzzle should be already correct.
- The element
pieces[14]should be in row 3, col 0. - The element
pieces[12]should be in row 3, col 1. - The element
pieces[13]should be in row 3, col 2. - The element
blankshould be in row 3, col 3.
The left side snapshots show the state that the puzzle should have when the Test Puzzle button is clicked and the right side snapshots show the state that the puzzle should have when the puzzle is done. Notice that when the puzzle is done, the reward block has been added in each case.
Note that if you click on any snapshot above, it will lead to the corresponding applet.
Homework 3 Hints
If you look carefully, you will see that the buttons New Puzzle
and Test Puzzle are aligned horizontally. This means that the
corresponding action objects are not placed directly in the array
mainStuff that is used to build mainPanel.
What is done instead is that the action objects are placed in a
horizontal panel using an HTable and that panel is placed
in turn in the array mainStuff.
One of the key things you will need to figure is how to test when the
user has finished the puzzle. You must run an appropriate loop over
the pieces array which is 1-dimensional and compare with the
Paintable objects stored within the TileBox
objects within the 2-dimensional tiles array. As you
can see from this description, careful thinking and attention to
detail will be essential.
As a matter of design, you should place the code that tests for the
finish of the puzzle in its own method. This method should be called
as the last line of the method click so it will be done
after each mouse click. Unfortunately, if you look at the design of
the click method in the original, there are lots of
return statements that make quick exits. All of these
will need to be removed or else you will never reach the last line of
the method! Of course, you cannot merely remove the return
statements since then the code will break. You must actually redesign
the click method to accomplish the same behavior but in a
different way.
You may ask: Why was the click method designed so badly in
the first place that it cannot be easily adapted to the new situation?
The answer is simple: I did not think of the enhancements until after
yesterday’s lecture and therefore did not design
the click method in a
way that would make the enhancements easy. This situation happens all
the time in real world code and it is essential for someone who will
work with code to be able to adapt the old to make the new.
If you test the applets, you will see that after the puzzle is finished
and the 16th block is in place, the mouse will no longer do anything in
the puzzle area. If you examine TicTacToe, you will see
a way to accomplish the same behavior using a boolean
variable.
Homework 3 Extras
You may be amused to try to implement one or both of the following:
- Bring up an OK dialog that says Congratulations when the user finishes the puzzle.
- Keep track of the click count and when you offer congratulations also tell the user the number of clicks required.
Back to Top.
Back to Links to Course Materials.
Back to Start of Homework 3: 15 Puzzle Enhancements.
Down to Bottom.
10/16/08: Homework 3: Comments
I have some further thoughts on the Homework 3 Extras. I would suggest 3 tasks rather than 2:
- Bring up an OK dialog that says Congratulations when the user finishes the puzzle.
- Keep track of the click count and when you offer congratulations also tell the user the number of clicks required.
- Save the time in milliseconds when the puzzle starts. When the puzzle ends, get the current time in milliseconds and then compute the difference between this time and the saved start time. Divide by 1000 to convert the difference to seconds. Then tell the user how many seconds were required to solve the puzzle.
Here is a snapshot of the dialog box that is displayed in my implementation of the 3 tasks:
Here are the links to the number puzzle and image puzzle with the dialog implemented:
Here are some technical hints:
-
The class
TextPaintableis designed to handle only a single line of text, that is, the text string may not contain a newline. -
To handle text with multiple lines as in the dialog snapshot above, use
the class
MultiLineTextPaintable. -
To determine how the text flows downward from line to line, you need to
use a
TextAnchor.Locatorobject. If you imagine the text being pinned to a bulletin board, theTextAnchor.Locatordetermines where in the text of the first line the pin position is. -
If
messageis the text string with the complete message to display andfontis the font you have defined for the message, then the code that you need to create thepaintableis this:This will be explained further in class.
MultiLineTextPaintable paintable =
new MultiLineTextPaintable
(message, font, TextAnchor.CENTER_BASELINE, 0, 0);
-
The Java method to get the current time in milliseconds is:
The return type of this method is
System.currentTimeMillis()
long. To use this method to compute the time difference, it will have to be called twice, once when the puzzle is started and once when it is finished. Obviously, each call should store the value in a different member data variable. - To show an OK dialog with the
paintableobject, use code of the form:In general, the first argument to this method is any object that is a Java component or may be converted into a Java component. The object
GeneralDialog.showOKDialog(paintable, "");
paintablesatisfies this requirement.
Back to Top.
Back to Links to Course Materials.
Back to Start of Homework 3: Comments.
Down to Bottom.
10/23/08: Playing Cards
The Playing Cards Demo displays a deck of 52 cards plus 2 card backs and 2 jokers. If a card is clicked with the mouse, it jumps to the top of the heap. If a card is dragged with the mouse, it moves. The demo can show the cards in sorted order or randomly placed as is illustrated by the two screen snapshots below:
Here are the links to the code:
In terms of building graphical user interfaces (GUIs), the Playing Cards Demo illustrates many useful techniques.
- How to define a
BufferedPanelgraphics window. - How to read the images of a deck of cards from a web site using the class
WebImageToolsand how to save references to these images as an array ofImagePaintableLiteobjects. - How to append
Paintableobjects to aBufferedPanelso that these objects will float above the panel and be able to be selected and dragged with the mouse. - How to define a permutation that will randomly order the playing cards
using tools from
ProbStatTools.
The playing cards are found on the JPT web site at:
http://www.ccs.neu.edu/jpt/images/jfitz_cards/
The ordering of the cards is hearts, diamonds, spades, and clubs, followed by 2 card backs and 2 jokers. This ordering is specified in the following text file within that site: imagelist.txt
There are additional “card fragments” but only the 56 images in
“imagelist.txt” are downloaded into the PlayingCards
program. To obtain all 67 images including the “card fragments”,
use instead the text file:
imagelistall.txt
The site from which the playing cards were originally downloaded is:
We appreciate the public service that the JFitz site performs by making these playing cards available at no charge.
Back to Top.
Back to Links to Course Materials.
Back to Start of Playing Cards.
Down to Bottom.
11/15/08: Picking Cards
The Picking Cards Demo is a demo program that evolved from the Playing Cards Demo. This demo allows the user to display the cards in a shuffled deck one at a time in contrast to the earlier demo that shows the entire deck at once. Two mechanisms are provided for showing a single card. The user may click the Show Next Card button or may click the image of the card back shown in the upper right of the graphics window. As a card is shown, the text view shows information about the card. This proves that the program can access this kind of information. To execute the program as an applet, click on the snapshot below:
The deck may be shuffled immediately by clicking the Shuffle Cards button. If all 52 cards have been displayed, the deck will be shuffled automatically when the next card is requested. On each shuffle, the graphics window will be cleared except for the card back image.
Here are the links to the code:
The Picking Cards Demo is much more explicit than the Playing Cards Demo. In order to show cards one at a time rather than all at once, it is necessary to maintain as data structure:
- The permutation array
shufflethat holds the current way in which the deck of cards in shuffled. - The position
currentthat shows which position in arrayshuffleholds the index of the current card.
Mathematically, what is happening is really beautiful. The array of
cards is never changed. Instead, to create a new card shuffle, we make
a new permutation array shuffle, and then use indexing to
find a shuffled card based on the current position.
Specifically, we may find the card index for the shuffled card
using:
shuffle[current]
However, as the cards are dealt one by one and current is
incremented, the value of current will reach 52
if the deck is not shuffled by calling shuffleCards(). This
value is beyond the range of the standard cards in the deck. To force an
automatic shuffle in this situation, use the following method to access
the current card index:
int currentCardIndex() {
if (current >= M) {
shuffleCards();
}
return shuffle[current];
}
Once we have the card index, we can find the image paintable to build a card tile and we can find the rank, suit, and value of the card.
Finding the rank index and suit index from the card index is based on the following table that shows the relationship between the various items. The card index is shown in the large data block.
| Suit | Hearts | Diamonds | Spades | Clubs | ||
| Suit Index | 0 | 1 | 2 | 3 | ||
| Rank | Rank Index | |||||
| Ace | 0 | 0 | 13 | 26 | 39 | |
| 2 | 1 | 1 | 14 | 27 | 40 | |
| 3 | 2 | 2 | 15 | 28 | 41 | |
| 4 | 3 | 3 | 16 | 29 | 42 | |
| 5 | 4 | 4 | 17 | 30 | 43 | |
| 6 | 5 | 5 | 18 | 31 | 44 | |
| 7 | 6 | 6 | 19 | 32 | 45 | |
| 8 | 7 | 7 | 20 | 33 | 46 | |
| 9 | 8 | 8 | 21 | 34 | 47 | |
| 10 | 9 | 9 | 22 | 35 | 48 | |
| Jack | 10 | 10 | 23 | 36 | 49 | |
| Queen | 11 | 11 | 24 | 37 | 50 | |
| King | 12 | 12 | 25 | 38 | 51 |
Therefore, the following methods relate the card index, the rank index, and the suit index:
int getRankFromIndex(int index) {
return index % 13;
}
int getSuitFromIndex(int index) {
return index / 13;
}
int getIndexFromRankSuit(int rank, int suit) {
return rank + 13 * suit;
}
It is also easy to get the card value from the rank (following Blackjack conventions) using the following method:
int getValueFromRank(int rank) {
if (rank == 0)
return 11;
else if (rank >= 9)
return 10;
else
return rank + 1;
}
In Blackjack, if the value of 11 for an ace will cause a bust,
it is simple to adjust the value to 1 after the fact and redo
the calculation of the sum of the cards.
The PickingCards example has been constructed so that you have
many useful pieces of code for doing the
Homework 4: Blackjack
assignment.
Note that, for the Blackjack assignment, you may use the IntVector class to store the card indices for the cards in a hand, the card values for the cards in a hand, and the card indices for all cards dealt since the last shuffle. What you use depends on what features of Blackjack you choose to implement.
Back to Top.
Back to Links to Course Materials.
Back to Start of Picking Cards.
Down to Bottom.
11/6/08: Homework 4: Blackjack
The purpose of this homework is to let you put together a simple program before you begin on your semester project. The basic assignment is to implement the game of Blackjack using a nice graphical user interface. You may design the details.
The game of Blackjack is described in Wikipedia:
In a Blackjack hand, aces count 1 or 11 as desired, other number cards count with their value, and jacks, queens, and kings count as 10. The goal is to get as close to 21 without going over 21, which is called a bust.
It is fairly easy to compute the value of a hand by first calculating as if all aces were 11. If the total goes over 21 but the hand has an ace then subtract 10 which is equivalent to counting that ace as 1. If the total is still over 21 and there is another ace, repeat the process.
In Blackjack, each player plays against the dealer. Hence, the simplest form of Blackjack that you can program for this assignment is to have one human player and one dealer controlled by the program.
A player with a hand can either hit, that is, take another card, or stand, that is, stand pat with the cards already taken. If you do hit and then bust, you lose even if the dealer also busts. In Blackjack, there are rules that determine whether the dealer must hit or must stand. These rules will make it fairly easy to program the dealer.
The question of whether you have one or more players besides the dealer involves two considerations:
- The more players you have, the more thought you must put into the user interface so the relevant information is visible but the screen is not too cluttered.
- The more players you have, the more you know about cards that have been played and you may sometimes improve your odds by making use of this information. This is the essence of counting cards.
Further comments
The Java ingredients for building Blackjack may be found by extracting code ideas from the following examples:
Fifteen Puzzle Playing Cards Picking Cards IntVector Sketch #1 Sketch #2
It is likely that the graphical user interface of your program will have to evolve. Try to build the GUI flexibly so if a change is needed then it is not too hard to do.
Start with a simple game: one player and one dealer. Ignore betting at first. Just determine who wins or loses each game. Introduce betting only when the basic game is working. Introduce multiple players only when the basic game with betting is working. Keep in mind that each player plays against the dealer and not against the other players.
Since counting cards is one way to win at Blackjack in real casinos but is stressful on the memory, you might have fun making a panel that can come up when a button is clicked that shows all cards played so far in some form of tabular representation. This could help you compete better in this electronic game. Of course, it is illegal to use electronic means to remember things in real casinos. ☺
The Wikepedia article mentions assorted enhancements and variations of Blackjack. You may program none of these. That’s OK. Or you may add the enhancements that you wish. Keep in mind that each addition puts pressure on the GUI so you must be careful with the tradeoffs.
Some final requirements:
- As in the Fifteen Puzzle homework, your name must be shown at the top of the program.
- If you add enhancements, it might help to have a button that brings
up a
StringViewerin a panel with directions for the user and discussion. - Please keep a log of your work. This is simple. Create a
text file named
log.txtin yoursrcfolder. When you finish a stretch of work, make an entry at the bottom of this file that has the date/time as the header and then has a summary of what have done during that work and a to-do-list of open problems to tackle. Just accumulate as you go along and don't bother to go back and edit old entries. This policy will both save you time and train you to write better on-the-fly.
Back to Top.
Back to Links to Course Materials.
Back to Start of Homework 4: Blackjack.
Down to Bottom.
11/15/08: IntVector
Class IntVector stores int data in an
indexed list whose capacity will be increased automatically
as needed.
In addition to the usual list-like operations,
IntVector also provides a sum() method
for summing the int data stored in the structure.
Class IntVector is useful because in Java 6 the
generic collection types can deal only with objects and
not with primitive types such as int.
The IntVector class may be useful in
Homework 4: Blackjack.
As shown by the code in
Picking Cards demo program,
a card may be specified by an index between 0 and 51 that selects
the card paintable image in the cards array and that
may be used to get the rank, suit, and value of the card. Thus,
if you want to store the hand for a player or dealer, it is
sufficient to store the sequence of index values corresponding to
the cards. The class IntVector will do just that
and will avoid the necessity of limiting the size of a hand in
advance.
Here is the link to the code:
Back to Top.
Back to Links to Course Materials.
Back to Start of IntVector.
Down to Bottom.
10/30/08: Sketch #1
Back to Top.
Back to Links to Course Materials.
Back to Start of Sketch.
Down to Bottom.
11/15/08: Sketch #2
Back to Top.
Back to Links to Course Materials.
Back to Start of Sketch #2.
Down to Bottom.
11/6/08: Spinning Animation
The screen snapshots below provides links to 2 animations that are
functionally the same but use 2 different Paintable
objects for the contents to animate.
The base class that supports the animations is:
This class illustrates the following techniques:
- The use of
SimpleThreadedActionto arrange that the animation is run in a separate thread so that it can appear to run in parallel with the Java code that manages the GUI interactions such as the mouse. - The use of the Java
synchronizeconstruct so that you can guarantee that the underlying data structure cannot be changed during the time that the animation is taking place. - The use of JPT
SliderViewcontrols to set the rotational step size in degrees and the animation speed as the animation progresses. This is more flexible than fixing the animation tick time in advance of running the program. - The technique for setting the
Paintableto be animated after construction of theSpinningAnimationobject. In particular, this technique permits setting to be done in a derived class which is what is done for the 2 examples. - The technique for setting a window closing action so that the animation is
terminated if the user closes the frame (window) for the animation. This
depends on an override of the critical inherited
framemethod. - The technique for creating multiple interrelated constructors that permit flexibility but keep the key code in a single place.
- How to define and use a
Paintable, itsTile, and its associatedPaintableComponent.
Back to Top.
Back to Links to Course Materials.
Back to Start of Spinning Animation.
Down to Bottom.
11/18/08 Text Sample using Annotation
This example shows how to use the JPT class Annotation
to put text into a cell within a panel in such a way that space is
reserved for the text even if the initial text is empty.
The text may be modified by the program but may not be edited by
the user.
In the example, the 3 buttons change the text from the empty string
to a short string or a long string or revert the text back to empty.
By using the following method from TablePanel
setMinimumColumnWidth
the width of the column in the panel may be set to a minimum of 500 pixels which is enough room for the long string.
As is evident from the snapshot, the program can control the font and color of the text.
Here are the links to the code:
Back to Top.
Back to Links to Course Materials.
Back to Start of Text Sample using Annotation.
Down to Bottom.
11/18/08 Text Sample using MultiLineTextPaintable
This example shows how to use the JPT class MultiLineTextPaintable
to put text into the PaintableSequence associated with a
BufferedPanel.
The text may be modified by the program but may not be edited by
the user.
The text string is typed by the user into a StringViewer panel.
When the user clicks the button, the string is replicated 3 times in the
graphics window using 3 MultiLineTextPaintable objects. These
objects use different “justification”: left-justified, centered,
and right-justified. These different settings are achieved using one of the
following TextAnchor settings:
TextAnchor.LEFT_BASELINETextAnchor.CENTER_BASELINETextAnchor.RIGHT_BASELINE
The TextAnchor setting determines the position within the text
that is used to “pin” the text to the graphics coordinates.
The setting also determines how the text is displayed relative to the pin
position.
The pin positions for the 3 MultiLineTextPaintable objects
are:
(100, 100)for the left-justified text(250, 250)for the centered text(400, 400)for the right-justified text
The pin positions are shown in the graphics window using 3
PointPaintable triangular wedge objects that point upwards at
the pin positions.
The TextAnchor settings in this example pin the text on the
“baseline” of the first line of the text. The vertical spacing
of the text is determined by the parameters of the font being used and thus
does not need to be computed by the program. The TextAnchor
class has additional pin position settings that you may see in the javadocs
for the class.
Note also that the PointPaintable class supports many different
PlotMark objects that may be used to mark a position. For this
example, we used:
PlotMark.FILLED_BLUNT_WEDGE_N
Here are the links to the code:
Back to Top.
Back to Links to Course Materials.
Back to Start of Text Sample using MultiLineTextPaintable.
Down to Bottom.
12/4/08 Parcheesi
The origin of this example is a student question about how to put the image of a game board into a GUI in such a way that game pieces may float above the game board and be movable via the mouse.
The original web location of the particular game board, Parcheesi, is:
http://i408.photobucket.com/albums/pp164/cmcd/Board.gif
However, because of annoying applet security restrictions, an applet can only access an image from its own web domain. Therefore, I needed to copy the image to a directory in the JPT directory tree:
http://www.ccs.neu.edu/jpt/images/gameboard/Parcheesi.gif
The Parcheesi game board image from this location is:
Here are the links to the code:
As you can see, I decided to simply use a Methods
class to provide the sample test code directly. I did not try
to invent a GameBoard class because I am uncertain
as to the best way to design such a class in full generality.
The basic technique is this:
- Write a method that will return the image, Parcheesi,
and embed that image in an
ImagePaintable. - Construct a
BufferedPanelwhose size is large enough to hold the image plus amarginon all four sides. - The margin is there for two reasons. To provide a place for game pieces off the board and to allow for the use of a background paint.
- After the
BufferedPanelis created, the background paint is used to fill the entire buffer. - Next, using the
ImagePaintable, the image is painted onto the buffer. In doing so, the painting is offset by the size of the margin. This centers the image in the buffer. - Finally, game pieces may be added to the
PaintableSequenceassociated with theBufferedPanelas desired. These pieces float above the game board and the margin which are painted onto the bits of the buffer below.
Click on the image below to access the test applet. You may move the small red and green pieces with the mouse but the Parcheesi game board is fixed.
Back to Top.
Back to Links to Course Materials.
Back to Start of Parcheesi.
Down to Bottom.