In general, Java is the language of the Internet, which can be used to create two types of programs: applications and applets. The output of a Java compiler is not executable code, but rather bytecode - making the Java run-time system an interpreter for bytecode.
Similarities
The two main similarities between Java and C++ are that they both use similar syntax, such as the general forms of the for, do, and while loops. Secondly, they both support object-oriented programming.
Differences
On the contrary, there are a number of differences between the two languages. Some main features that are not supported in Java are:
1. Perhaps the single greatest difference between C++ and Java, is that Java doesn’t support pointers, therefore the -> operator DNE as well.
2. Java does not include structures or unions because the class encompasses these other forms. It is redundant to include them.
3. Java does not support operator overloading.
4. Java does not include a preprocessor or support the preprocessor directives.
5. Java does not perform any automatic type conversions that result in a loss of precision.
6. All the code in a Java program is encapsulated within one or more classes.
7. Therefore, Java does not have global variables or global functions.
8. Java does not support multiple inheritance.
9. Java does not support destructors, but rather, add the finalize() function.
10. Java does not have the delete operator.
11. The << and >> are not overloaded for I/O operations.
12. Java does not support templates.
13. Java supports “garbage collection”, where as C++ does not.
There are also a number of other differences between the way Java and C++ relate to classes. By default, members of a class are accessible by other members of their class, derived classes, and by other members of their package. Therefore, class members are “more public” than they are in C++, however, the private access specifier applies only to the variable or method that it immediately precedes. All class objects are instantiated in Java using the new operator. Therefore, all class objects are dynamically allocated. When there are no references to an object, then the object is considered inactive.
Java includes two class-management features that help make using and organizing classes easier. The first is called a package, which defines a scope. Therefore, names declared inside a package are private to that package. Java uses file directories to store packages. Therefore, each package must be stored in a directory that has the same name as the package—including capitalization.
Java, like C++, supports hierarchies of classes. However, the way that inheritance is implemented in Java differs substantially from the way that it is implemented in C++. Since multiple inheritance is not allowed in Java, Java class hierarchies are linear. In Java, inheritance is referred to as subclassing. A base class in C++ is referred to as superclass in Java.
And there you have it, hope that helps.
Tuesday, August 21, 2007
Saturday, August 18, 2007
Blackjack Game
Below is a description of my Blackjack Game project, which I've implemented:
Create a single-player Blackjack applet:
New players will be assigned a BlackJackHand with two Cards to start. They have the option to “hit” or “stay”. If the player busts, the round is over and a point goes to the dealer. When the player “stays”, the game will generate the dealer’s Hand, and indicate the results to the player. The user can play another round after a round is finished. A running tally of dealer and player wins is displayed, which can be reset.
To complete this assignment, you will need:
- a single applet (BlackjackApplet), which responds to “hit” and “stay” commands, and displays the game state
- a BlackJackGame class, that performs all the actions of the game (the applet will use this class)
- a Deck class (provided)
Tips:
- you will want to get card images from the web to use in your applet, or devise some graphical representation. A set (gif and png) is available at http://www.jfitz.com/cards/
- test your BlackJackGame class with a text console interface first, prior to building the applet. That is, create a BlackJackConsole class that provides a console interface to BlackJackGame.
- use your own implementations of Card, BlackJackHand and Hand if possible. Either way, these classes must be used in your project.
Marking:
- all source code exists and compiles. The application runs and provides the required features. Code is commented using javadoc in the manner required for the course.
- the logic for the game is in BlackJackGame and BlackJackHand. Basic card playing support functionality is in Deck, Hand and Card. UI details are in BlackJackApplet.
- A web page should be provided for the applet. The applet should work properly when the page is opened in a browser. The webpage, applet, supporting bytecode and files should be easily transferred to a different location on your filesystem and still work properly (i.e. do not hard-code absolute paths or operating-system-specific path separators).
Create a single-player Blackjack applet:
New players will be assigned a BlackJackHand with two Cards to start. They have the option to “hit” or “stay”. If the player busts, the round is over and a point goes to the dealer. When the player “stays”, the game will generate the dealer’s Hand, and indicate the results to the player. The user can play another round after a round is finished. A running tally of dealer and player wins is displayed, which can be reset.
To complete this assignment, you will need:
- a single applet (BlackjackApplet), which responds to “hit” and “stay” commands, and displays the game state
- a BlackJackGame class, that performs all the actions of the game (the applet will use this class)
- a Deck class (provided)
Tips:
- you will want to get card images from the web to use in your applet, or devise some graphical representation. A set (gif and png) is available at http://www.jfitz.com/cards/
- test your BlackJackGame class with a text console interface first, prior to building the applet. That is, create a BlackJackConsole class that provides a console interface to BlackJackGame.
- use your own implementations of Card, BlackJackHand and Hand if possible. Either way, these classes must be used in your project.
Marking:
- all source code exists and compiles. The application runs and provides the required features. Code is commented using javadoc in the manner required for the course.
- the logic for the game is in BlackJackGame and BlackJackHand. Basic card playing support functionality is in Deck, Hand and Card. UI details are in BlackJackApplet.
- A web page should be provided for the applet. The applet should work properly when the page is opened in a browser. The webpage, applet, supporting bytecode and files should be easily transferred to a different location on your filesystem and still work properly (i.e. do not hard-code absolute paths or operating-system-specific path separators).
BlackJackApplet Class
//---------------------------------------------------------------------------
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.applet.*;
import java.util.*;
import javax.swing.*;
import java.io.*;
import javax.imageio.ImageIO;
//---------------------------------------------------------------------------
/**
A
and displays the game's state.
@author: Tommy Flewwelling
@version: 1.00
Creation Date: 2007/07/17
*/
public class BlackJackApplet extends JApplet{
public void init(){
// Instantiate a BlackJackGame object.
BlackJackGame canvas = new BlackJackGame();
// Add a canvas to the center of the Layout.
add(canvas, BorderLayout.CENTER);
// Create Button panel.
JPanel buttonPanel = new JPanel();
// Set background color of Button panel.
buttonPanel.setBackground(Color.BLUE);
// Hit button - create buttons and add them to the Button panel.
JButton hit = new JButton("Hit");
hit.addActionListener(canvas);
buttonPanel.add(hit);
// Stay button.
JButton stay = new JButton("Stay");
stay.addActionListener(canvas);
buttonPanel.add(stay);
// New Game button.
JButton newGame = new JButton("New Game");
newGame.addActionListener(canvas);
buttonPanel.add(newGame);
// Reset button.
JButton reset = new JButton("Reset");
reset.addActionListener(canvas);
buttonPanel.add(reset);
// Add Button Panel to the south.
add(buttonPanel, BorderLayout.SOUTH);
}
//---------------------------------------------------------------------------
/**
A
the option to “hit” or “stay”, while the Dealer must “stay” if their Hand is seventeen or greater.
Blackjack wins over all other Hands. If both Player and Dealer have the same Hand, the round
ends in a push(tie). I’ve defined the number of Players to be one for simplicity.
@author: Tommy Flewwelling
@version: 1.00
Creation Date: 2007/07/17
*/
class BlackJackGame extends Canvas implements ActionListener{
//---------------------------------------------------------------------------
// Define the initial number of cards needed for a Hand of BlackJack.
public static final int INIT_SIZE_BLACKJACK_HAND = 2;
// Constants used throughout the program.
public static final int HIT = 0, STAY = 1, ZERO = 0, SET = 1, DEFAULT = -1, PLAYER = 0, DEALER = 1, BLACKJACK = 21, TWENTY_ONE = 21, EMPTY = 0;
// Define the number of Players as one - for simplicity.
public static final int NUMBER_OF_PLAYERS = 1;
// The lowest and highest Hand of BlackJack that can be dealt - used to determine if the Dealer should "Hit" or "Stay".
public static final int BLACKJACK_LOW = 4, BLACKJACK_HIGH = 17;
// Set if Player obtains BlackJack on first draw.
int blackJackFlag = DEFAULT;
// Tally number of rounds played, wins, losses and ties of both Dealer and Player.
public int playerWinTally = ZERO, dealerWinTally = ZERO, playerLostTally = ZERO, dealerLostTally = ZERO, tieTally = ZERO, roundTally = ZERO;
// Note the status of the game.
boolean gameInProgress = false;
// Display message.
String display;
// Font for displaying messages.
Font font;
/** A Card object. */
private Card card;
/** A Deck object. */
private Deck deck;
/** A Hand object. */
private Hand[] hand;
/** A BlackJackHand object for the Player. */
private BlackJackHand playersHand;
/** A BlackJackHand object for the Dealer. */
private BlackJackHand dealersHand;
/** A HashMap Object. */
private HashMap mapCards;
/** An Image object. */
private Image cardImage;
//---------------------------------------------------------------------------
/**
Sets background color, initializes fonts, creates a hashmap and begins the game.
*/
BlackJackGame(){
// Set background color.
setBackground(Color.GREEN.darker().darker());
// Set font.
font = new Font("Serif", Font.BOLD, 14);
// Mapping of Cards to their image.
mapCards = new HashMap();
try{
// Clubs.
mapCards.put(new Card(2,0), ImageIO.read(new java.net.URL(getCodeBase(),"cards/2c.gif")));
mapCards.put(new Card(3,0), ImageIO.read(new java.net.URL(getCodeBase(),"cards/3c.gif")));
mapCards.put(new Card(4,0), ImageIO.read(new java.net.URL(getCodeBase(),"cards/4c.gif")));
mapCards.put(new Card(5,0), ImageIO.read(new java.net.URL(getCodeBase(),"cards/5c.gif")));
mapCards.put(new Card(6,0), ImageIO.read(new java.net.URL(getCodeBase(),"cards/6c.gif")));
mapCards.put(new Card(7,0), ImageIO.read(new java.net.URL(getCodeBase(),"cards/7c.gif")));
mapCards.put(new Card(8,0), ImageIO.read(new java.net.URL(getCodeBase(),"cards/8c.gif")));
mapCards.put(new Card(9,0), ImageIO.read(new java.net.URL(getCodeBase(),"cards/9c.gif")));
mapCards.put(new Card(10,0), ImageIO.read(new java.net.URL(getCodeBase(),"cards/tc.gif")));
mapCards.put(new Card(11,0), ImageIO.read(new java.net.URL(getCodeBase(),"cards/jc.gif")));
mapCards.put(new Card(12,0), ImageIO.read(new java.net.URL(getCodeBase(),"cards/qc.gif")));
mapCards.put(new Card(13,0), ImageIO.read(new java.net.URL(getCodeBase(),"cards/kc.gif")));
mapCards.put(new Card(14,0), ImageIO.read(new java.net.URL(getCodeBase(),"cards/ac.gif")));
// Spades.
mapCards.put(new Card(2,1), ImageIO.read(new java.net.URL(getCodeBase(),"cards/2s.gif")));
mapCards.put(new Card(3,1), ImageIO.read(new java.net.URL(getCodeBase(),"cards/3s.gif")));
mapCards.put(new Card(4,1), ImageIO.read(new java.net.URL(getCodeBase(),"cards/4s.gif")));
mapCards.put(new Card(5,1), ImageIO.read(new java.net.URL(getCodeBase(),"cards/5s.gif")));
mapCards.put(new Card(6,1), ImageIO.read(new java.net.URL(getCodeBase(),"cards/6s.gif")));
mapCards.put(new Card(7,1), ImageIO.read(new java.net.URL(getCodeBase(),"cards/7s.gif")));
mapCards.put(new Card(8,1), ImageIO.read(new java.net.URL(getCodeBase(),"cards/8s.gif")));
mapCards.put(new Card(9,1), ImageIO.read(new java.net.URL(getCodeBase(),"cards/9s.gif")));
mapCards.put(new Card(10,1),ImageIO.read(new java.net.URL(getCodeBase(),"cards/ts.gif")));
mapCards.put(new Card(11,1),ImageIO.read(new java.net.URL(getCodeBase(),"cards/js.gif")));
mapCards.put(new Card(12,1),ImageIO.read(new java.net.URL(getCodeBase(),"cards/qs.gif")));
mapCards.put(new Card(13,1),ImageIO.read(new java.net.URL(getCodeBase(),"cards/ks.gif")));
mapCards.put(new Card(14,1),ImageIO.read(new java.net.URL(getCodeBase(),"cards/as.gif")));
// Hearts.
mapCards.put(new Card(2,2), ImageIO.read(new java.net.URL(getCodeBase(),"cards/2h.gif")));
mapCards.put(new Card(3,2), ImageIO.read(new java.net.URL(getCodeBase(),"cards/3h.gif")));
mapCards.put(new Card(4,2), ImageIO.read(new java.net.URL(getCodeBase(),"cards/4h.gif")));
mapCards.put(new Card(5,2), ImageIO.read(new java.net.URL(getCodeBase(),"cards/5h.gif")));
mapCards.put(new Card(6,2), ImageIO.read(new java.net.URL(getCodeBase(),"cards/6h.gif")));
mapCards.put(new Card(7,2), ImageIO.read(new java.net.URL(getCodeBase(),"cards/7h.gif")));
mapCards.put(new Card(8,2), ImageIO.read(new java.net.URL(getCodeBase(),"cards/8h.gif")));
mapCards.put(new Card(9,2), ImageIO.read(new java.net.URL(getCodeBase(),"cards/9h.gif")));
mapCards.put(new Card(10,2),ImageIO.read(new java.net.URL(getCodeBase(),"cards/th.gif")));
mapCards.put(new Card(11,2),ImageIO.read(new java.net.URL(getCodeBase(),"cards/jh.gif")));
mapCards.put(new Card(12,2),ImageIO.read(new java.net.URL(getCodeBase(),"cards/qh.gif")));
mapCards.put(new Card(13,2),ImageIO.read(new java.net.URL(getCodeBase(),"cards/kh.gif")));
mapCards.put(new Card(14,2),ImageIO.read(new java.net.URL(getCodeBase(),"cards/ah.gif")));
// Dimonds.
mapCards.put(new Card(2,3), ImageIO.read(new java.net.URL(getCodeBase(),"cards/2d.gif")));
mapCards.put(new Card(3,3), ImageIO.read(new java.net.URL(getCodeBase(),"cards/3d.gif")));
mapCards.put(new Card(4,3), ImageIO.read(new java.net.URL(getCodeBase(),"cards/4d.gif")));
mapCards.put(new Card(5,3), ImageIO.read(new java.net.URL(getCodeBase(),"cards/5d.gif")));
mapCards.put(new Card(6,3), ImageIO.read(new java.net.URL(getCodeBase(),"cards/6d.gif")));
mapCards.put(new Card(7,3), ImageIO.read(new java.net.URL(getCodeBase(),"cards/7d.gif")));
mapCards.put(new Card(8,3), ImageIO.read(new java.net.URL(getCodeBase(),"cards/8d.gif")));
mapCards.put(new Card(9,3), ImageIO.read(new java.net.URL(getCodeBase(),"cards/9d.gif")));
mapCards.put(new Card(10,3),ImageIO.read(new java.net.URL(getCodeBase(),"cards/td.gif")));
mapCards.put(new Card(11,3),ImageIO.read(new java.net.URL(getCodeBase(),"cards/jd.gif")));
mapCards.put(new Card(12,3),ImageIO.read(new java.net.URL(getCodeBase(),"cards/qd.gif")));
mapCards.put(new Card(13,3),ImageIO.read(new java.net.URL(getCodeBase(),"cards/kd.gif")));
mapCards.put(new Card(14,3),ImageIO.read(new java.net.URL(getCodeBase(),"cards/ad.gif")));
// Face-down card.
mapCards.put(1,ImageIO.read(new java.net.URL(getCodeBase(),"cards/blueCard.gif")));
// Catch exception if one occurs.
}catch (java.net.MalformedURLException me){System.out.println("Image not found!");
JOptionPane.showMessageDialog(this, "Image not found!");
}catch (IOException e){System.out.println(e.getMessage ());}
// Jump to New Game.
newGame();
}
//---------------------------------------------------------------------------
/**
Respond to button clicks.
@param evt The ActionEvent.
*/
public void actionPerformed(ActionEvent evt){
// Returns the command string associated with the action.
String command = evt.getActionCommand();
if(command.equals("Hit"))
hit();
else if(command.equals("Stay"))
stay();
else if(command.equals("New Game"))
newGame();
else if(command.equals("Reset"))
reset();
}
//---------------------------------------------------------------------------
/**
Generates and shuffles a new deck. Creates the Player’s Hand and determines if the Player
has Blackjack and provides the option to “hit” or “stay”.
*/
void newGame(){
// Determine if a game is in progress.
if(gameInProgress){display = "A game is currently in progress."; repaint(); return;}
// Game in progress.
gameInProgress = true;
// Create the Deck.
deck = new Deck();
// Shuffle the Deck.
deck.shuffle();
// Allocate enough Hands for the Player(one in this case) and the Dealer.
hand = new Hand[NUMBER_OF_PLAYERS + DEALER];
// Instantiate a Card object for the Player.
Card[] playerCards = new Card[INIT_SIZE_BLACKJACK_HAND];
// Fill the Card array with the initial number of cards from the Deck.
for(int i = 0; i < playerCards.length; i++)
playerCards[i] = deck.takeCard();
// Ctor call to pass in the array of cards.
hand[PLAYER] = new BlackJackHand(playerCards);
// Casting to access the subclass method getValue().
playersHand = (BlackJackHand)hand[PLAYER];
// Determine if the Player has BlackJack.
if(playersHand.getValue() == BLACKJACK){
// Player was dealt BlackJack on first Draw.
blackJackFlag = SET;
// Jump to STAY to determine if Dealer has BlackJack as well.
stay();
}
else{
// Display the value of the Player's Hand.
display = "You have " + playersHand.getValue() + ". Hit or Stay?";
}
repaint();
} // End newGame().
//---------------------------------------------------------------------------
/**
Takes the top Card from the Deck and adds it to the Player's Hand. Determines if the Player
has TWENTY-ONE or if the Player busted; and provides the option to “hit” or “stay”.
*/
void hit(){
// Determine if a game is in progress.
if(gameInProgress == false){display = "Click \"New Game\" to start a new game."; repaint(); return;}
// Take the top Card from the Deck.
card = deck.takeCard();
// Add the top Card to the Player's Hand.
hand[PLAYER].addCard(card);
// Determine if the Player has TWENTY-ONE.
if(playersHand.getValue() == TWENTY_ONE)
// Jump to STAY.
stay();
else{
// Determine if the Player Busted.
if(playersHand.isBusted()){
display = "You have Busted! Dealer wins!";
// Increment the tallies.
playerLostTally++; dealerWinTally++;
// Game Over!
gameInProgress = false;
}
else{
// Prompt the user to Hit or Stay.
display = "You have " + playersHand.getValue() + ". Hit or Stay?";
}
}
repaint();
} // End hit().
//---------------------------------------------------------------------------
/**
Generates the Dealer’s Hand and determines the winner of BlackJack.
*/
void stay(){
// Determine if a game is in progress.
if(gameInProgress == false){display = "Click \"New Game\" to start a new game."; repaint(); return;}
// Game will finish.
gameInProgress = false;
// Generate the Dealer’s Hand and instantiate a Card object for the Dealer.
Card[] dealerCards = new Card[INIT_SIZE_BLACKJACK_HAND];
// Fill the Card array with cards from the Deck.
for(int i = 0; i < dealerCards.length; i++)
dealerCards[i] = deck.takeCard();
// Ctor call to pass in the array of cards.
hand[DEALER] = new BlackJackHand(dealerCards);
// Casting to access the subclass method getValue().
dealersHand = (BlackJackHand)hand[DEALER];
// Determine if Dealer has BlackJack on first draw.
if(dealersHand.getValue() == BLACKJACK){
// Determine if the Dealer and Player have BlackJack on first draw.
if(blackJackFlag == SET){
// Reset Flag.
blackJackFlag = DEFAULT;
// Game Over! Increment tie tally.
tieTally++;
display = "Push! Both you and the dealer have BlackJack.";
}
else{
display = "Dealer has BlackJack. Dealer wins!";
// Game Over! Increment the tallies.
dealerWinTally++; playerLostTally++;
}
}
// Player has BlackJack on First draw.
else if(blackJackFlag == SET){
// Reset Flag.
blackJackFlag = DEFAULT;
// Game Over! Increment the tallies.
playerWinTally++; dealerLostTally++;
display = "You win! You have BlackJack!";
}
else{// Determine the winner.
// If the Dealer's Hand is lower than 17, contine to Hit.
while(dealersHand.getValue() >= BLACKJACK_LOW && dealersHand.getValue() < BLACKJACK_HIGH){
// Take the top Card from the Deck.
card = deck.takeCard();
// Add the top Card to the Dealer's Hand.
hand[DEALER].addCard(card);
display = " Dealer has " + dealersHand.getValue() + ".";
repaint();
} // End while.
// Determine if the Dealer Busted.
if(dealersHand.isBusted()){
display = "Dealer has Busted! You have " + playersHand.getValue() + ". You have won!";
// Game Over! Increment the tallies.
playerWinTally++; dealerLostTally++;
}
// Compare the Player and Dealer's Hand.
else if(playersHand.getValue() == dealersHand.getValue()){
display = "Push! Both you and the dealer have " + playersHand.getValue() + ".";
// Game Over! Increment tie tally.
tieTally++;
}
else if(playersHand.getValue() > dealersHand.getValue()){
display = "You have " + playersHand.getValue() + ". Dealer has " + dealersHand.getValue() + ". You have won!";
// Game Over! Increment tallies.
playerWinTally++; dealerLostTally++;
}
else{
display = "Dealer has " + dealersHand.getValue() + ". You have " + playersHand.getValue() + ". Dealer has won!";
// Game Over! Increment tallies.
dealerWinTally++; playerLostTally++;
}
} // End outer else.
repaint();
} // End stay().
//---------------------------------------------------------------------------
/**
Provides the option to reset the running tally of Dealer and Player wins, losses and ties.
*/
void reset(){
if(gameInProgress){display = "You must finish this game before stats can be reset."; repaint(); return;}
playerWinTally = ZERO; dealerWinTally = ZERO; playerLostTally = ZERO; dealerLostTally = ZERO; tieTally = ZERO;
display = "Stats have been reset.";
repaint();
}
//---------------------------------------------------------------------------
/**
Displays the Cards in the Dealer and Player’s Hand, as well as the running tally of wins and losses.
@param g A graphic instance.
*/
public void paint(Graphics g){
super.paint(g);
g.setFont(font);
g.setColor(Color.GREEN);
g.drawString("Dealer's Cards:", 10, 23);
g.drawString("Your Cards:", 10, 153);
g.drawString(display, 10, getSize().height - 10);
g.drawString("Wins: | Player " + playerWinTally + " | Dealer " + dealerWinTally + " |", getSize().width - 180, getSize().height - 10);
// Display two face-down cards for the Dealer.
cardImage = (Image)mapCards.get(1);
g.drawImage(cardImage, 10, 30, null);
g.drawImage(cardImage, 100, 30, null);
// Display Player's Hand.
for(int i = 0; i < hand[PLAYER].getNumberOfCards(); i++){
cardImage = (Image)mapCards.get(hand[PLAYER].getCard(i));
g.drawImage(cardImage, 10 + i * 90, 160, null);
}
// Display Dealer's Hand.
for(int i = 0; i < hand[DEALER].getNumberOfCards(); i++){
cardImage = (Image)mapCards.get(hand[DEALER].getCard(i));
g.drawImage(cardImage, 10 + i * 90, 30, null);
}
} // End paint().
//---------------------------------------------------------------------------
} // End BlackJackGame.
//---------------------------------------------------------------------------
} // End BlackJackApplet.
//---------------------------------------------------------------------------
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.applet.*;
import java.util.*;
import javax.swing.*;
import java.io.*;
import javax.imageio.ImageIO;
//---------------------------------------------------------------------------
/**
A
BlackJackApplet responds to "hit" and "stay", "reset" and "new game" commands, and displays the game's state.
@author: Tommy Flewwelling
@version: 1.00
Creation Date: 2007/07/17
*/
public class BlackJackApplet extends JApplet{
public void init(){
// Instantiate a BlackJackGame object.
BlackJackGame canvas = new BlackJackGame();
// Add a canvas to the center of the Layout.
add(canvas, BorderLayout.CENTER);
// Create Button panel.
JPanel buttonPanel = new JPanel();
// Set background color of Button panel.
buttonPanel.setBackground(Color.BLUE);
// Hit button - create buttons and add them to the Button panel.
JButton hit = new JButton("Hit");
hit.addActionListener(canvas);
buttonPanel.add(hit);
// Stay button.
JButton stay = new JButton("Stay");
stay.addActionListener(canvas);
buttonPanel.add(stay);
// New Game button.
JButton newGame = new JButton("New Game");
newGame.addActionListener(canvas);
buttonPanel.add(newGame);
// Reset button.
JButton reset = new JButton("Reset");
reset.addActionListener(canvas);
buttonPanel.add(reset);
// Add Button Panel to the south.
add(buttonPanel, BorderLayout.SOUTH);
}
//---------------------------------------------------------------------------
/**
A
BlackJackGame object performs all the actions of the game. The Player is given the option to “hit” or “stay”, while the Dealer must “stay” if their Hand is seventeen or greater.
Blackjack wins over all other Hands. If both Player and Dealer have the same Hand, the round
ends in a push(tie). I’ve defined the number of Players to be one for simplicity.
@author: Tommy Flewwelling
@version: 1.00
Creation Date: 2007/07/17
*/
class BlackJackGame extends Canvas implements ActionListener{
//---------------------------------------------------------------------------
// Define the initial number of cards needed for a Hand of BlackJack.
public static final int INIT_SIZE_BLACKJACK_HAND = 2;
// Constants used throughout the program.
public static final int HIT = 0, STAY = 1, ZERO = 0, SET = 1, DEFAULT = -1, PLAYER = 0, DEALER = 1, BLACKJACK = 21, TWENTY_ONE = 21, EMPTY = 0;
// Define the number of Players as one - for simplicity.
public static final int NUMBER_OF_PLAYERS = 1;
// The lowest and highest Hand of BlackJack that can be dealt - used to determine if the Dealer should "Hit" or "Stay".
public static final int BLACKJACK_LOW = 4, BLACKJACK_HIGH = 17;
// Set if Player obtains BlackJack on first draw.
int blackJackFlag = DEFAULT;
// Tally number of rounds played, wins, losses and ties of both Dealer and Player.
public int playerWinTally = ZERO, dealerWinTally = ZERO, playerLostTally = ZERO, dealerLostTally = ZERO, tieTally = ZERO, roundTally = ZERO;
// Note the status of the game.
boolean gameInProgress = false;
// Display message.
String display;
// Font for displaying messages.
Font font;
/** A Card object. */
private Card card;
/** A Deck object. */
private Deck deck;
/** A Hand object. */
private Hand[] hand;
/** A BlackJackHand object for the Player. */
private BlackJackHand playersHand;
/** A BlackJackHand object for the Dealer. */
private BlackJackHand dealersHand;
/** A HashMap Object. */
private HashMap mapCards;
/** An Image object. */
private Image cardImage;
//---------------------------------------------------------------------------
/**
Sets background color, initializes fonts, creates a hashmap and begins the game.
*/
BlackJackGame(){
// Set background color.
setBackground(Color.GREEN.darker().darker());
// Set font.
font = new Font("Serif", Font.BOLD, 14);
// Mapping of Cards to their image.
mapCards = new HashMap();
try{
// Clubs.
mapCards.put(new Card(2,0), ImageIO.read(new java.net.URL(getCodeBase(),"cards/2c.gif")));
mapCards.put(new Card(3,0), ImageIO.read(new java.net.URL(getCodeBase(),"cards/3c.gif")));
mapCards.put(new Card(4,0), ImageIO.read(new java.net.URL(getCodeBase(),"cards/4c.gif")));
mapCards.put(new Card(5,0), ImageIO.read(new java.net.URL(getCodeBase(),"cards/5c.gif")));
mapCards.put(new Card(6,0), ImageIO.read(new java.net.URL(getCodeBase(),"cards/6c.gif")));
mapCards.put(new Card(7,0), ImageIO.read(new java.net.URL(getCodeBase(),"cards/7c.gif")));
mapCards.put(new Card(8,0), ImageIO.read(new java.net.URL(getCodeBase(),"cards/8c.gif")));
mapCards.put(new Card(9,0), ImageIO.read(new java.net.URL(getCodeBase(),"cards/9c.gif")));
mapCards.put(new Card(10,0), ImageIO.read(new java.net.URL(getCodeBase(),"cards/tc.gif")));
mapCards.put(new Card(11,0), ImageIO.read(new java.net.URL(getCodeBase(),"cards/jc.gif")));
mapCards.put(new Card(12,0), ImageIO.read(new java.net.URL(getCodeBase(),"cards/qc.gif")));
mapCards.put(new Card(13,0), ImageIO.read(new java.net.URL(getCodeBase(),"cards/kc.gif")));
mapCards.put(new Card(14,0), ImageIO.read(new java.net.URL(getCodeBase(),"cards/ac.gif")));
// Spades.
mapCards.put(new Card(2,1), ImageIO.read(new java.net.URL(getCodeBase(),"cards/2s.gif")));
mapCards.put(new Card(3,1), ImageIO.read(new java.net.URL(getCodeBase(),"cards/3s.gif")));
mapCards.put(new Card(4,1), ImageIO.read(new java.net.URL(getCodeBase(),"cards/4s.gif")));
mapCards.put(new Card(5,1), ImageIO.read(new java.net.URL(getCodeBase(),"cards/5s.gif")));
mapCards.put(new Card(6,1), ImageIO.read(new java.net.URL(getCodeBase(),"cards/6s.gif")));
mapCards.put(new Card(7,1), ImageIO.read(new java.net.URL(getCodeBase(),"cards/7s.gif")));
mapCards.put(new Card(8,1), ImageIO.read(new java.net.URL(getCodeBase(),"cards/8s.gif")));
mapCards.put(new Card(9,1), ImageIO.read(new java.net.URL(getCodeBase(),"cards/9s.gif")));
mapCards.put(new Card(10,1),ImageIO.read(new java.net.URL(getCodeBase(),"cards/ts.gif")));
mapCards.put(new Card(11,1),ImageIO.read(new java.net.URL(getCodeBase(),"cards/js.gif")));
mapCards.put(new Card(12,1),ImageIO.read(new java.net.URL(getCodeBase(),"cards/qs.gif")));
mapCards.put(new Card(13,1),ImageIO.read(new java.net.URL(getCodeBase(),"cards/ks.gif")));
mapCards.put(new Card(14,1),ImageIO.read(new java.net.URL(getCodeBase(),"cards/as.gif")));
// Hearts.
mapCards.put(new Card(2,2), ImageIO.read(new java.net.URL(getCodeBase(),"cards/2h.gif")));
mapCards.put(new Card(3,2), ImageIO.read(new java.net.URL(getCodeBase(),"cards/3h.gif")));
mapCards.put(new Card(4,2), ImageIO.read(new java.net.URL(getCodeBase(),"cards/4h.gif")));
mapCards.put(new Card(5,2), ImageIO.read(new java.net.URL(getCodeBase(),"cards/5h.gif")));
mapCards.put(new Card(6,2), ImageIO.read(new java.net.URL(getCodeBase(),"cards/6h.gif")));
mapCards.put(new Card(7,2), ImageIO.read(new java.net.URL(getCodeBase(),"cards/7h.gif")));
mapCards.put(new Card(8,2), ImageIO.read(new java.net.URL(getCodeBase(),"cards/8h.gif")));
mapCards.put(new Card(9,2), ImageIO.read(new java.net.URL(getCodeBase(),"cards/9h.gif")));
mapCards.put(new Card(10,2),ImageIO.read(new java.net.URL(getCodeBase(),"cards/th.gif")));
mapCards.put(new Card(11,2),ImageIO.read(new java.net.URL(getCodeBase(),"cards/jh.gif")));
mapCards.put(new Card(12,2),ImageIO.read(new java.net.URL(getCodeBase(),"cards/qh.gif")));
mapCards.put(new Card(13,2),ImageIO.read(new java.net.URL(getCodeBase(),"cards/kh.gif")));
mapCards.put(new Card(14,2),ImageIO.read(new java.net.URL(getCodeBase(),"cards/ah.gif")));
// Dimonds.
mapCards.put(new Card(2,3), ImageIO.read(new java.net.URL(getCodeBase(),"cards/2d.gif")));
mapCards.put(new Card(3,3), ImageIO.read(new java.net.URL(getCodeBase(),"cards/3d.gif")));
mapCards.put(new Card(4,3), ImageIO.read(new java.net.URL(getCodeBase(),"cards/4d.gif")));
mapCards.put(new Card(5,3), ImageIO.read(new java.net.URL(getCodeBase(),"cards/5d.gif")));
mapCards.put(new Card(6,3), ImageIO.read(new java.net.URL(getCodeBase(),"cards/6d.gif")));
mapCards.put(new Card(7,3), ImageIO.read(new java.net.URL(getCodeBase(),"cards/7d.gif")));
mapCards.put(new Card(8,3), ImageIO.read(new java.net.URL(getCodeBase(),"cards/8d.gif")));
mapCards.put(new Card(9,3), ImageIO.read(new java.net.URL(getCodeBase(),"cards/9d.gif")));
mapCards.put(new Card(10,3),ImageIO.read(new java.net.URL(getCodeBase(),"cards/td.gif")));
mapCards.put(new Card(11,3),ImageIO.read(new java.net.URL(getCodeBase(),"cards/jd.gif")));
mapCards.put(new Card(12,3),ImageIO.read(new java.net.URL(getCodeBase(),"cards/qd.gif")));
mapCards.put(new Card(13,3),ImageIO.read(new java.net.URL(getCodeBase(),"cards/kd.gif")));
mapCards.put(new Card(14,3),ImageIO.read(new java.net.URL(getCodeBase(),"cards/ad.gif")));
// Face-down card.
mapCards.put(1,ImageIO.read(new java.net.URL(getCodeBase(),"cards/blueCard.gif")));
// Catch exception if one occurs.
}catch (java.net.MalformedURLException me){System.out.println("Image not found!");
JOptionPane.showMessageDialog(this, "Image not found!");
}catch (IOException e){System.out.println(e.getMessage ());}
// Jump to New Game.
newGame();
}
//---------------------------------------------------------------------------
/**
Respond to button clicks.
@param evt The ActionEvent.
*/
public void actionPerformed(ActionEvent evt){
// Returns the command string associated with the action.
String command = evt.getActionCommand();
if(command.equals("Hit"))
hit();
else if(command.equals("Stay"))
stay();
else if(command.equals("New Game"))
newGame();
else if(command.equals("Reset"))
reset();
}
//---------------------------------------------------------------------------
/**
Generates and shuffles a new deck. Creates the Player’s Hand and determines if the Player
has Blackjack and provides the option to “hit” or “stay”.
*/
void newGame(){
// Determine if a game is in progress.
if(gameInProgress){display = "A game is currently in progress."; repaint(); return;}
// Game in progress.
gameInProgress = true;
// Create the Deck.
deck = new Deck();
// Shuffle the Deck.
deck.shuffle();
// Allocate enough Hands for the Player(one in this case) and the Dealer.
hand = new Hand[NUMBER_OF_PLAYERS + DEALER];
// Instantiate a Card object for the Player.
Card[] playerCards = new Card[INIT_SIZE_BLACKJACK_HAND];
// Fill the Card array with the initial number of cards from the Deck.
for(int i = 0; i < playerCards.length; i++)
playerCards[i] = deck.takeCard();
// Ctor call to pass in the array of cards.
hand[PLAYER] = new BlackJackHand(playerCards);
// Casting to access the subclass method getValue().
playersHand = (BlackJackHand)hand[PLAYER];
// Determine if the Player has BlackJack.
if(playersHand.getValue() == BLACKJACK){
// Player was dealt BlackJack on first Draw.
blackJackFlag = SET;
// Jump to STAY to determine if Dealer has BlackJack as well.
stay();
}
else{
// Display the value of the Player's Hand.
display = "You have " + playersHand.getValue() + ". Hit or Stay?";
}
repaint();
} // End newGame().
//---------------------------------------------------------------------------
/**
Takes the top Card from the Deck and adds it to the Player's Hand. Determines if the Player
has TWENTY-ONE or if the Player busted; and provides the option to “hit” or “stay”.
*/
void hit(){
// Determine if a game is in progress.
if(gameInProgress == false){display = "Click \"New Game\" to start a new game."; repaint(); return;}
// Take the top Card from the Deck.
card = deck.takeCard();
// Add the top Card to the Player's Hand.
hand[PLAYER].addCard(card);
// Determine if the Player has TWENTY-ONE.
if(playersHand.getValue() == TWENTY_ONE)
// Jump to STAY.
stay();
else{
// Determine if the Player Busted.
if(playersHand.isBusted()){
display = "You have Busted! Dealer wins!";
// Increment the tallies.
playerLostTally++; dealerWinTally++;
// Game Over!
gameInProgress = false;
}
else{
// Prompt the user to Hit or Stay.
display = "You have " + playersHand.getValue() + ". Hit or Stay?";
}
}
repaint();
} // End hit().
//---------------------------------------------------------------------------
/**
Generates the Dealer’s Hand and determines the winner of BlackJack.
*/
void stay(){
// Determine if a game is in progress.
if(gameInProgress == false){display = "Click \"New Game\" to start a new game."; repaint(); return;}
// Game will finish.
gameInProgress = false;
// Generate the Dealer’s Hand and instantiate a Card object for the Dealer.
Card[] dealerCards = new Card[INIT_SIZE_BLACKJACK_HAND];
// Fill the Card array with cards from the Deck.
for(int i = 0; i < dealerCards.length; i++)
dealerCards[i] = deck.takeCard();
// Ctor call to pass in the array of cards.
hand[DEALER] = new BlackJackHand(dealerCards);
// Casting to access the subclass method getValue().
dealersHand = (BlackJackHand)hand[DEALER];
// Determine if Dealer has BlackJack on first draw.
if(dealersHand.getValue() == BLACKJACK){
// Determine if the Dealer and Player have BlackJack on first draw.
if(blackJackFlag == SET){
// Reset Flag.
blackJackFlag = DEFAULT;
// Game Over! Increment tie tally.
tieTally++;
display = "Push! Both you and the dealer have BlackJack.";
}
else{
display = "Dealer has BlackJack. Dealer wins!";
// Game Over! Increment the tallies.
dealerWinTally++; playerLostTally++;
}
}
// Player has BlackJack on First draw.
else if(blackJackFlag == SET){
// Reset Flag.
blackJackFlag = DEFAULT;
// Game Over! Increment the tallies.
playerWinTally++; dealerLostTally++;
display = "You win! You have BlackJack!";
}
else{// Determine the winner.
// If the Dealer's Hand is lower than 17, contine to Hit.
while(dealersHand.getValue() >= BLACKJACK_LOW && dealersHand.getValue() < BLACKJACK_HIGH){
// Take the top Card from the Deck.
card = deck.takeCard();
// Add the top Card to the Dealer's Hand.
hand[DEALER].addCard(card);
display = " Dealer has " + dealersHand.getValue() + ".";
repaint();
} // End while.
// Determine if the Dealer Busted.
if(dealersHand.isBusted()){
display = "Dealer has Busted! You have " + playersHand.getValue() + ". You have won!";
// Game Over! Increment the tallies.
playerWinTally++; dealerLostTally++;
}
// Compare the Player and Dealer's Hand.
else if(playersHand.getValue() == dealersHand.getValue()){
display = "Push! Both you and the dealer have " + playersHand.getValue() + ".";
// Game Over! Increment tie tally.
tieTally++;
}
else if(playersHand.getValue() > dealersHand.getValue()){
display = "You have " + playersHand.getValue() + ". Dealer has " + dealersHand.getValue() + ". You have won!";
// Game Over! Increment tallies.
playerWinTally++; dealerLostTally++;
}
else{
display = "Dealer has " + dealersHand.getValue() + ". You have " + playersHand.getValue() + ". Dealer has won!";
// Game Over! Increment tallies.
dealerWinTally++; playerLostTally++;
}
} // End outer else.
repaint();
} // End stay().
//---------------------------------------------------------------------------
/**
Provides the option to reset the running tally of Dealer and Player wins, losses and ties.
*/
void reset(){
if(gameInProgress){display = "You must finish this game before stats can be reset."; repaint(); return;}
playerWinTally = ZERO; dealerWinTally = ZERO; playerLostTally = ZERO; dealerLostTally = ZERO; tieTally = ZERO;
display = "Stats have been reset.";
repaint();
}
//---------------------------------------------------------------------------
/**
Displays the Cards in the Dealer and Player’s Hand, as well as the running tally of wins and losses.
@param g A graphic instance.
*/
public void paint(Graphics g){
super.paint(g);
g.setFont(font);
g.setColor(Color.GREEN);
g.drawString("Dealer's Cards:", 10, 23);
g.drawString("Your Cards:", 10, 153);
g.drawString(display, 10, getSize().height - 10);
g.drawString("Wins: | Player " + playerWinTally + " | Dealer " + dealerWinTally + " |", getSize().width - 180, getSize().height - 10);
// Display two face-down cards for the Dealer.
cardImage = (Image)mapCards.get(1);
g.drawImage(cardImage, 10, 30, null);
g.drawImage(cardImage, 100, 30, null);
// Display Player's Hand.
for(int i = 0; i < hand[PLAYER].getNumberOfCards(); i++){
cardImage = (Image)mapCards.get(hand[PLAYER].getCard(i));
g.drawImage(cardImage, 10 + i * 90, 160, null);
}
// Display Dealer's Hand.
for(int i = 0; i < hand[DEALER].getNumberOfCards(); i++){
cardImage = (Image)mapCards.get(hand[DEALER].getCard(i));
g.drawImage(cardImage, 10 + i * 90, 30, null);
}
} // End paint().
//---------------------------------------------------------------------------
} // End BlackJackGame.
//---------------------------------------------------------------------------
} // End BlackJackApplet.
//---------------------------------------------------------------------------
IllegalTurnException Class
//---------------------------------------------------------------------------
/**
A
to add a card to an already busted hand.
@author: Tommy Flewwelling
@version: 1.00
Creation Date: 2007/06/12
*/
class IllegalTurnException extends RuntimeException{
public IllegalTurnException(){
super("Invalid action - an attempt was made to add a card to an already busted hand.");}
public IllegalTurnException(String message){
super (message);
//System.out.println ("I'm in the IllegalTurnException's constructor.");
}
}
//---------------------------------------------------------------------------
/**
A
IllegalTurnException object represents an exception when an attempt is made to add a card to an already busted hand.
@author: Tommy Flewwelling
@version: 1.00
Creation Date: 2007/06/12
*/
class IllegalTurnException extends RuntimeException{
public IllegalTurnException(){
super("Invalid action - an attempt was made to add a card to an already busted hand.");}
public IllegalTurnException(String message){
super (message);
//System.out.println ("I'm in the IllegalTurnException's constructor.");
}
}
//---------------------------------------------------------------------------
BlackJackHand Class
//---------------------------------------------------------------------------
import java.util.Iterator;
//---------------------------------------------------------------------------
/**
A
is a subclass of
@author: Tommy Flewwelling
@version: 1.00
Creation Date: 2007/07/17
*/
public class BlackJackHand extends Hand
{
//---------------------------------------------------------------------------
/** Creates a new empty
public BlackJackHand(){}
//---------------------------------------------------------------------------
/**
Initializes a
@param cards[] An array of cards in the
@throws IllegalArgumentException when cards remain to be added however the hand's value is already >=21.
*/
public BlackJackHand (Card [] cards) throws IllegalArgumentException {
try{
for(int i = 0; i < cards.length; i++){
this.addCard(cards[i]);}
}catch(IllegalTurnException e)
{String message = "Error constructing BlackJackHand with card array: " + e.getMessage ();
throw new IllegalArgumentException (message);}}
//---------------------------------------------------------------------------
/**
Gets this Hand's BlackJack value.
@return The value of this Hand according to BlackJack rules.
*/
// This is a dynamically generated value.
public int getValue(){
int tally = 0;
int aceCount = 0;
for(Iterator it = this.iterator(); it.hasNext();){
int fv = ((Card)it.next()).getFaceValue();
if(fv <= 10) tally += fv; // Card's face value to 10.
else if (fv != 14) tally += 10; // J, Q, K == 10.
else{
tally += 11; // Ace, value is 11.
// Increment Ace count.
aceCount++;
}
}
// Accommodate for Ace value 1.
while (aceCount > 0 && tally > 21){
tally -= 10; aceCount--;
}
return tally;
}
//---------------------------------------------------------------------------
/**
Indicates whether or not this hand is busted.
@return true If the hand is busted, false otherwise.
*/
public boolean isBusted(){return this.getValue() > 21;}
//---------------------------------------------------------------------------
/**
Adds the card to this hand. Ignores whether the card already
exists in this hand or not. Use contains to determine this.
Note the card will not be added if this hand is 21 or busted.
@see BlackJackHand#isBusted()
@param card The Card to be added.
*/
public void addCard(Card card) throws IllegalTurnException{
if(this.getValue() < 21)
super.addCard(card);
else {String m = "The " + card + " cannot be add, hand value is " + ((this.isBusted ()) ? "busted." : "21.");
throw new IllegalTurnException (m);}
}
//---------------------------------------------------------------------------
}
import java.util.Iterator;
//---------------------------------------------------------------------------
/**
A
BlackJackHand object represents a Hand of cards in the game of Blackjack, which is a subclass of
Hand. @author: Tommy Flewwelling
@version: 1.00
Creation Date: 2007/07/17
*/
public class BlackJackHand extends Hand
{
//---------------------------------------------------------------------------
/** Creates a new empty
BlackJackHand. */public BlackJackHand(){}
//---------------------------------------------------------------------------
/**
Initializes a
BlackJackHand given an array of cards.@param cards[] An array of cards in the
Hand.@throws IllegalArgumentException when cards remain to be added however the hand's value is already >=21.
*/
public BlackJackHand (Card [] cards) throws IllegalArgumentException {
try{
for(int i = 0; i < cards.length; i++){
this.addCard(cards[i]);}
}catch(IllegalTurnException e)
{String message = "Error constructing BlackJackHand with card array: " + e.getMessage ();
throw new IllegalArgumentException (message);}}
//---------------------------------------------------------------------------
/**
Gets this Hand's BlackJack value.
@return The value of this Hand according to BlackJack rules.
*/
// This is a dynamically generated value.
public int getValue(){
int tally = 0;
int aceCount = 0;
for(Iterator it = this.iterator(); it.hasNext();){
int fv = ((Card)it.next()).getFaceValue();
if(fv <= 10) tally += fv; // Card's face value to 10.
else if (fv != 14) tally += 10; // J, Q, K == 10.
else{
tally += 11; // Ace, value is 11.
// Increment Ace count.
aceCount++;
}
}
// Accommodate for Ace value 1.
while (aceCount > 0 && tally > 21){
tally -= 10; aceCount--;
}
return tally;
}
//---------------------------------------------------------------------------
/**
Indicates whether or not this hand is busted.
@return true If the hand is busted, false otherwise.
*/
public boolean isBusted(){return this.getValue() > 21;}
//---------------------------------------------------------------------------
/**
Adds the card to this hand. Ignores whether the card already
exists in this hand or not. Use contains to determine this.
Note the card will not be added if this hand is 21 or busted.
@see BlackJackHand#isBusted()
@param card The Card to be added.
*/
public void addCard(Card card) throws IllegalTurnException{
if(this.getValue() < 21)
super.addCard(card);
else {String m = "The " + card + " cannot be add, hand value is " + ((this.isBusted ()) ? "busted." : "21.");
throw new IllegalTurnException (m);}
}
//---------------------------------------------------------------------------
}
Subscribe to:
Posts (Atom)