Problem with for loop stopping while checking Poker Hand - java

I am creating a game of texas hold 'em, if you know poker it's simple enough.
I've working on a SevenCardHand class that basically takes an ArrayList of 7 cards in the constructor. I am creating algorithms for to find the rank of a 7 card hand (whether it is a flush, straight, pair, three of a kind ...)
But the odds of some hands happening are very low, so to test this I want to automatically deal a whole bunch of hands. So I am looping through creating new SevenCardHands and printing whether or not they are a flush (is the one I'm testing right now)
The problem is that it won't let me create more than 7 hands with that for loop. The program doesn't terminate, but it doesn't make any more progress. No matter what I've done it won't make more than seven before freezing.
Here is the code from my Card, DeckOfCards, HoldEmDriver, and SevenCardHand classes
Class HoldEmDriver.java
import java.util.ArrayList;
import java.util.Scanner;
public class HoldEmDriver {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
DeckOfCards theDeck = new DeckOfCards();
TableCards table = new TableCards();
SevenCardHand seven = new SevenCardHand();
ArrayList<Card> cards = new ArrayList();
for(int j=0; j<7; j++) {
cards.clear();
for(int i=0; i<7; i++) {
cards.add(theDeck.dealCard());
}
seven = new SevenCardHand(cards);
System.out.println(""+seven+seven.hasFlush());
}
public enum Card {
ACEOFSPADES(1, "Spades"),
TWOOFSPADES(2, "Spades"),
THREEOFSPADES(3, "Spades"),
FOUROFSPADES(4, "Spades"),
FIVEOFSPADES(5, "Spades"),
SIXOFSPADES(6, "Spades"),
SEVENOFSPADES(7, "Spades"),
EIGHTOFSPADES(8, "Spades"),
NINEOFSPADES(9, "Spades"),
TENOFSPADES(10, "Spades"),
JACKOFSPADES(11, "Spades"),
QUEENOFSPADES(12, "Spades"),
KINGOFSPADES(13, "Spades"),
ACEOFCLUBS(1, "Clubs"),
TWOOFCLUBS(2, "Clubs"),
THREEOFCLUBS(3, "Clubs"),
FOUROFCLUBS(4, "Clubs"),
FIVEOFCLUBS(5, "Clubs"),
SIXOFCLUBS(6, "Clubs"),
SEVENOFCLUBS(7, "Clubs"),
EIGHTOFCLUBS(8, "Clubs"),
NINEOFCLUBS(9, "Clubs"),
TENOFCLUBS(10, "Clubs"),
JACKOFCLUBS(11, "Clubs"),
QUEENOFCLUBS(12, "Clubs"),
KINGOFCLUBS(13, "Clubs"),
ACEOFDIAMONDS(1, "Diamonds"),
TWOOFDIAMONDS(2, "Diamonds"),
THREEOFDIAMONDS(3, "Diamonds"),
FOUROFDIAMONDS(4, "Diamonds"),
FIVEOFDIAMONDS(5, "Diamonds"),
SIXOFDIAMONDS(6, "Diamonds"),
SEVENOFDIAMONDS(7, "Diamonds"),
EIGHTOFDIAMONDS(8, "Diamonds"),
NINEOFDIAMONDS(9, "Diamonds"),
TENOFDIAMONDS(10, "Diamonds"),
JACKOFDIAMONDS(11, "Diamonds"),
QUEENOFDIAMONDS(12, "Diamonds"),
KINGOFDIAMONDS(13, "Diamonds"),
ACEOFHEARTS(1, "Hearts"),
TWOOFHEARTS(2, "Hearts"),
THREEOFHEARTS(3, "Hearts"),
FOUROFHEARTS(4, "Hearts"),
FIVEOFHEARTS(5, "Hearts"),
SIXOFHEARTS(6, "Hearts"),
SEVENOFHEARTS(7, "Hearts"),
EIGHTOFHEARTS(8, "Hearts"),
NINEOFHEARTS(9, "Hearts"),
TENOFHEARTS(10, "Hearts"),
JACKOFHEARTS(11, "Hearts"),
QUEENOFHEARTS(12, "Hearts"),
KINGOFHEARTS(13, "Hearts");
/**The value of the card Ace-King */
private int cardValue;
/** The suit of the card SCDM */
private String cardSuit;
/**
* Creates a card object with a suit and value
* #param cardValue the cards value
* #param cardSuit the cards suit
*/
private Card(int cardValue, String cardSuit) {
this.cardValue = cardValue;
this.cardSuit = cardSuit;
}
/** Checks if this card is the same card as other
* #param other Another card
* #return True if the same, false otherwise
*/
public boolean isSameCard(Card other) {
if(other.cardValue == cardValue && cardSuit.equals(other.cardSuit)) {
return true;
} return false;
}
/**
*
* #return This cards value Ace-King
*/
public int getCardValue() {
return cardValue;
}
/**
* Gets this cards suit
* #return The card's suit
*/
public String getCardSuit() {
return cardSuit;
}
/**
* Checks if two cards have the same suit
* #param other The other card
* #return True if same suit, false otherwise
*/
public boolean isSameSuit(Card other) {
if(this.cardSuit.equals(other.cardSuit)) {
return true;
} return false;
}
/**
* Checks if a card is followed by another card
* 2 followed by 3, 10 followed by Jack
* #param other The card to be compared with
* #return True if other's cardValue is 1 higher than this card
* False otherwise
*/
public boolean isFollowedBy(Card other) {
if(this.cardValue==other.cardValue-1) {
return true;
}
return false;
}
/**
* Checks if a card has the same value as another card
* #param other The card to compare with
* #return True if same value, false otherwise
*/
public boolean isSameValue(Card other) {
if(this.cardValue==other.cardValue) {
return true;
}
return false;
}
/**
* Returns the card in readable format
* Ace of Hearts
* 7 of Clubs
*
*/
public String toString() {
String card = "";
if(cardValue == 1) {
card = card + "Ace ";
} else if(cardValue == 11) {
card = card + "Jack ";
} else if(cardValue == 12) {
card = card + "Queen ";
} else if(cardValue == 13) {
card = card + "King ";
} else {
card = card + cardValue+" ";
}
if(cardSuit.equals("Spades")) {
card = card + "of Spades";
} else if(cardSuit.equals("Clubs")) {
card = card + "of Clubs";
} else if(cardSuit.equals("Hearts")) {
card = card + "of Hearts";
} else if(cardSuit.equals("Diamonds")) {
card = card + "of Diamonds";
}
return card;
}
}
Class DeckOfCards.java
import java.util.ArrayList;
import java.util.Random;
public class DeckOfCards {
private ArrayList<Card> dealtCards= new ArrayList();
private Random random = new Random();
/**
* Makes a Deck with no cards yet dealt
*/
public DeckOfCards() {
}
/**
* Deals a random card from the deck that hasn't been
* dealt already, and adds that card to dealtCards
* #return A unique Card object randomly chosen
*/
public Card dealCard() {
Card newCard = Card.values()[random.nextInt(52)];
while(isAlreadyDealt(newCard)) {
newCard = Card.values()[random.nextInt(52)];
}
dealtCards.add(newCard);
return newCard;
}
/**
* Checks if a card has already been dealt
* #param theCard The card to check
* #return True if the card has been dealt, otherwise false
*/
public boolean isAlreadyDealt(Card theCard) {
boolean isDealt = false;
for(int i=0; i<dealtCards.size(); i++) {
if (theCard.isSameCard(dealtCards.get(i))) {
return true;
}
}
return false;
}
}
Class SevenCardHand.java
import java.util.ArrayList;
public class SevenCardHand {
ArrayList<Card> allCards = new ArrayList();
public SevenCardHand(ArrayList<Card> holeCards, ArrayList<Card> tableCards) {
if(holeCards.size()!=2 || tableCards.size()!=5) {
throw new IllegalArgumentException();
}
allCards.addAll(holeCards);
allCards.addAll(tableCards);
allCards.sort(new CardComparator());
}
public SevenCardHand() {
}
public SevenCardHand(ArrayList<Card> sevenCards) {
if(sevenCards.size()!=7) {
throw new IllegalArgumentException();
}
allCards.addAll(sevenCards);
allCards.sort(new CardComparator());
}
public ArrayList<Card> getAllCards(){
return allCards;
}
public String toString() {
allCards.sort(new CardComparator());
return ""+allCards;
}
public boolean hasRoyalFlush() {
}
public boolean hasStraightFlush() {
}
public boolean hasFourOfAKind() {
}
public boolean hasFullHouse() {
}
public boolean hasFlush() {
int clubs = 0;
int spades = 0;
int hearts = 0;
int diamonds = 0;
for(Card current: allCards) {
if(current.getCardSuit().equals("Spades")) {
spades = spades + 1;
} else if(current.getCardSuit().equals("Clubs")) {
clubs = clubs + 1;
} else if(current.getCardSuit().equals("Hearts")) {
hearts = hearts + 1;
} else if(current.getCardSuit().equals("Diamonds")) {
diamonds = diamonds + 1;
}
}
if(clubs>4 || spades>4 || hearts>4 || diamonds>4) {
return true;
}
return false;
}
public boolean hasStraight() {
int cardsInRow = 1;
int lastInStraight = allCards.get(0).getCardValue();
for(int i=1; i<allCards.size(); i++) {
if(allCards.get(i).getCardValue()==(lastInStraight+1)) {
cardsInRow = cardsInRow + 1;
lastInStraight = lastInStraight+1;
} else if(allCards.get(i).getCardValue()!=lastInStraight) {
cardsInRow = 1;
lastInStraight = allCards.get(i).getCardValue();
}
if(lastInStraight == 13 && cardsInRow>3) {
if(allCards.get(0).getCardValue()==1) {
return true;
}
}
if (cardsInRow >4) {
return true;
}
}
return false;
}
public boolean hasThreeOfAKind() {
for(int i=0; i<allCards.size()-2; i++) {
if(allCards.get(i).isSameValue(allCards.get(i+1))) {
if(allCards.get(i).isSameValue(allCards.get(i+2))) {
return true;
}
}
}
return false;
}
public boolean hasTwoPair() {
int numberOfPairs = 0;
int valueOfFirstPair = 0;
for(int i=0; i<allCards.size()-1; i++) {
if(allCards.get(i).isSameValue(allCards.get(i+1))) {
if(allCards.get(i).getCardValue()!=valueOfFirstPair) {
numberOfPairs = numberOfPairs + 1;
valueOfFirstPair = allCards.get(i).getCardValue();
}
}
if(numberOfPairs>1) {
return true;
}
}
return false;
}
public boolean hasPair() {
for(int i=0; i<allCards.size()-1; i++) {
if(allCards.get(i).isSameValue(allCards.get(i+1))) {
return true;
}
}
return false;
}
}

I'm not entirely sure why you're using a double-for loop to do this if what you're trying to find are the odds that someone has a flush in a seven-card hand. From what I can tell, the outer loop is what's giving you trouble here, because it's only asking for a new 7-card hand 7 times. To increase your sample size, I might try something like:
int count = 0;
int not_flush = 0;
int is_flush = 0;
while (count < 1000) {
cards.clear();
for(int i=0; i<7; i++) {
cards.add(theDeck.dealCard());
}
seven = new SevenCardHand(cards);
if (seven.hasFlush()) {
is_flush++;
}
else {
not_flush++;
}
count++;
}
float result = (float)is_flush/(float)not_flush;

Related

Cannot get card/deck object program to work

this is my first time posting on the forum and I'm not entirely sure if my question is valid, but I will try to be specific and follow the guideline. In following the guidelines, this is a question based around a class assignment. This assignment is to take code that creates a 'deck' object that represents a deck of cards and add several features. I am currently stuck in the process.
My issue lies within this code:
public class SilasAlmgrenS6L1CardCreate {
public static void main(String args[]) {
Deck d = new Deck();
d.shuffle();
Hand f = new Hand(d); //Returns error 'Hand cannot be resolved to a type'
}
public static class Deck {
Card[] cardArray = new Card[52];
Deck() { //constructor
int suits = 4;
int cardType = 13;
int cardCount = 0;
for (int i = 1; i <= suits; i++)
for (int j = 1; j <= cardType; j++) {
cardArray[cardCount] = new Card(i, j);
cardCount++;
} //End loop
} //End deck() constructor
////////////////////////////////////////////////////////
//My code starts here
public class Hand {
Hand(Deck a) {
Card[] Hand = {a.cardArray[0], a.cardArray[1], a.cardArray[2], a.cardArray[3], a.cardArray[4]};
Card[] playerHand = {Hand[0], Hand[1]};
System.out.println("You have " + playerHand[0] + " and " + playerHand[1] );
} //End hand constructor
} //End hand class
public void shuffle() {
//Runs loop for the length of the deck
for(int i = 0; i < cardArray.length; i++) {
int num = (int) (Math.random() * (51 - 0)) + 0; //Creates a random number between 0 and 51; used to shuffle
Card placeHolder = cardArray[i]; //Picks a place holder card from the deck
cardArray[i] = cardArray[num]; //Picks two random cards and make them equal
cardArray[num] = placeHolder; //Assigns one of the duplicate cards to the placeholder value
} //End for
} //End shuffle
//And ends here
/////////////////////////////////////////////////
public void print() {
for (int i = 0; i < cardArray.length; i++)
System.out.println(cardArray[i]);
} //End print loop
} //End print class
public static class Card {
String suit, name;
int points;
Card(int n1, int n2) {
suit = getSuit(n1);
name = getName(n2);
points = getPoints(name);
} //End card class
public String toString() {
return "The " + name + " of " + suit;
} //End toString
public String getName(int i) {
if (i == 1) return "Ace";
if (i == 2) return "Two";
if (i == 3) return "Three";
if (i == 4) return "Four";
if (i == 5) return "Five";
if (i == 6) return "Six";
if (i == 7) return "Seven";
if (i == 8) return "Eight";
if (i == 9) return "Nine";
if (i == 10) return "Ten";
if (i == 11) return "Jack";
if (i == 12) return "Queen";
if (i == 13) return "King";
return "error";
} //End getName String
public int getPoints(String n) {
if (n == "Jack" || n == "Queen" || n == "King" || n == "Ten")
return 10;
if (n == "Two")
return 2;
if (n == "Three")
return 3;
if (n == "Four")
return 4;
if (n == "Five")
return 5;
if (n == "Six")
return 6;
if (n == "Seven")
return 7;
if (n == "Eight")
return 8;
if (n == "Nine")
return 9;
if (n == "Ace")
return 11;
return -1;
} //End int getPoints
public String getSuit(int i) {
if (i == 1) return "Diamonds";
if (i == 2) return "Clubs";
if (i == 3) return "Spades";
if (i == 4) return "Hearts";
return "error";
} //End getSuit String
} //End Deck class
}
The majority of this program was already provided with the assignment, but we are to add several features. The first of these features was a shuffle method, which I was able to do. In the next feature we are to create a 'Hand' class that deals a hand of cards to the user and calculate how many points they have, as if it were a game of blackjack.
This is the exact wording of this step is:
'Add a Hand Class that contains an array of 5 Card references. Have the program Deal the Hand two cards and display them for the user. Tell the user how many points they have and ask them if they would like another card or not. Continue to allow the player to add cards until they reach 5 cards or the total is greater than 21.'
I have ran through several ways that I felt I could create this class, but none seem to be working. This current iteration is as close as I've gotten. I am currently stumped, however. My issues are; I don't know why I'm getting the type error when I try to use the Hand class and I have no idea how to implement the getPoints() method. There are several steps following the creation of the Hand class, but I am sure I can get through them if I can figure out how to make this class work. I'm on the brink of punching a hole in my wall, so any help with fixing this code would be absolutely appreciated.
The first problem is that your Hand class is a subclass of your static Deck class. This way you can not use it in your main method, because that is not the enclosing class.
EDIT
So, I went a little overboard here. Hope it makes sense to you.
First of all, we have your main class. I renamed it for the sake of not wanting to type that long name. I added your Handand Deck objects as variables, since neither the Hand belongs to the Deck or the other way around, but they both are part of the Main class, let's refer to it as the game.
You start by shuffling the deck. When you have the deck, you can get a random card. This is provided by the deck. (I will come to that method shortly).
As soon as you have a hand, you can show the user the amount of points they have and ask them if they would like an extra card (if numberOfPoints < 22 and numberOfCards < 5). If they do want an extra card, ask the deck for a random card and add it to the hand. Go on until any of the boundaries are met.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class CardExample {
private Hand playHand;
private Deck playDeck;
private Scanner reader = new Scanner(System.in); // Reading from System.in
public static void main(String args[]) {
new CardExample().play();
}
public void play(){
playDeck = new Deck();
playDeck.shuffle();
Card firstCard = playDeck.getRandomCard();
Card secondCard = playDeck.getRandomCard();
List<Card> startCards = new ArrayList<>();
startCards.add(firstCard);
startCards.add(secondCard);
playHand = new Hand(startCards);
requestInput();
}
private void requestInput(){
System.out.println("You have " + playHand.getPoints() + " points");
System.out.println("New card? (Y/N)");
String input = reader.next();
if(input.equalsIgnoreCase("y")){
Card newCard = playDeck.getRandomCard();
playHand.addCard(newCard);
if(playHand.getNumberOfCards() < 5 && playHand.getPoints() < 22) {
requestInput();
}else if(playHand.getPoints() >= 22){
System.out.println("You have " + playHand.getPoints() + "points. You're dead, sorry.");
reader.close();
} else{
System.out.println("You have 5 cards, that's the max");
reader.close();
}
}else{
System.out.println("Your score is " + playHand.getPoints() + " points");
reader.close();
}
}
}
Deck class
public class Deck {
private Card[] cardArray = new Card[52];
private int currentIndex = 0;
public Deck() { //constructor
int suits = 4;
int cardType = 13;
int cardCount = 0;
for (int i = 1; i <= suits; i++)
for (int j = 1; j <= cardType; j++) {
cardArray[cardCount] = new Card(i, j);
cardCount++;
} //End loop
}
public void shuffle() {
//Runs loop for the length of the deck
for(int i = 0; i < cardArray.length; i++) {
int num = (int) (Math.random() * (51 - 0)) + 0; //Creates a random number between 0 and 51; used to shuffle
Card placeHolder = cardArray[i]; //Picks a place holder card from the deck
cardArray[i] = cardArray[num]; //Picks two random cards and make them equal
cardArray[num] = placeHolder; //Assigns one of the duplicate cards to the placeholder value
} //End for
} //End shuffle
public Card[] getCardArray() {
return cardArray;
}
public Card getRandomCard(){
Card nextCard = cardArray[currentIndex];
currentIndex += 1;
return nextCard;
}
//And ends here
/////////////////////////////////////////////////
public void print() {
for (int i = 0; i < cardArray.length; i++)
System.out.println(cardArray[i]);
} //End print loop
}
Hand class
addCard updates points so that whenever getting numberOfCards or points, right value is returned
import java.util.ArrayList;
import java.util.List;
public class Hand {
private int points = 0;
private int numberOfCards = 0;
private List<Card> hand = new ArrayList<>();
public Hand(List<Card> cards) {
hand.addAll(cards);
numberOfCards += cards.size();
for(Card card: cards){
points += card.points;
}
} //End hand constructor
public void addCard(Card card){
hand.add(card);
points += card.points;
numberOfCards += 1;
}
public int getNumberOfCards() {
return numberOfCards;
}
public int getPoints() {
return points;
}
}
Card class (unchanged, but seperate file)
public class Card {
String suit, name;
int points;
Card(int n1, int n2) {
suit = getSuit(n1);
name = getName(n2);
points = getPoints(name);
} //End card class
public String toString() {
return "The " + name + " of " + suit;
} //End toString
public String getName(int i) {
if (i == 1) return "Ace";
if (i == 2) return "Two";
if (i == 3) return "Three";
if (i == 4) return "Four";
if (i == 5) return "Five";
if (i == 6) return "Six";
if (i == 7) return "Seven";
if (i == 8) return "Eight";
if (i == 9) return "Nine";
if (i == 10) return "Ten";
if (i == 11) return "Jack";
if (i == 12) return "Queen";
if (i == 13) return "King";
return "error";
} //End getName String
public int getPoints(String n) {
if (n == "Jack" || n == "Queen" || n == "King" || n == "Ten")
return 10;
if (n == "Two")
return 2;
if (n == "Three")
return 3;
if (n == "Four")
return 4;
if (n == "Five")
return 5;
if (n == "Six")
return 6;
if (n == "Seven")
return 7;
if (n == "Eight")
return 8;
if (n == "Nine")
return 9;
if (n == "Ace")
return 11;
return -1;
} //End int getPoints
public String getSuit(int i) {
if (i == 1) return "Diamonds";
if (i == 2) return "Clubs";
if (i == 3) return "Spades";
if (i == 4) return "Hearts";
return "error";
} //End getSuit String
} //End Deck class

CardPile Index Out of bounds

I'm currently trying to convert my code to ArrayList and I can't seem to make it work. I'm running the whole program and it tells me Index out bounds. I'm sure I forgot to add the size of the array for the cards, but I don't know how to add it. Thanks for the help!
Edit: The error I get is at the bottom. Also, it tells me to go to the removeTop method. It looks fine there.
import java.util.Random;
import java.util.List;
import java.util.ArrayList;
public class CardPile {
private ArrayList<Card> cards = new ArrayList<Card>();
private static Random r = new Random(1);
public void addToBottom(Card c) {
if (this.cards.size() == 52) {
System.out.println("The CardPile is full. You cannot add any more Card objects.");
}
this.cards.add(c);
}
public Card removeCard(Card c) {
if (this.cards.contains(c)) {
this.cards.remove(c);
}
return null;
}
public Card removeTop() {
return this.cards.remove(0);
}
public int searchValue(int value) {
int count = 0,
for (int i = 0;i < this.cards.size();i++) {
if (this.cards.get(i).getValue() == value) {
count++;
}
}
//System.out.println("Count = "+count);
return count;
}
public Card[] removeAll(int value)
//System.out.println("(removeAll) cards ="+ cards);
int count = searchValue(value);
Card[] removed = new Card[count];
int deletedCount = 0;
int i = 0;
while (deletedCount < count) {
if (this.cards.get(i).getValue() == value) {
removed[deletedCount] = this.cards.remove(i);
deletedCount++;
} else {
i++;
}
}
return removed;
}
public int getNumberCards() {
return this.cards.size();
}
public String toString() {
if (this.cards.isEmpty()) {
return "";
}
String builder = "";
for (int i = 0;i < this.cards.size() - 1;i++) {
builder = builder + this.cards.get(i) + ", ";
}
builder = builder + this.cards.get(this.cards.size() - 1);
return builder;
}
public void shuffle() {
if (this.cards.isEmpty()) {
return;
}
for (int count = 0; count < 100000;count++) {
int i = r.nextInt(this.cards.size());
int j = r.nextInt(this.cards.size());
Card temp = this.cards.get(i);
this.cards.set(i, this.cards.get(j));
this.cards.set(j, temp);
}
}
public static CardPile makeFullDeck() {
CardPile deck = new CardPile();
for (int suit = 0;suit < 4;suit++) {
for (int value = 1; value <= 13;value++) {
deck.addToBottom(new Card(suit, value));
}
}
deck.shuffle();
return deck;
}
}
**Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.remove(ArrayList.java:492)
at CardPile.removeTop(CardPile.java:40)
at GoFish.dealCards(GoFish.java:112)
at GoFish.main(GoFish.java:13)**
EDIT:
This is the Player class:
public class Player {
private boolean[] books;
private CardPile pile;
private static int MAXIMUM_VALUE_CARD = 13;
public Player()
{
this.pile = new CardPile();
this.books = new boolean[13]; //by default all are false
}
public boolean hasCard(int value)
{
return this.pile.searchValue(value) > 0;
}
public Card[] removeAll(int value)
{
return this.pile.removeAll(value);
}
public void addAll(Card[] cards)
{
for (int i = 0; i < cards.length; i++)
{
this.pile.addToBottom(cards[i]);
}
}
//optional additional method
public void addCard(Card card)
{
this.pile.addToBottom(card);
}
public int getNumberCards()
{
return this.pile.getNumberCards();
}
public int countBooks()
{
int count = 0;
for (int i = 0; i < MAXIMUM_VALUE_CARD; i++)
{
if (books[i])
{
count++;
}
}
return count;
}
public void addBook(int value)
{
this.books[value - 1] = true;
}
public void printHand()
{
System.out.println("Player's hand is " + this.pile);
}
}
And this is the GoFish class:
import java.util.Scanner;
public class GoFish {
private static Scanner reader;
public static void main(String[] args)
{
System.out.println("How many players?");
reader = new Scanner(System.in);
int numberPlayers = reader.nextInt();
Player[] players = createPlayersArray(numberPlayers);
int currentTurn = 0;
CardPile deck = CardPile.makeFullDeck();
dealCards(deck, players);
int maximumRetries = 2;
int numRetries = 0;
while(deck.getNumberCards() > 0 && players[currentTurn].getNumberCards() > 0)
{
updateBooks(players[currentTurn]);
if (numRetries == maximumRetries)
{
numRetries = 0;
currentTurn++;
if (currentTurn == numberPlayers)
{
currentTurn = 0;
}
}
System.out.println("Player " + currentTurn + ", here is your hand. What card would you like to ask for?");
players[currentTurn].printHand();
int queryCard = reader.nextInt();
System.out.println("And from whom would you like to get it from?");
int queryPlayer = reader.nextInt();
if (queryCard < 1 || queryCard > 13 || queryPlayer < 0 || queryPlayer >= numberPlayers || queryPlayer == currentTurn)
{
System.out.println("Invalid entries. Please retry");
numRetries++;
}
else
{
numRetries = 0;
boolean hasCard = players[queryPlayer].hasCard(queryCard);
if (hasCard)
{
System.out.println("Cards found!");
Card[] removed = players[queryPlayer].removeAll(queryCard);
players[currentTurn].addAll(removed);
}
else
{
System.out.println("Go fish!");
Card top = deck.removeTop();
System.out.println("You drew " + top);
players[currentTurn].addCard(top);
//check to make sure this extra card didn't form a book
//Note this could happen even if it doesn't match the card they were asking about
updateBooks(players[currentTurn]);
if (top.getValue() == queryCard)
{
System.out.println("You successfully went fishing!");
}
else
{
currentTurn++;
if (currentTurn == numberPlayers)
{
currentTurn = 0;
}
}
}
}
}
//calculate the winner now
int maxPlayer = 0;
int maxPlayerBooks = players[0].countBooks();
for (int i = 1; i < numberPlayers; i++)
{
int currentBooks = players[i].countBooks();
if (currentBooks > maxPlayerBooks)
{
maxPlayer = i;
maxPlayerBooks = currentBooks;
}
}
System.out.println("Congratulations! Player " + maxPlayer + " you have won the game by accumulating " + maxPlayerBooks + " books!");
}
private static Player[] createPlayersArray(int numPlayers)
{
Player[] players = new Player[numPlayers];
for (int i = 0; i < numPlayers; i++)
{
players[i] = new Player();
}
return players;
}
private static void dealCards(CardPile deck, Player[] players)
{
final int NUMBER_CARDS_PER_PLAYER = 7;
for (int i = 0; i < NUMBER_CARDS_PER_PLAYER * players.length; i++)
{
Card next = deck.removeTop();
players[i % players.length].addCard(next);
}
}
private static void updateBooks(Player player)
{
for (int i = 1; i <= 13; i++)
{
//alternative option would be to modify the hasCard method to return an int instead of boolean. Then we could just count (this is probably better design)
Card[] valued = player.removeAll(i);
if (valued.length == 4)
{
player.addBook(i);
}
else
{
player.addAll(valued);
}
}
}
}

Way to reset card game?

I'm making a game similar to solitaire, and when the user recognizes they have lost I have a button to reset the game. Currently I'm unsure how I can reset the game. I know ill have to make a new deck and clear my array to recreate everything as if the game was starting for the first time, but I don't know how to do this. How can I reset my game when a user presses reset?
/**
* This is a class that tests the Deck class.
*/
public class DeckTester {
/**
* The main method in this class checks the Deck operations for consistency.
* #param args is not used.
*/
public static void main(String[] args) {
Board board = new Board();
board.startGame();
}
}
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* The Deck class represents a shuffled deck of cards.
* It provides several operations including
* initialize, shuffle, deal, and check if empty.
*/
public class Deck {
/**
* cards contains all the cards in the deck.
*/
private List<Card> cards;
/**
* size is the number of not-yet-dealt cards.
* Cards are dealt from the top (highest index) down.
* The next card to be dealt is at size - 1.
*/
private int size;
/**
* Creates a new <code>Deck</code> instance.<BR>
* It pairs each element of ranks with each element of suits,
* and produces one of the corresponding card.
* #param ranks is an array containing all of the card ranks.
* #param suits is an array containing all of the card suits.
* #param values is an array containing all of the card point values.
*/
ArrayList<Card> cardList = new ArrayList<>();
String[] ranks = {"Ace","Two","Three","Four","Five","Six" , "Seven" , "Eight","Nine","Ten", "Jack", "Queen","King"};
String[] suits = {"spades" , "diamonds" , "clubs" , "hearts"};
int[] values = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};
boolean selected = false;
public Deck() {
cards = new ArrayList<Card>();
for (int j = 0; j < ranks.length; j++) {
for (String suitString : suits) {
cards.add(new Card(ranks[j], suitString, values[j], selected));
}
}
size = cards.size();
}
public Card nextCard() {
if(cards.size() > 0) {
System.out.println(cards.get(0).toString());
return cards.remove(0);
}else{
return null;
}
}
/**
* Determines if this deck is empty (no undealt cards).
* #return true if this deck is empty, false otherwise.
*/
public boolean isEmpty() {
return size == 0;
}
/**
* Accesses the number of undealt cards in this deck.
* #return the number of undealt cards in this deck.
*/
public int size() {
return cards.size();
}
/**
* Randomly permute the given collection of cards
* and reset the size to represent the entire deck.
*/
List<Card> shuffledDeck;
ArrayList<Integer> usedNumbers = new ArrayList<Integer>();
public void shuffle() {
shuffledDeck = new ArrayList<>();
Random random = new Random();
for(usedNumbers.size(); usedNumbers.size() < 52;) {
int randomNum = random.nextInt(52);
if(!usedNumbers.contains(randomNum)) {
shuffledDeck.add(usedNumbers.size(), cards.get(randomNum));
usedNumbers.add(randomNum);
}
}
size = shuffledDeck.size();
cards = shuffledDeck;
}
/**
* Generates and returns a string representation of this deck.
* #return a string representation of this deck.
*/
#Override
public String toString() {
String rtn = "size = " + size + "\nUndealt cards: \n";
for (int k = cards.size() - 1; k >= 0; k--) {
rtn = rtn + cards.get(k);
if (k != 0) {
rtn = rtn + ", ";
}
if ((size - k) % 2 == 0) {
// Insert carriage returns so entire deck is visible on console.
rtn = rtn + "\n";
}
}
rtn = rtn + "\nDealt cards: \n";
for (int k = cards.size() - 1; k >= size; k--) {
rtn = rtn + cards.get(k);
if (k != size) {
rtn = rtn + ", ";
}
if ((k - cards.size()) % 2 == 0) {
// Insert carriage returns so entire deck is visible on console.
rtn = rtn + "\n";
}
}
rtn = rtn + "\n";
return rtn;
}
}
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Board extends JFrame implements ActionListener {
Deck deck = new Deck();
Card card;
JPanel buttonPanel = new JPanel();
JPanel menuPanel = new JPanel();
JButton cardOne = new JButton();
JButton cardTwo = new JButton();
JButton cardThree = new JButton();
JButton cardFour = new JButton();
JButton cardFive = new JButton();
JButton cardSix = new JButton();
JButton cardSeven = new JButton();
JButton[] buttons = {cardOne, cardTwo, cardThree, cardFour, cardFive, cardSix, cardSeven};
int winCount = 0;
int lossCount = 0;
int deckCount = 52;
JButton replace = new JButton("Replace");
JButton reset = new JButton("Reset");
JLabel cardsLeft = new JLabel("Cards left:" + deckCount);
JLabel winLossLabel = new JLabel("Win: " + winCount + "\tLoss: " + lossCount);
public Board() {
initGUI();
}
ArrayList<Card> boardArray = new ArrayList<>();
public void startGame() {
deck.shuffle();
Card card;
for(int i = 0 ; i <=6 ; i++) {
boardArray.add(card = deck.nextCard());
buttons[i].setIcon(card.cardImage);
}
}
public void initGUI() {
setTitle("Elevens");
setLayout(new GridLayout(1,2));
buttonPanel.setLayout(new GridLayout(2,4));
menuPanel.setLayout(new GridLayout(4,1));
setResizable(false);
buttonPanel.add(cardOne);
buttonPanel.add(cardTwo);
buttonPanel.add(cardThree);
buttonPanel.add(cardFour);
buttonPanel.add(cardFive);
buttonPanel.add(cardSix);
buttonPanel.add(cardSeven);
menuPanel.add(replace);
menuPanel.add(reset);
menuPanel.add(cardsLeft);
menuPanel.add(winLossLabel);
add(buttonPanel);
add(menuPanel);
for(int i = 0; i < buttons.length; i++){
buttons[i].addActionListener(this);
}
replace.addActionListener(this);
reset.addActionListener(this);
replace.setSize(new Dimension (100,10));
pack();
setVisible(true);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(600,300);
}
ImageIcon selectedIcon;
Boolean selected = false;
String newPathString;
int buttonNumber;
public void getPath(int buttonNumber) {
String path = "/Users/AlecR/Documents/workspace/Elevens Lab Midyear Exam/src/";
if(boardArray.get(buttonNumber).rank() == "Ace" || boardArray.get(buttonNumber).rank() == "Jack" || boardArray.get(buttonNumber).rank() == "Queen" || boardArray.get(buttonNumber).rank() == "King") {
newPathString = path + boardArray.get(buttonNumber).rank() + boardArray.get(buttonNumber).suit() + "S.GIF";
}else{
newPathString = path + Integer.toString(boardArray.get(buttonNumber).pointValue()) + boardArray.get(buttonNumber).suit() + "S.GIF";
}
selectedIcon = new ImageIcon(newPathString);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == cardOne) {
if(boardArray.get(0).selected == false) {
getPath(0);
buttons[0].setIcon(selectedIcon);
boardArray.get(0).selected = true;
}else{
boardArray.get(0).selected = false;
buttons[0].setIcon(boardArray.get(0).cardImage);
}
}
if(e.getSource() == cardTwo) {
if(boardArray.get(1).selected == false) {
getPath(1);
buttons[1].setIcon(selectedIcon);
boardArray.get(1).selected = true;
}else{
boardArray.get(1).selected = false;
buttons[1].setIcon(boardArray.get(1).cardImage);
}
}
if(e.getSource() == cardThree) {
if(boardArray.get(2).selected == false) {
getPath(2);
buttons[2].setIcon(selectedIcon);
boardArray.get(2).selected = true;
}else{
boardArray.get(2).selected = false;
buttons[2].setIcon(boardArray.get(2).cardImage);
}
}
if(e.getSource() == cardFour) {
if(boardArray.get(3).selected == false) {
getPath(3);
buttons[3].setIcon(selectedIcon);
boardArray.get(3).selected = true;
}else{
boardArray.get(3).selected = false;
buttons[3].setIcon(boardArray.get(3).cardImage);
}
}
if(e.getSource() == cardFive) {
if(boardArray.get(4).selected == false) {
getPath(4);
buttons[4].setIcon(selectedIcon);
boardArray.get(4).selected = true;
}else{
boardArray.get(4).selected = false;
buttons[4].setIcon(boardArray.get(4).cardImage);
}
}
if(e.getSource() == cardSix) {
if(boardArray.get(5).selected == false) {
getPath(5);
buttons[5].setIcon(selectedIcon);
boardArray.get(5).selected = true;
}else{
boardArray.get(5).selected = false;
buttons[5].setIcon(boardArray.get(5).cardImage);
}
}
if(e.getSource() == cardSeven) {
if(boardArray.get(6).selected == false) {
getPath(6);
buttons[6].setIcon(selectedIcon);
boardArray.get(6).selected = true;
}else{
boardArray.get(6).selected = false;
buttons[6].setIcon(boardArray.get(6).cardImage);
}
}
if(e.getSource() == replace) {
checkWin();
}
if(e.getSource() == reset) {
System.out.println("Feature In Progress. Exit game to reset.");
}
}
int total;
int buttonsSelected = 0;
public void checkWin() {
for(int i = 0; i <= 6; i++) {
if(boardArray.get(i).selected == true) {
int pointValue = boardArray.get(i).pointValue();
total = total + pointValue;
buttonsSelected++;
}
}
if((buttonsSelected == 3 && total == 36) || (buttonsSelected == 2 && total == 11)) {
for(int i = 0; i <= 6; i++) {
if(boardArray.get(i).selected == true) {
boardArray.set(i, deck.nextCard());
buttons[i].setIcon(boardArray.get(i).cardImage);
deckCount--;
cardsLeft.setText("Cards left:" + deckCount);
}
}
}
total = 0;
buttonsSelected = 0;
}
}
import javax.swing.ImageIcon;
/**
* Card.java
*
* <code>Card</code> represents a playing card.
*/
public class Card {
/**
* String value that holds the suit of the card
*/
private String suit;
/**
* String value that holds the rank of the card
*/
private String rank;
/**
* int value that holds the point value.
*/
private int pointValue;
/**
* Creates a new <code>Card</code> instance.
*
* #param cardRank
* a <code>String</code> value containing the rank of the card
* #param cardSuit
* a <code>String</code> value containing the suit of the card
* #param cardPointValue
* an <code>int</code> value containing the point value of the
* card
*/
ImageIcon cardImage;
Card card;
Boolean selected = false;
int picNumber = 1;
public Card(String cardRank, String cardSuit, int cardPointValue, Boolean selected) {
// initializes a new Card with the given rank, suit, and point value
rank = cardRank;
suit = cardSuit;
pointValue = cardPointValue;
selected = false;
String pointString = Integer.toString(pointValue);
String path = "/Users/AlecR/Documents/workspace/Elevens Lab Midyear Exam/src/";
if (cardPointValue >= 2 && cardPointValue <= 10) {
String cardImageString = path + pointString + cardSuit + ".GIF";
cardImage = new ImageIcon(cardImageString);
}
if (cardPointValue == 1) {
}
switch (pointValue) {
case 1:
cardImage = new ImageIcon(path + "ace" + cardSuit + ".GIF");
break;
case 11:
cardImage = new ImageIcon(path + "jack" + cardSuit + ".GIF");
break;
case 12:
cardImage = new ImageIcon(path + "queen" + cardSuit + ".GIF");
break;
case 13:
cardImage = new ImageIcon(path + "king" + cardSuit + ".GIF");
break;
}
}
public String getCardImage() {
return cardImage.toString();
}
/**
* Accesses this <code>Card's</code> suit.
*
* #return this <code>Card's</code> suit.
*/
public String suit() {
return suit;
}
/**
* Accesses this <code>Card's</code> rank.
*
* #return this <code>Card's</code> rank.
*/
public String rank() {
return rank;
}
/**
* Accesses this <code>Card's</code> point value.
*
* #return this <code>Card's</code> point value.
*/
public int pointValue() {
return pointValue;
}
/**
* Compare this card with the argument.
*
* #param otherCard
* the other card to compare to this
* #return true if the rank, suit, and point value of this card are equal to
* those of the argument; false otherwise.
*/
public boolean matches(Card otherCard) {
return otherCard.suit().equals(this.suit())
&& otherCard.rank().equals(this.rank())
&& otherCard.pointValue() == this.pointValue();
}
/**
* Converts the rank, suit, and point value into a string in the format
* "[Rank] of [Suit] (point value = [PointValue])". This provides a useful
* way of printing the contents of a <code>Deck</code> in an easily readable
* format or performing other similar functions.
*
* #return a <code>String</code> containing the rank, suit, and point value
* of the card.
*/
#Override
public String toString() {
return rank + " of " + suit + " (point value = " + pointValue + ")";
}
}
When it resets, it is basically same as the state when you start a new game.
When starting a new game:
1) Create deck
2) Shuffle deck
3) Draw images(cards) or reset the image in swing
So when you reset, basically you repeat the same process as above.
You can have something like this:
public static void startNewGame() //use this for reset
{
ArrayList<Card> deck = createNewDeck();
ShuffleCards(deck);
ResetImages(deck); //reset card images
ResetComponents(); //reset all buttons/display to initial state
}
Something like this:
board.this.setVisible(false);
board.this.dispose();
new Board();
You can assign board = new Board(); but you need to make it static in the main class.
The best way is to make it using
public class DeckTester {
.
.
private static Board board;
public static void newBoard(){
board = new Board();
}
Then, refresh what you need.
All you have to do to restart is redefine the attributes as you would at the beginning so if you populate a deck and shuffle it at startup, you should so the same at restart. Try using a function for both scenarios, I'll give you a generic example.
public void setup() {
populate() // populate deck
shuffle() // and shuffle it
// anything else like ...
score = 0;
}

How to create a hand class for BlackJack java [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Can someone please please help. I have created a card class and Deck class but I just dont know how to create the Hand class.
This is my Card class below.
package blackjack;
public class Card {
private int rank;
private int suit;
#Override
public String tostring() {
String result = "";
if (rank == 1) result = "Ace";
if (rank == 2) result = "Two";
if (rank == 3) result = "Three";
if (rank == 4) result = "Four";
if (rank == 5) result = "Five";
if (rank == 6) result = "Six";
if (rank == 7) result = "Seven";
if (rank == 8) result = "Eight";
if (rank == 9) result = "Nine";
if (rank == 10) result = "Ten";
if (rank == 11) result = "Jack";
if (rank == 12) result = "Queen";
if (rank == 13) result = "King";
if (suit == 1) result = result + " of Clubs ";
if (suit == 2) result = result + " of Diamonds ";
if (suit == 3) result = result + " of Hearts ";
if (suit == 4) result = result + " of Spades ";
return result;
}
public Card(int rank, int suit) {
this.rank = rank;
this.suit = suit;
}
}
This is my Deck Class
package blackjack;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
public class Deck {
private Random shuffles = new Random();
public ArrayList<Card> Deck = new ArrayList<Card>();
Random rand = new Random();
// private int numberOfCards = 52;
public Deck() {
for (int ranks = 1; ranks <= 13; ranks++) {
for (int suits =1 ; suits <= 4; suits++) {
Deck.add(new Card(ranks, suits));
//System.out.println(Deck.get(ranks) + "" +Deck.get(suits));
}
}
shuffle();
for (int i = 1; i < Deck.size(); i++) {
//int cardPosition2 = shuffles.nextInt(52);
//shuffle.nextInt(Deck.get(i);
System.out.println(Deck.get(i));
//System.out.println(cardPosition2);
//i++;
}
}
public void shuffle() {
Collections.shuffle(Deck);
}
public Card DrawCard() {
int cardPosition = shuffles.nextInt(Deck.size());
return Deck.remove(cardPosition);
}
public int TotalCardsLeft() {
return Deck.size();
}
public Card dealCard() {
// Deals one card from the deck and returns it.
if (Deck.size() == 52) {
shuffle();
}
Card temp;
temp = Deck.get(0);
Deck.remove(0);
return temp;
}
public Card getCard(int i) {
return Deck.get(i);
}
public Card remove(int i) {
Card remo = Deck.get(i);
Deck.remove(i);
return remo;
}
}
If you can help me with my Hand call I would really appreciate it.
Create Class, which will contain for example ArrayList hand.
public class Hand {
private ArrayList<Card> hand
.
.
Then make methods to add(draw) Card :
public void addCard(Card c){
this.hand.add(c);
}
You will also need method to check whether card of specific type is present:
public boolean checkPresence(int rank){
for(int i=0;i<hand.size();i++){
//note you will need to implement getters to the Card class first
if (hand.get(i).getRank==rank)
return true;
}
return false;
}
Similarly for suit.
Of course you will most probably need other methods, but I am sure you can figure them out yourself.

Java lists and the garbage collector

I am doing a quick card game project in Java. I am storing the deck of cards as a node list. I think I am having trouble properly adding and removing from the list. Do you see anything that doesn't look right? I've been banging my head off the desk trying to figure this one out. EDIT: Posted all the classes for you to see
Card class
public class Card
{
private CardType theCard;
private CardSuit theSuit;
private Card nextCard = null, previousCard = null;
Card(Card card)
{
/*
* Question - If I just set "this = c", would this
* object be pointing to the same object c? Or will
* a separate object be created from Card c
*/
this.theCard = card.getTheCard();
this.theSuit = card.getTheSuit();
this.nextCard = card.getNext();
this.previousCard = card.getPrevious();
}
Card(CardType theCard, CardSuit theSuit)
{
this.theCard = theCard;
this.theSuit = theSuit;
}
Card(CardType theCard, CardSuit theSuit, Card nextCard, Card previousCard)
{
this.theCard = theCard;
this.theSuit = theSuit;
this.nextCard = nextCard;
this.previousCard = previousCard;
}
//the suit order is spade, heart, diamond, and then club.
public int getTotValue()
{
return theCard.getValue() + theCard.getFaceValue() + theSuit.getValue();
}
public int getFaceValue()
{
return theCard.getFaceValue();
}
public int getSuitValue()
{
return theSuit.getValue();
}
public String getFace()
{
return theSuit.getFace();
}
public String getSuit()
{
return theSuit.getFace();
}
public int getValue()
{
return theCard.getValue();
}
public Card getNext()
{
return nextCard;
}
public void setNext(Card nextCard)
{
this.nextCard = nextCard;
}
public Card getPrevious()
{
return previousCard;
}
public void setPrevious(Card previousCard)
{
this.previousCard = previousCard;
}
/**
* #return the theCard
*/
public CardType getTheCard() {
return theCard;
}
/**
* #param theCard the theCard to set
*/
public void setTheCard(CardType theCard) {
this.theCard = theCard;
}
/**
* #return the theSuit
*/
public CardSuit getTheSuit() {
return theSuit;
}
/**
* #param theSuit the theSuit to set
*/
public void setTheSuit(CardSuit theSuit) {
this.theSuit = theSuit;
}
public String toString()
{
return (theCard.getFace() + " of " + theSuit.getFace());
}
}
CardSuit
public enum CardSuit
{
SPADE("Spade", 4),
HEART("Heart", 3),
DIAMOND("Diamond", 2),
CLUB("Club", 1);
private final String face;
private final int value;
CardSuit(String face, int value)
{
this.face = face;
this.value = value;
}
public String getFace()
{
return face;
}
public int getValue()
{
return value;
}
}
CardType
public enum CardType
{
ACE("Ace", 11),
KING("King", 3, 10),
QUEEN("Queen", 2, 10),
JACK("Jack", 1, 10),
TEN("Ten", 10),
NINE("Nine", 9),
EIGHT("Eight", 8),
SEVEN("Seven", 7),
SIX("Six", 6),
FIVE("Five", 5),
FOUR("Four", 4),
THREE("Three", 3),
DEUCE("Deuce", 2);
private final String face;
private final int value;
private int faceValue = 0;
CardType(String f, int v)
{
this.face = f;
this.value = v;
}
CardType(String f, int fv, int v)
{
this.face = f;
this.faceValue = fv;
this.value = v;
}
public String getFace()
{
return face;
}
public int getValue()
{
return value;
}
public int getFaceValue()
{
return faceValue;
}
}
Deck
/**
*
*/
/**
* #author Andrew-Desktop
*
*/
public class Deck extends Pile
{
/**
* the suit order is spade, heart, diamond, and then club.
*/
public Deck()
{
for(CardType card: CardType.values())
{
for(CardSuit suit: CardSuit.values())
{
this.addLastCard(new Card(card, suit));
}
}
}
/**
* #param topCard
* #param bottomCard
*/
public Deck(Card topCard, Card bottomCard)
{
super(topCard, bottomCard);
// TODO Auto-generated constructor stub
}
/**
* #param topCard
* #param bottomCard
* #param nCard
*/
public Deck(Card topCard, Card bottomCard, int nCard)
{
super(topCard, bottomCard, nCard);
// TODO Auto-generated constructor stub
}
}
Pile
import java.util.Random;
public class Pile
{
private static final int GREATER_THAN = 1;
private static final int EQUAL_TO = 0;
private static final int LESS_THAN = -1;
Card topCard, bottomCard;
int nCard;
Random ran = new Random();
int ranNum;
Pile()
{
topCard = null;
bottomCard = null;
nCard = 0;
}
Pile(Card topCard, Card bottomCard)
{
this.topCard = topCard;
this.bottomCard = bottomCard;
this.nCard = 52;
}
Pile(Card topCard, Card bottomCard, int nCard)
{
this.topCard = topCard;
this.bottomCard = bottomCard;
this.nCard = nCard;
}
public void
shuffle() throws InterruptedException
{
for(int i = ran.nextInt(10000);0<i;i--)
{
Card tempCard = remove(1);
this.insert(tempCard, (ran.nextInt(52)+1));
}
}
public boolean
thereIsDuplicates()
{
Card travCard = topCard;
for(int x = 1; x<=nCard && travCard != null; x++)
{
for(int y = x+1; y<=nCard; y++)
{
if(travCard == this.getCardAtIndex(y))
{
// System.out.println(this.getIndexOfCard(travCard) + ": " + travCard);
System.out.println(travCard.toString());
return true;
}
}
travCard = travCard.getNext();
}
return false;
}
public
Card remove(Card c)
{
assert !isEmpty();//Don't know if this even works
if(c == topCard)// if topCard
{
topCard = topCard.getNext();
topCard.setPrevious(null);
}
else if(c == bottomCard) // if bottom card
{
bottomCard = bottomCard.getPrevious();
bottomCard.setNext(null);
}
else
{
Card tempCard = c.getPrevious();
tempCard.setNext(c.getNext());
tempCard.getNext().setPrevious(tempCard);
}
nCard--;
return null;
}
// public void
// remove(int i)
// {
// assert (i>0 && i <= nCard && !isEmpty());
// if(i == 1)// if topCard
// {
// topCard = topCard.getNext();
// topCard.setPrevious(null);
// }
// else if(this.getCardAtIndex(i).getNext()==null) // if bottom card
// {
// bottomCard = bottomCard.getPrevious();
// bottomCard.setNext(null);
// }
// else
// {
// Card cardBefore = this.getCardAtIndex(i-1);
// cardBefore.setNext(cardBefore.getNext().getNext());
// cardBefore.getNext().setPrevious(cardBefore);
// }
// nCard--;
//
// }
public Card remove(int givenPosition) throws InterruptedException
{
Card result = null; // return value
if ((givenPosition >= 1) && (givenPosition <= nCard))
{
if (givenPosition == 1) // case 1: remove first entry
{
result = topCard; // save entry to be removed
topCard = topCard.getNext();
topCard.setPrevious(null);
}
else // case 2: givenPosition > 1
{
Card cardBefore = getCardAtIndex(givenPosition - 1);
Card cardToRemove = cardBefore.getNext();
Card cardAfter = cardToRemove.getNext();
cardBefore.setNext(cardAfter); // disconnect the node to be removed
cardAfter.setPrevious(cardBefore);
result = cardToRemove; // save entry to be removed
} // end if
nCard--;
} // end if
if(result == null)
{
this.printCards();
Thread.sleep(1000);
}
return result;
}
/**
* <p>Precondition: index must be 0<i and i<53 or less than the number of cards
* <p>Postcondition:
* #param i - The index of the card.
* #return Card at that index.
*
*/
public Card getCardAtIndex(int i)
{
Card travCard = topCard;
assert (i>0 && i<=nCard && !isEmpty());
for(int x = 1; x<=i && travCard != null; x++)
{
travCard = travCard.getNext();
}
return travCard;
}
public int
getIndexOfCard(Card c, int i)
{
Card travCard = topCard;
for(int x = i; x<=nCard; x++)
{
if(travCard == c)
return x;
travCard = travCard.getNext();
}
return -1;
}
public Card
getCard(Card c)//don't think I'll need this method
{
Card travCard = topCard;
assert (!isEmpty());
while(c!=travCard && null != travCard)
{
travCard = travCard.getNext();
}
return travCard;
}
/**
* Sorts from highest(Ace) to lowest 2
* the suit order is spade, heart, diamond, and then club.
*/
public void
addLastCard(Card c)
{
if(isEmpty())
{
topCard = c;
bottomCard = c;
}
else
{
bottomCard.setNext(c);
c.setPrevious(bottomCard);
bottomCard = c;
}
nCard++;
}
public void
sort()
{
quickSort(topCard, bottomCard);
}
private void
quickSort(Card start, Card end)
{
Card left = start;
Card right = end;
if (start != end)
{
Card pivot = start;
while (!(left.getNext()!=right))
{
while (compare(left, pivot) == LESS_THAN && left != end && left!=right)
{
left = left.getNext();
}
while (compare(right, pivot) == GREATER_THAN && right!=start && right!=left)
{
right = right.getPrevious();
}
if (left!=right)
{
swap(left, right);
}
}
swap(start, right);
quickSort(start, right.getPrevious());
quickSort(right.getNext(), end);
}
else // if there is only one element in the partition, do not do any sorting
{
return; // the array is sorted, so exit
}
}
public void
swap(Card one, Card two)
{
Card temp = new Card(one);
one = two;
two = temp;
}
public void
insert(Card theCard, int givenPosition)
{
if(givenPosition>0 && givenPosition<=nCard)
{
if(isEmpty())// if an empty list
{
topCard = theCard;
bottomCard = theCard;
System.out.println("EmptyList");
}
else if(1==givenPosition)// if adding to the top of the pile
{
theCard.setNext(topCard);
topCard.setPrevious(theCard);
topCard = theCard;
}
else if(nCard == givenPosition) // if adding to the bottom of the pile
{
this.addLastCard(theCard);
nCard--;
}
else
{
Card tempCard = getCardAtIndex(givenPosition);
theCard.setNext(tempCard.getNext());
tempCard.setNext(theCard);
theCard.setPrevious(tempCard);
}
nCard++;
}
}
//the suit order is spade, heart, diamond, and then club.
public int
compare(Card one, Card two)
{
if(one.getValue()<two.getValue() || (one.getValue() == two.getValue() && one.getTotValue()<two.getTotValue()))
{
return LESS_THAN;
}
else if(one.getValue() == two.getValue() && one.getTotValue() == two.getTotValue())
{
return EQUAL_TO;
}
else if(one.getValue()>two.getValue() || (one.getValue() == two.getValue() && one.getTotValue()>two.getTotValue()))
{
return GREATER_THAN;
}
return -5;
}
public boolean
isEmpty()
{
if(0 == nCard && null == topCard)
return true;
else
return false;
}
public void
printCards()
{
Card travCard = topCard;
int i = 1;
while(travCard!=null)
{
System.out.println(i + ": " + travCard.toString());
travCard = travCard.getNext();
i++;
}
}
/**
* #return the topCard
*/
public Card
getTopCard()
{
return topCard;
}
/**
* #param topCard the topCard to set
*/
public void
setTopCard(Card topCard)
{
this.topCard = topCard;
}
/**
* #return the bottomCard
*/
public Card
getBottomCard()
{
return bottomCard;
}
/**
* #param bottomCard the bottomCard to set
*/
public void
setBottomCard(Card bottomCard)
{
this.bottomCard = bottomCard;
}
/**
* #return the nCard
*/
public int
getnCard()
{
return nCard;
}
/**
* #param nCard the nCard to set
*/
public void
setnCard(int nCard)
{
this.nCard = nCard;
}
}
TwentyOne
public class TwentyOne
{
/**
* #param args
* #throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException
{
Deck theDeck = new Deck();
theDeck.printCards();
theDeck.shuffle();
theDeck.printCards();
}
}
The output looks something like this:
577625: Ace of Spade
577626: Nine of Spade
577627: Five of Diamond
577628: Ten of Heart
577629: Eight of Heart
577630: Nine of Club
577631: Jack of Heart
577632: Eight of Spade
577633: Queen of Heart
577634: Seven of Heart
577635: Deuce of Club
577636: Jack of Diamond
577637: Four of Club
577638: Five of Club
577639: Ace of Spade
577640: Nine of Spade
577641: Five of Diamond
577642: Ten of Heart
577643: Eight of Heart
577644: Nine of Club
577645: Jack of Heart
577646: Eight of Spade
577647: Queen of Heart
577648: Seven of Heart
577649: Deuce of Club
577650: Jack of Diamond
577651: Four of Club
577652: Five of Club
577653: Ace of Spade
577654: Nine of Spade
577655: Five of Diamond
577656: Ten of Heart
577657: Eight of Heart
577658: Nine of Club
577659: Jack of Heart
577660: Eight of Spade
577661: Queen of Heart
577662: Seven of Heart
577663: Deuce of Club
577664: Jack of Diamond
577665: Four of Club
577666: Five of Club
577667: Ace of Spade
577668: Nine of Spade
577669: Five of Diamond
577670: Ten of Heart
577671: Eight of Heart
577672: Nine of Club
577673: Jack of Heart
577674: Eight of Spade
577675: Queen of Heart
577676: Seven of Heart
577677: Deuce of Club
577678: Jack of Diamond
577679: Four of Club
577680: Five of Club
577681: Ace of Spade
577682: Nine of Spade
577683: Five of Diamond
577684: Ten of Heart
577685: Eight of Heart
577686: Nine of Club
577687: Jack of Heart
577688: Eight of Spade
577689: Queen of Heart
577690: Seven of Heart
577691: Deuce of Club
577692: Jack of Diamond
577693: Four of Club
577694: Five of Club
577695: Ace of Spade
577696: Nine of Spade
577697: Five of Diamond
Use one of the java.util.List subclasses. Either ArrayList (probably what you should pick) or LinkedList (in case your feeling froggy like you need something that implements Queue). Then look at using Collections.shuffle() method to shuffle the cards.
http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html
http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#shuffle(java.util.List)
LinkedList won't perform as well as ArrayList when it comes to random access.
Looking at the output like this makes it hard to figure out what is going on. Something is wrong as the Queen of Hearts appears multiple times. Try testing your insert method without calling shuffle and remove. Testing one method at a time helps isolate the problem.
When you can see that you are able to insert all of your cards in order, see what happens when you remove a single card.

Categories