public class GameOf21 {
public static void main(String[] args) {
PlayingCard[] cards = new PlayingCard[13];
String suit = "spades";
String[] faces = { "jack", "queen", "king", "ace" };
for(int j = 0; j < 13; j++) {
int value = Math.min(j+2, 10);
if(j == 12) value += 1;
String name = (j < 9) ? String.valueOf(value)
: faces[j-9];
cards[j] = new PlayingCard(value, name + " of " + suit);
}
showCards(cards);
Player player = new Player();
for(int j = 0; j < 5; j++)
player.drawCard(cards[j]);
showCards(player.hand);
int handValue = player.totalHand();
System.out.println("handValue = " + handValue);
}
private static void showCards(PlayingCard[] cards) {
for(int j = 0; j < cards.length; j++) {
System.out.print(cards[j]);
if(j < cards.length-1)
System.out.print(", ");
else
System.out.println();
}
System.out.println("--------------");
}
}
class PlayingCard {
int value;
String name;
public PlayingCard(int value, String name) {
this.value = value;
this.name = name;
}
public int getValue() {
return value;
}
public String getName() {
return name;
}
public String toString() {
return name;
}
}
class Player {
PlayingCard[] hand = new PlayingCard[0];
public Player() {
// nothing to do here...
}
public void drawCard(PlayingCard card) {
int size = hand.length;
PlayingCard[] newHand = new PlayingCard[size+1];
System.arraycopy(hand, 0, newHand, 0, size);
newHand[size] = card;
hand = newHand;
}
public int totalHand() {
int total = 0;
for(int j = 0; j < hand.length; j++) {
PlayingCard card = hand[j];
int value = card.getValue();
if(total + value > 21 && value == 11)
value = 1;
total += value;
}
return total;
}
public void endHand() {
hand = new PlayingCard[0];
}
}