Solved

I need help creating a twoPlayerBlackJack method?

Posted on 2011-09-15
11
386 Views
Last Modified: 2012-05-12
Card class:

public class Card
{
   
    private String rank;//card rank: a number between 2 and 10, or Jack, Queen, King or Ace
    private char suit;//card suit: S,C,H,or D
    private static String[] Ranks={"2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace"};
    private static char[] Suites={'C','H','D','S'};
     
    /**
     * Default constructor: sets card rank to 2 and card suit to H
     */
    public Card()
    {
        rank="2";
        suit='H';
       
    }
   
    /**
     * Class constructor: sets card rank and suit to provided values.
     */
    public Card(String rank, char suit)
    {
        this.rank=rank;
        this.suit=suit;
    }
   
    /**
     * Gets the rank
     */
    public String getRank()
    {
        return rank;
    }
   
    /**
     * Gets the suit
     */
    public char getSuit()
    {
        return suit;
    }
   
    /**
     * Sets the rank
     */
    public void setRank(String rank)
    {
        this.rank=rank;
    }
   
    /**
     * Sets the suit
     */
    public void setSuit(char suit)
    {
        this.suit=suit;
    }
    /**
     * Returns an array of possible card ranks
     */
    public static String[] getPossibleRanks()
    {
        return Ranks;
    }
    /**
     * Returns an array of possible card suits
     */
   
    public static char[] getPossibleSuits()
    {
        return Suites;
    }
   
    /**
     * Returns string representation of the card that looks as follows:
     * 2 of Hearts, 3 of Spades, Jack of Diamonds, etc.
     */
    public String toString()
    {String suitName = "";
        switch (suit){
        case 'H':
         suitName = rank + " of Hearts";
            break;
         case 'S':
            suitName = rank + " of Spades";
             break;
              case 'D':
                suitName = rank + " of Diamonds";
                  break;
                  case 'C':
                   suitName = rank + " of Clubs";


    }
return suitName;
}
}

DeckOfCards class:

mport java.util.Random;
import java.util.ArrayList;
public class DeckOfCards
{
    private ArrayList<Card> deck;
    Random getRandom = new Random();
   
    /**
     * Default constructor creates an Array List of Cards and populates it with 52 different cards
     */
    public DeckOfCards()
    {
        deck = new ArrayList<Card>();
        resetDeckOfCards();
    }

    /**
     * Remove all leftover cards from the ArrayList of Cards called deck
     * Populate an empty deck with 52 new cards...
     */
    public void resetDeckOfCards()
    {
       String[] ranks = Card.getPossibleRanks();
       char[] suites = Card.getPossibleSuits();

  for (int i = 0; i < Card.getPossibleRanks().length ; i++)
       {
           for (int j = 0; j < Card.getPossibleSuits().length; j++)
           {
              deck.add(new Card(ranks, suites[j]));
           }
       }
    }

    /**
     * Remove random card of arraylist of cards and return value from method
     */
    public Card getCard()
    {
       if (deck.isEmpty())
            resetDeckOfCards();
       return deck.remove(getRandom.nextInt(deck.size()));
    }

    /**
     * Return an ArrayList of specified size (i.e. returned cards are being removed from the deck).
     */
    public ArrayList<Card> getHand(int size)
    {
        ArrayList<Card> hand = new ArrayList<Card>();
        for (int i = 0; i < size; i++)
        {
            hand.add(this.getCard());
        }
        return hand;
       
    }

}

TwoPlayerBlackJack class:

import java.util.ArrayList;
import java.util.Scanner;
import java.util.Random;
/**
 * Write a description of class TwoPlayerBlackJack here.
 *
 * @author (your name)
 * @version (a version number or a date)
 */
public class TwoPlayerBlackJack
{
   
    private String rank;
    private ArrayList<Card> blackJack;
    private char suit;
   
    /**
     * Constructor for objects of class TwoPlayerBlackJack
     */
    public TwoPlayerBlackJack()
    {
       String[] ranks = Card.getPossibleRanks();
       char[] suites = Card.getPossibleSuits();
       blackJack = new ArrayList<Card>();
  for (int i = 0; i < Card.getPossibleRanks().length ; i++)
       {
           for (int j = 0; j < Card.getPossibleSuits().length; j++)
           {
              blackJack.add(new Card(ranks, suites[j]));
           }
       }
    }

    /**
     * The method takes an object of class Card and return an integer that represents the value of that card.
     * The values of the cards are determines as follows:
     * two is 2, three is 3, ...., nine is 9, ten is 10,  jacks, queens and kings are all 10.
     * Ace could be either 1 or 11 but for this method we will assume that the value Ace is always 1
     */
    public int getCardValue(Card c){
String rank = c.getRank();

int value = -1;
try {
value = new Integer(rank);
}catch(Exception ex){
if(rank.equals("Ace"))value = 1;
else{ value = 10;

}

}
return value;
}

/**
 * Given a hand cards (i.e. ArrayList of Cards) return an integer value that corresponds to the hand value
 * (i.e. sum of all card values).
 */
public int computeHandValue(ArrayList <Card> hand)
{
 
int sum = 0;
int numAces = 0;

for(Card c: hand){
  int value = getCardValue(c);
   sum += value;
 if(c.getRank().equals("Ace"))
 numAces++;

}
 if(sum<12 && numAces >0)sum += 10;  
   
    return sum;

}

/**
 * Method display hand value display the value of each card followed by the hand value
 */
public void printHandValue(ArrayList <Card> hand)
{
    System.out.println(computeHandValue(hand));
}

/**
 * Method that takes two Array Lists of Cards (i.e. two card hands) and determines the winner
 * of the BlackJack game.
 * 1 – the first hand won the game
 * 0 – nobody won, it is a push
 * -1 – the first hand lost the game
 */
public int isWinner(ArrayList <Card> hand01, ArrayList <Card> hand02)
{

if(computeHandValue(hand01) > 21) return -1;

if(computeHandValue(hand02)  > 21) return 1;

if(computeHandValue(hand01) > computeHandValue(hand02)) return 1;
else  if(computeHandValue(hand01) == computeHandValue(hand02)) return 0;
else return -1;
}  

/**
 * Method that returns true if players would like to play another game, and false otherwise.
 */


public boolean toContinue()
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Would you like to play again? Answer yes or no");
String line = keyboard.nextLine();
if(line.trim().toLowerCase().equals("no"))
return false;
return true;
}

/**
 * Displays the following information: first hand, second hand, and the outcome of the game (i.e. which hand won)
 * 1. Create and initialize a new object of class DeckOfCards
 * 2. While method toContinue returns true repeat the following steps:
 * 3. Generate two random numbers: size01 and size02, values between 3 and 10
 * 4. Get two hands of cards one of size size01 and another of size size02
 * 5. Display the following info.
 * (a) first hand info
 * (b) second hand info
 * (c) outcome of the game(i.e. which hand won)
 */
public void twoPlayerBlackJack()
{
int size01,size02;
DeckOfCards myDeck = new DeckOfCards();
while(toContinue()==true)
{
Random generator = new Random();
size01= generator.nextInt();
size02 = generator.nextInt();
printHandValue();
isWinner();
}

}
}
0
Comment
Question by:ryanbecker24
  • 7
  • 4
11 Comments
 
LVL 47

Expert Comment

by:for_yan
ID: 36544701


I don't see a method which creates your Hand - arbitrarily select Cards form the deck - dp you have such method - to create Hands ?
0
 

Author Comment

by:ryanbecker24
ID: 36544730
I don't know. I am just following the methods that my instructor told us to write. I don't think I am allowed to anything different.
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36544800

You don' need to write ==true for sure (I corrected this part below).

Now think - your Hand is ArrayList of cards - so first you need t create the ArrayList  for each player
and then drwa cards from the deck - and then how many tim,es you draw - thios is
the main point odfstratgy in black jack - ok instead of it you just drwa
size 01 for oner hand and size02 cards for the other hand - but you still have to have the mthod to draw
card from the deck and this method you should call siz01 for fisrt hand and size02 for the second hand

When you end drawing the cards on both hands then you can compare
so this method is still a lot to do.


public void twoPlayerBlackJack()

{
int size01,size02;
DeckOfCards myDeck = new DeckOfCards();
while(toContinue())
{
Random generator = new Random();
size01= generator.nextInt();
size02 = generator.nextInt();
printHandValue();
isWinner();
}

}

Open in new window

0
 
LVL 47

Expert Comment

by:for_yan
ID: 36544888
So you can use this method to draw cards - but you need to put it in class DeckOfCards
and then you need to create instance of this class and draw cards form it and aadd them to each of your hands
Try doing it - I'll then correct.

  public Card drawFromDeck()
	    {
	        Random generator = new Random();
	        int index= generator.nextInt( cards.size() );
	        return cards.remove(index);
	    }
	 

Open in new window

0
 

Author Comment

by:ryanbecker24
ID: 36545072
Is there another way besides creating a seperate method such as calling other methods?
0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 47

Expert Comment

by:for_yan
ID: 36545136
well, insetad of calling method you can put the code inside this method - but then you ned to do it
every time you draw a card or to have a loop - why not haveing such method - makes sense to jhave it
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36545399
Actually now that I pasted your code into my IDE I found some usweful methods in there. So we camnn make this method
0
 
LVL 47

Accepted Solution

by:
for_yan earned 500 total points
ID: 36545455
Should be something like that:

So what s it that you don;t understand that you cannot do it yourself?

Exaoplain me what is it you don;t unsderatsn adfter all waht we went through - and
you should be able to do it yourself.

Also post your code between the code tags , like I am doing and
and sepatartely each public class - it will simplify even looking at it
public void twoPlayerBlackJack()
{
int size01,size02;
DeckOfCards myDeck = new DeckOfCards();
while(toContinue())
{
Random generator = new Random();
size01= generator.nextInt(8);
ArrayList<Card> hand1 = myDeck.getHand(size01+3);   
size02 = generator.nextInt(8);
    ArrayList<Card> hand2 = myDeck.getHand(size02+3);  
printHandValue(hand1);
printHandValue(hand2);    
System.out.println(isWinner(hand1, hand2));
}

}

Open in new window

0
 

Author Comment

by:ryanbecker24
ID: 36550043
Thank you for all your help.
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36550049
You are always welcome.
0
 

Author Closing Comment

by:ryanbecker24
ID: 36550051
Thanks again
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

The purpose of this article is to demonstrate how we can use conditional statements using Python.
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now