Saturday, August 18, 2007

BlackJackHand Class

//---------------------------------------------------------------------------
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);}
}
//---------------------------------------------------------------------------
}

No comments: