Saturday, August 18, 2007

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

No comments: