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;
}
Related
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;
first excuse me for my English it is not strong.
Yesterday a friend tell me about The Sagrada Familia Magic Square that is conformed by 16 numbers in a 4x4 matrix.
According to the creator "Antoni Gaudi" there are 310 possible combinations of 4 number without getting repeated that sums 33 'age at which Jesus died'.
So, i have created a java program using Depth First Search algorithm "just for practice" but i just get 88 combinations, i would like to know if there is anything wrong with my code or if making 310 combinations is not possible.
PDT:"I have searched on internet if it is not possible to make 310 combinations but without lucky".
The program has three classes Nodo, IA, Pila.
"IA is the main part of the project which centralize everything, Nodo is just a Node and Pila is for Stacking purposes"
First, I have divided the matrix 4x4 Sagrada familia in position and values. Position starts at 0 and ends in 15 and each position has a specific values "wath the hastable on IA"
The program creates every possible combination of positions in a DFS way "combinations of four numbers" and then checks if they sum 33.
the value -1 is a special number that means that this position can take any number.
How does it works - tree ('posx','posy','posw','posz')
-1,-1,-1,-1
0,-1,-1,-1 1,-1,-1,-1 . . .
0,1,-1,-1 0,2,-1,-1 . . . 1,0,-1,-1 1,2,-1,-1 . .
0,1,2,-1 . . . . . . . .
0,1,2,3 . . .
Nodo Class
import java.util.Arrays;
/**
*
* #author Vicar
*/
public class Nodo {
private int posx;
private int posy;
private int posw;
private int posz;
private int valx;
private int valy;
private int valw;
private int valz;
public Nodo (){
posx=-1;
posy=-1;
posw=-1;
posz=-1;
valx=-1;
valy=-1;
valw=-1;
valz=-1;
}
public Nodo (int posx, int posy, int posw, int posz, int valx, int valy, int valw, int valz){
this.posx=posx;
this.posy=posy;
this.posw=posw;
this.posz=posz;
this.valx=valx;
this.valy=valy;
this.valw=valw;
this.valz=valz;
}
//returns the sum
public int sumar (){
return valx+valy+valw+valz;
}
//Returns the position of each value
public String retornarPos(){
return posx+","+posy+","+posw+","+posz;
}
//returns the value
public String retornarVal(){
return valx+","+valy+","+valw+","+valz;
}
//Returns the sorted position of the 4 combinations
public String retornarPosOrdenado(){
int [] arreglo ={posx,posy,posw,posz};
Arrays.sort(arreglo);
return arreglo[0]+","+arreglo[1]+","+arreglo[2]+","+arreglo[3];
}
/**
* #return the posx
*/
public int getPosx() {
return posx;
}
/**
* #param posx the posx to set
*/
public void setPosx(int posx) {
this.posx = posx;
}
/**
* #return the posy
*/
public int getPosy() {
return posy;
}
/**
* #param posy the posy to set
*/
public void setPosy(int posy) {
this.posy = posy;
}
/**
* #return the posw
*/
public int getPosw() {
return posw;
}
/**
* #param posw the posw to set
*/
public void setPosw(int posw) {
this.posw = posw;
}
/**
* #return the posz
*/
public int getPosz() {
return posz;
}
/**
* #param posz the posz to set
*/
public void setPosz(int posz) {
this.posz = posz;
}
/**
* #return the valx
*/
public int getValx() {
return valx;
}
/**
* #param valx the valx to set
*/
public void setValx(int valx) {
this.valx = valx;
}
/**
* #return the valy
*/
public int getValy() {
return valy;
}
/**
* #param valy the valy to set
*/
public void setValy(int valy) {
this.valy = valy;
}
/**
* #return the valw
*/
public int getValw() {
return valw;
}
/**
* #param valw the valw to set
*/
public void setValw(int valw) {
this.valw = valw;
}
/**
* #return the valz
*/
public int getValz() {
return valz;
}
/**
* #param valz the valz to set
*/
public void setValz(int valz) {
this.valz = valz;
}
}
Pila class
import java.util.ArrayList;
import java.util.Stack;
/**
*
* #author Vicar
*/
public class Pila {
private Stack <Nodo> pila;
private ArrayList<String> valor;
public Pila (){
pila = new Stack();
valor = new ArrayList<String>();
}
//add a Node to the stack
public void agregar(Nodo nodo){
pila.push(nodo);
valor.add(nodo.retornarPos());
}
//Pops a node from the stack
public Nodo sacar(){
valor.remove(valor.indexOf(pila.peek().retornarPos()));
return pila.pop();
}
// checks if the stack is empty
public boolean estaVacia(){
return pila.isEmpty();
}
// checks if the stack contains an specific node
public boolean contiene(String busqueda){
return valor.contains(busqueda);
}
}
IA Class
import java.util.*;
/**
*
* #author vicar
*/
public class IA {
Hashtable<Integer,Integer> tabla=new Hashtable<Integer,Integer>();
//add the matrix 4,4 to a hastable (pos,val)
public IA(){
tabla.put(0, 1);
tabla.put(1, 14);
tabla.put(2, 14);
tabla.put(3, 4);
tabla.put(4, 11);
tabla.put(5, 7);
tabla.put(6, 6);
tabla.put(7, 9);
tabla.put(8, 8);
tabla.put(9, 10);
tabla.put(10,10);
tabla.put(11, 5);
tabla.put(12, 13);
tabla.put(13, 2);
tabla.put(14, 3);
tabla.put(15, 15);
}
//DFS
public ArrayList<String> busquedaAProfundidad(){
Pila pila = new Pila();
ArrayList <String> visitados = new ArrayList<String>();
ArrayList <Nodo> hijos = new ArrayList<Nodo>();
ArrayList <String> resultado = new ArrayList<String>();
Nodo nodoRaiz = new Nodo();
pila.agregar(nodoRaiz);
//Chsck if the stack is empty
while(!pila.estaVacia()){
Nodo nodo = pila.sacar();
visitados.add(nodo.retornarPos());
//i get every possible children from the node
hijos=crearHijos(nodo);
for (int i = 0; i < hijos.size(); i++) {
//checks that the node is not visited and the sum results in 33
if(!visitados.contains(hijos.get(i).retornarPos()) && !pila.contiene(hijos.get(i).retornarPos())){
if(hijos.get(i).getPosx()!=-1 && hijos.get(i).getPosy()!=-1 && hijos.get(i).getPosw()!=-1 && hijos.get(i).getPosz()!=-1 && hijos.get(i).sumar()==33 ){
//this is the final result without repeted numbers
if(!resultado.contains(hijos.get(i).retornarPosOrdenado())){
resultado.add(hijos.get(i).retornarPosOrdenado());
}
}
else{
//System.err.println("pos: "+hijos.get(i).retornarPosOrdenado());
pila.agregar(hijos.get(i));
}
}
}
}
return resultado;
}
// method to create children from a father node
public ArrayList<Nodo> crearHijos(Nodo padre){
ArrayList <Nodo> hijos = new ArrayList<Nodo>();
//positions of the father
int x = padre.getPosx();
int y = padre.getPosy();
int w = padre.getPosw();
int z = padre.getPosz();
if (x==-1 && y==-1 && w==-1 && z==-1){
for (int i = 0; i < 16; i++) {
hijos.add(new Nodo(i,-1,-1,-1,tabla.get(i),-1,-1,-1));
}
return hijos;
}
else if(x>=0 && y==-1 && w==-1 && z==-1){
for (int i = 0; i < 16; i++) {
if (x != i){
hijos.add(new Nodo(x,i,-1,-1,tabla.get(x),tabla.get(i),-1,-1));
}
}
}
else if(x>=0 && y>=0 && w==-1 && z==-1){
for (int i = 0; i < 16; i++) {
if (x != i && y != i){
hijos.add(new Nodo(x,y,i,-1,tabla.get(x),tabla.get(y),tabla.get(i),-1));
}
}
}
else if(x>=0 && y>=0 && w>=0 && z==-1){
for (int i = 0; i < 16; i++) {
if (x != i && y != i && w !=i){
hijos.add(new Nodo(x,y,w,i,tabla.get(x),tabla.get(y),tabla.get(w),tabla.get(i)));
}
}
}
return hijos;
}
}
a final class to check the result and send the output to a txt file
import java.util.ArrayList;
import java.io.File;
import java.io.FileWriter;
/**
*
* #author vicar
*/
public class Probador {
public static void main(String[] args) {
IA run = new IA();
ArrayList<String> resultado = run.busquedaAProfundidad();
try {
File archivo = new File("/tmp/gaudi.in");
FileWriter escribir = new FileWriter(archivo, true);
for (String resul : resultado) {
escribir.write(resul+"\n");
}
escribir.close();
}
catch (Exception e) {
System.out.println("Error al escribir");
}
}
}
Thanks!!!
The number 310 refers to the number of combinations of any size taking elements from the matrix (without picking the same cell twice). See https://blog.sagradafamilia.org/en/divulgation/the-magic-square-the-passion-facade-keys-to-understanding-it/
Here are the seventeen possible combinations of three numbers: [...]
With four numbers, there are 88 possible combinations that add up to
33; with five, there are 131; and with six, 66. With seven numbers,
there are eight different combinations:...
17 + 88 + 131 + 66 + 8 = 310
I set the button according to the 1-13 numbers on game card. When I click on a button I want it to randomly draw a card from the deck. If the card doesn't match the button # then I can try another button, if the card match the button # then the game ends. The program will keep running through 52 cards as long as the button and the card doesn't match. lblpic is where the card image suppose to appear when the user click one of the number button. I can't get the buttons to work properly. I fixed some codes in my Card game, but it's still not working. I also can't get the card image to show up when the user click on a number button. I tried linking the ImageLoader class to the CardGame Jframe, but it's not wokring.
ImageLoader
import javax.swing.ImageIcon;
public class ImageLoader {
public final ImageIcon BACK = new ImageIcon("img/backbluepattern.gif");
public ImageIcon[][] cardImg = new ImageIcon[4][13];
public final String[] SUITS = {"clubs", "hearts", "spades", "diamonds"};
public ImageLoader() {
for (int i = 0; i < 4; i++) {
for (int j = 1; j <= 13; j++) {
String strBuf = "img/" + SUITS[i] + j + ".gif";
cardImg[i][j-1] = new ImageIcon(strBuf);
}
}
}
}
Card
public class Card {
//Numerical equivalent of the suit and face
private int suitNum; // valid range is 0 - 3
private int faceNum; // valid range is 0 - 12
//For converting between names and numbers
public static final String[] SUITS = {"Clubs", "Hearts", "Spades", "Diamonds"};
public static final String[] FACES = {"Ace", "Two", "Three", "Four", "Five", "Six",
"Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"};
//Constructor takes combined number and splits it to suit and face numbers
public Card(int num) {
if (num > 51) {
System.out.println("Input number is larger than 51.");
System.exit(0);
}
suitNum = num / 13;
faceNum = num % 13;
}
// Return a calculated value that combines suit and face numbers
public int getTotalNumber() {
return (this.suitNum * 13 + this.faceNum);
}
public int getFaceNumber() {
return faceNum;
}
public int getSuitNumber() {
return suitNum;
}
public String toString() {
int num = getTotalNumber();
String outStr = FACES[num % 13];
outStr += " of ";
outStr += SUITS[num / 13];
return outStr;
}
}
Deck
import java.util.Collections;
import java.util.Stack;
public class Deck extends Stack<Card>{
//pop method already in the stack
// Create a new shuffled deck
public Deck() {
for (int ii = 0; ii < 52; ii++) {
push(new Card(ii));
}
Collections.shuffle(this);
}
// For debug purposes
public void printDeck() {
for (int ii = 0; ii < 52; ii++) {
System.out.println(get(ii).toString());
}
}
}
CardGame
import java.awt.EventQueue;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JFrame;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.ImageIcon;
public CardGame() {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
CardGame window = new CardGame();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
lblpic = new JLabel("");
Image img = new ImageIcon BACK(this getClass().getResource("img/backbluepattern.gif")).getImage();
lblpic.getIcon(new ImageIcon(img));
JButton btn1 = new JButton("1");
btn1.setBounds(4, 13, 97, 25);
btn1.addActionListener(new Btn1ActionListener());
frame.getContentPane().setLayout(null);
frame.getContentPane().add(btn1);
JButton btn2 = new JButton("2");
btn2.setBounds(4, 51, 97, 25);
btn2.addActionListener(new Btn2ActionListener());
frame.getContentPane().add(btn2);
JButton btn3 = new JButton("3");
btn3.setBounds(4, 89, 97, 25);
btn3.addActionListener(new Btn3ActionListener());
frame.getContentPane().add(btn3);
JButton btn4 = new JButton("4");
btn4.setBounds(4, 127, 97, 25);
btn4.addActionListener(new Btn4ActionListener());
frame.getContentPane().add(btn4);
JButton btn5 = new JButton("5");
btn5.setBounds(4, 165, 97, 25);
btn5.addActionListener(new Btn5ActionListener());
frame.getContentPane().add(btn5);
JButton btn6 = new JButton("6");
btn6.setBounds(4, 203, 97, 25);
btn6.addActionListener(new Btn6ActionListener());
frame.getContentPane().add(btn6);
JButton btn7 = new JButton("7");
btn7.setBounds(113, 13, 97, 25);
btn7.addActionListener(new Btn7ActionListener());
frame.getContentPane().add(btn7);
JButton btn8 = new JButton("8");
btn8.setBounds(113, 51, 97, 25);
btn8.addActionListener(new Btn8ActionListener());
frame.getContentPane().add(btn8);
JButton btn9 = new JButton("9");
btn9.setBounds(113, 89, 97, 25);
btn9.addActionListener(new Btn9ActionListener());
frame.getContentPane().add(btn9);
JButton btn10 = new JButton("10");
btn10.setBounds(113, 127, 97, 25);
btn10.addActionListener(new Btn10ActionListener());
frame.getContentPane().add(btn10);
JButton btn11 = new JButton("11");
btn11.setBounds(113, 165, 97, 25);
btn11.addActionListener(new Btn11ActionListener());
frame.getContentPane().add(btn11);
JButton btn12 = new JButton("12");
btn12.setBounds(113, 203, 97, 25);
btn12.addActionListener(new Btn12ActionListener());
frame.getContentPane().add(btn12);
JButton btn13 = new JButton("13");
btn13.setBounds(222, 13, 97, 25);
btn13.addActionListener(new Btn13ActionListener());
frame.getContentPane().add(btn13);
lblpic = new JLabel("");
lblpic.setBounds(222, 51, 115, 177);
frame.getContentPane().add(lblpic);
}
private class Btn1ActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
Card One = B.pop(); //Card one is from Deck B, need to compare to the button
int actionValue = Integer.parseInt(e.getActionCommand());
int cardValue = (actionValue - 1) + (One.getSuitNumber() * 13);
Card match = new Card(cardValue);
System.out.println("Match " + match + " to " + One);
if (One.equals(match)) {
System.out.println("Game Over!");
} else {
System.out.println("Try Again!");
}
}
}
private class Btn2ActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
Card One = B.pop(); //Card one is from Deck B, need to compare to the button
int actionValue = Integer.parseInt(e.getActionCommand());
int cardValue = (actionValue - 1) + (One.getSuitNumber() * 13);
Card match = new Card(cardValue);
System.out.println("Match " + match + " to " + One);
if (One.equals(match)) {
System.out.println("Game Over!");
} else {
System.out.println("Try Again!");
}
}
}
private class Btn3ActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
Card One = B.pop(); //Card one is from Deck B, need to compare to the button
int actionValue = Integer.parseInt(e.getActionCommand());
int cardValue = (actionValue - 1) + (One.getSuitNumber() * 13);
Card match = new Card(cardValue);
System.out.println("Match " + match + " to " + One);
if (One.equals(match)) {
System.out.println("Game Over!");
} else {
System.out.println("Try Again!");
}
}
}
private class Btn4ActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
Card One = B.pop(); //Card one is from Deck B, need to compare to the button
int actionValue = Integer.parseInt(e.getActionCommand());
int cardValue = (actionValue - 1) + (One.getSuitNumber() * 13);
Card match = new Card(cardValue);
System.out.println("Match " + match + " to " + One);
if (One.equals(match)) {
System.out.println("Game Over!");
} else {
System.out.println("Try Again!");
}
}
}
private class Btn5ActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
Card One = B.pop(); //Card one is from Deck B, need to compare to the button
int actionValue = Integer.parseInt(e.getActionCommand());
int cardValue = (actionValue - 1) + (One.getSuitNumber() * 13);
Card match = new Card(cardValue);
System.out.println("Match " + match + " to " + One);
if (One.equals(match)) {
System.out.println("Game Over!");
} else {
System.out.println("Try Again!");
}
}
}
private class Btn6ActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
Card One = B.pop(); //Card one is from Deck B, need to compare to the button
int actionValue = Integer.parseInt(e.getActionCommand());
int cardValue = (actionValue - 1) + (One.getSuitNumber() * 13);
Card match = new Card(cardValue);
System.out.println("Match " + match + " to " + One);
if (One.equals(match)) {
System.out.println("Game Over!");
} else {
System.out.println("Try Again!");
}
}
}
private class Btn7ActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
Card One = B.pop(); //Card one is from Deck B, need to compare to the button
int actionValue = Integer.parseInt(e.getActionCommand());
int cardValue = (actionValue - 1) + (One.getSuitNumber() * 13);
Card match = new Card(cardValue);
System.out.println("Match " + match + " to " + One);
if (One.equals(match)) {
System.out.println("Game Over!");
} else {
System.out.println("Try Again!");
}
}
}
private class Btn8ActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
Card One = B.pop(); //Card one is from Deck B, need to compare to the button
int actionValue = Integer.parseInt(e.getActionCommand());
int cardValue = (actionValue - 1) + (One.getSuitNumber() * 13);
Card match = new Card(cardValue);
System.out.println("Match " + match + " to " + One);
if (One.equals(match)) {
System.out.println("Game Over!");
} else {
System.out.println("Try Again!");
}
}
}
private class Btn9ActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
Card One = B.pop(); //Card one is from Deck B, need to compare to the button
int actionValue = Integer.parseInt(e.getActionCommand());
int cardValue = (actionValue - 1) + (One.getSuitNumber() * 13);
Card match = new Card(cardValue);
System.out.println("Match " + match + " to " + One);
if (One.equals(match)) {
System.out.println("Game Over!");
} else {
System.out.println("Try Again!");
}
}
}
private class Btn10ActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
Card One = B.pop(); //Card one is from Deck B, need to compare to the button
int actionValue = Integer.parseInt(e.getActionCommand());
int cardValue = (actionValue - 1) + (One.getSuitNumber() * 13);
Card match = new Card(cardValue);
System.out.println("Match " + match + " to " + One);
if (One.equals(match)) {
System.out.println("Game Over!");
} else {
System.out.println("Try Again!");
}
}
}
private class Btn11ActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
Card One = B.pop(); //Card one is from Deck B, need to compare to the button
int actionValue = Integer.parseInt(e.getActionCommand());
int cardValue = (actionValue - 1) + (One.getSuitNumber() * 13);
Card match = new Card(cardValue);
System.out.println("Match " + match + " to " + One);
if (One.equals(match)) {
System.out.println("Game Over!");
} else {
System.out.println("Try Again!");
}
}
}
private class Btn12ActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
Card One = B.pop(); //Card one is from Deck B, need to compare to the button
int actionValue = Integer.parseInt(e.getActionCommand());
int cardValue = (actionValue - 1) + (One.getSuitNumber() * 13);
Card match = new Card(cardValue);
System.out.println("Match " + match + " to " + One);
if (One.equals(match)) {
System.out.println("Game Over!");
} else {
System.out.println("Try Again!");
}
}
}
private class Btn13ActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
Card One = B.pop(); //Card one is from Deck B, need to compare to the button
int actionValue = Integer.parseInt(e.getActionCommand());
int cardValue = (actionValue - 1) + (One.getSuitNumber() * 13);
Card match = new Card(cardValue);
System.out.println("Match " + match + " to " + One);
if (One.equals(match)) {
System.out.println("Game Over!");
} else {
System.out.println("Try Again!");
}
}
}
}
First, I would put aside Window Builder, it's not doing you any favors.
Next, you need to attach an ActionListener to EACH button, in your case, you can use the same instance of ActionListener for each button as it will basically be doing the same thing.
Next, when the ActionListener is triggered, you need to ascertain which button was clicked. There's are number of ways to do this, but in your case, the actionCommand of the ActionEvent will be the text of the button, which is a number (in String format), so we can use that. Next, we need to calculate the card that the button represents, this is harder, as there are 52 cards, but only 13 cards. Assuming we only care about the value of the card and not it's face, we can use the Card from the deck to determine the suit.
Once we have both Cards, we can compare them, for that, you could simply use the equals method of the Card
Card
public class Card {
//...
#Override
public int hashCode() {
int hash = 7;
hash = 97 * hash + this.suitNum;
hash = 97 * hash + this.faceNum;
return hash;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Card other = (Card) obj;
if (this.suitNum != other.suitNum) {
return false;
}
if (this.faceNum != other.faceNum) {
return false;
}
return true;
}
}
BtnNewButtonActionListener
private class BtnNewButtonActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
Card card = B.pop(); //Card one is from Deck B, need to compare to the button
int actionValue = Integer.parseInt(e.getActionCommand());
int cardValue = (actionValue - 1) + (card.getSuitNumber() * 13);
Card match = new Card(cardValue);
System.out.println("Match " + match + " to " + card);
if (card.equals(match)) {
System.out.println("Winner");
} else {
System.out.println("Loser");
}
}
}
And finally, a runnable example, because that's a lot of information to take in...
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Collections;
import java.util.Stack;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class CardGame {
private JFrame frame;
private JLabel lblA;
private Deck B = new Deck(); //B have 52 cards, and shuffled
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
CardGame window = new CardGame();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public CardGame() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(4, 4, 4, 4);
gbc.ipadx = 15;
gbc.fill = gbc.HORIZONTAL;
for (int index = 0; index < 13; index++) {
System.out.println(index + " - " + (index % 3));
gbc.gridx = index / 6;
gbc.gridy = index % 6;
JButton btn1 = new JButton(Integer.toString(index + 1));
btn1.addActionListener(new BtnNewButtonActionListener());
frame.getContentPane().add(btn1, gbc);
}
}
private class BtnNewButtonActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
Card card = B.pop(); //Card one is from Deck B, need to compare to the button
int actionValue = Integer.parseInt(e.getActionCommand());
int cardValue = (actionValue - 1) + (card.getSuitNumber() * 13);
Card match = new Card(cardValue);
System.out.println("Match " + match + " to " + card);
if (card.equals(match)) {
System.out.println("Winner");
} else {
System.out.println("Loser");
}
}
}
public static class Card {
//Numerical equivalent of the suit and face
private int suitNum; // valid range is 0 - 3
private int faceNum; // valid range is 0 - 12
//For converting between names and numbers
public static final String[] SUITS = {"Clubs", "Hearts", "Spades", "Diamonds"};
public static final String[] FACES = {"Ace", "Two", "Three", "Four", "Five", "Six",
"Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"};
//Constructor takes combined number and splits it to suit and face numbers
public Card(int num) {
if (num > 51) {
System.out.println("Input number is larger than 51.");
System.exit(0);
}
suitNum = num / 13;
faceNum = num % 13;
}
// Return a calculated value that combines suit and face numbers
public int getTotalNumber() {
return (this.suitNum * 13 + this.faceNum);
}
public int getFaceNumber() {
return faceNum;
}
public int getSuitNumber() {
return suitNum;
}
public String toString() {
int num = getTotalNumber();
String outStr = FACES[num % 13];
outStr += " of ";
outStr += SUITS[num / 13];
return outStr;
}
#Override
public int hashCode() {
int hash = 7;
hash = 97 * hash + this.suitNum;
hash = 97 * hash + this.faceNum;
return hash;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Card other = (Card) obj;
if (this.suitNum != other.suitNum) {
return false;
}
if (this.faceNum != other.faceNum) {
return false;
}
return true;
}
}
public class Deck extends Stack<Card> {
//pop method already in the stack
// Create a new shuffled deck
public Deck() {
for (int ii = 0; ii < 52; ii++) {
push(new Card(ii));
}
Collections.shuffle(this);
}
// For debug purposes
public void printDeck() {
for (int ii = 0; ii < 52; ii++) {
System.out.println(get(ii).toString());
}
}
}
}
Have a look at How to Use Buttons, Check Boxes, and Radio Buttons, How to Write an Action Listeners, Laying Out Components Within a Container and How to Use GridBagLayout for more details
Not sure if I need to edit this class or not since the cards ARE changing. Just not in order
import java.lang.Integer;
/**
* This class is used to keep track of playing cards.
*
* #author (name)
* #version (date)
*/
public class Card implements Comparable<Card>
{
public int compareTo(Card otherCard) {
// instance variables - replace the example below with your own
private String denom, suit;
/**
* Card is to be passed in as a denomination and suit
*/
public Card(String description)
{
description = description.toUpperCase();
if( description.length() == 2)
{
suit = description.substring(1);
denom = description.substring(0,1);
} else if(description.length() == 3) {
suit = description.substring(2);
denom = description.substring(0,2);
} else {
System.out.print("Error: An invalid card code was given.");
}
}
/**
* This will give a string that states a description of the card.
* #return Card description as a string.
*/
public String getDis()
{
//get the description
String denomMessage = denom;
if(denom.equals("A"))
denomMessage = "Ace";
else if(denom.equals("K"))
denomMessage = "King";
else if(denom.equals("Q"))
denomMessage = "Queen";
else if(denom.equals("J"))
denomMessage = "Jack";
//get the suit
String suitMessage = suit;
if(suit.equals("S"))
suitMessage = "Spades";
else if(suit.equals("D"))
suitMessage = "Dimonds";
else if(suit.equals("C"))
suitMessage = "Clubs";
else if(suit.equals("H"))
suitMessage = "Hearts";
else
suitMessage = "There was a problem";
return denomMessage + " of " + suitMessage;
}
/**
* This was written for the purpose of helping to select a card image.
* #return clubs are 1, hearts are 2, spades are 3, diamonds are 4
*/
public int numSuit()
{
int value = 0;
if(suit.equals("C"))
value = 1;
else if(suit.equals("H"))
value = 2;
else if(suit.equals("S"))
value = 3;
else if(suit.equals("D"))
value = 4;
return value;
}
/**
* This class was written for the purpose of selecting a card image
* #return ace is a 1, jack is a 11, queen is a 12, king is a 13
*/
public int numDenom()
{
int value = 0;
if(denom.equals("A"))
value = 1;
else if(denom.equals("J"))
value = 11;
else if(denom.equals("Q"))
value = 12;
else if(denom.equals("K"))
value = 13;
else
value = Integer.parseInt(denom);
return value;
}
/**
* Are the two cards the same suit and denomination?
* #return true or false
*/
public boolean equals(Card a)
{
if(denom.equals(a.denom) && suit.equals(a.suit))
return true;
else
return false;
}
/**
* I would suggest that you write this method
*/
public int denomCompareTo(Card a)
{
return a.numDenom() - numDenom();
}
}
All it's doing is changing it's card to the lowest card entered. I have to make it go in order from smallest to largest. no matter what face.
import java.awt.*;
import java.io.*;
import java.applet.*;
import java.awt.image.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* This applet is currently working. It will run in a webpage. It will take in card codes such as
* 2h for the two of heart and "paint" the image of five cards when all five text fields each have a
* card coding entered into them. Your assignment will be to write the part of the code
* that will sort the cards once they have been entered so that the will be "painted" from smallest
* to largest denomination regardless of suit as long "None" is selected in the drop down box. In
* the event one of the suits is selected that suit will be placed in order first then followed by
* the rest of the cards in order. To complete the assignment you should read through this class' code
* but you will only need to change the section that state that you should change it and possibly
* the card class.
*
* #author (Put your name here.)
* #version (Put the date here.)
*/
public class CardApplet extends Applet {
Image ic1,ic2,ic3,ic4,ic5;
Card c1,c2,c3,c4,c5;
private TextField cardIn1,cardIn2,cardIn3,cardIn4,cardIn5;
private String message;
private Button enter,sort;
private ButtonListener buttonListen;
private Choice trump;
static final int CARD_WIDTH = 73;
static final int CARD_HEIGHT = 98;
/**
* This is called an inner class as it is a class writen inside of another class. It is here so
* that the buttons will be able to trigger an event.
*/
class ButtonListener implements ActionListener
{
/**
* The name of this method is important and should not be changed. This will take in the
* "action" of a button being pushed and store reference to it in the object variable e.
*/
public void actionPerformed(ActionEvent e)
{
String action = e.paramString();
if( action.indexOf("Enter") >= 0)
{
//get text
String text1 = cardIn1.getText();
String text2 = cardIn2.getText();
String text3 = cardIn3.getText();
String text4 = cardIn4.getText();
String text5 = cardIn5.getText();
//Get rid of whitespace before and after string
text1 = text1.trim();
text2 = text2.trim();
text3 = text3.trim();
text4 = text4.trim();
text5 = text5.trim();
message = "Cards Entered";
//setup cards and card images
c1 = new Card(text1);
ic1 = getCardImage(c1);
c2 = new Card(text2);
ic2 = getCardImage(c2);
c3 = new Card(text3);
ic3 = getCardImage(c3);
c4 = new Card(text4);
ic4 = getCardImage(c4);
c5 = new Card(text5);
ic5 = getCardImage(c5);
//this method call is to this class and tells the applet to follow the code of paint again.
repaint();
}
else if( action.indexOf("Sort") >= 0)
{
//ADD YOUR CODE HERE.
if(c1.denomCompareTo(c2) < 0 )
ic1 = ic2;
c1 = c2;
if(c1.denomCompareTo(c3) < 0 )
ic1 = ic3;
c1 = c3;
if(c1.denomCompareTo(c4) < 0 )
ic1 = ic4;
c1 = c4;
if(c1.denomCompareTo(c5) < 0 )
ic1 = ic5;
c1 = c5;
if(c2.denomCompareTo(c1) < 0 )
ic2 = ic1;
c2 = c1;
if(c2.denomCompareTo(c3) < 0 )
ic2 = ic3;
c2 = c3;
if(c2.denomCompareTo(c4) < 0 )
ic2 = ic4;
c2 = c4;
if(c2.denomCompareTo(c5) < 0 )
ic2 = ic5;
c2 = c5;
if(c3.denomCompareTo(c1) < 0 )
ic3 = ic1;
c3 = c1;
if(c3.denomCompareTo(c2) < 0 )
ic3 = ic2;
c3 = c2;
if(c3.denomCompareTo(c4) < 0 )
ic3 = ic4;
c3 = c4;
if(c3.denomCompareTo(c5) < 0 )
ic3 = ic5;
c3 = c5;
if(c4.denomCompareTo(c1) < 0 )
ic4 = ic1;
c4 = c1;
if(c4.denomCompareTo(c2) < 0 )
ic4 = ic2;
c4 = c2;
if(c4.denomCompareTo(c3) < 0 )
ic4 = ic3;
c4= c3;
if(c4.denomCompareTo(c5) < 0 )
ic4 = ic5;
c4 = c5;
if(c5.denomCompareTo(c1) < 0 )
ic5 = ic1;
c5 = c1;
if(c5.denomCompareTo(c2) < 0 )
ic5 = ic2;
c5 = c2;
if(c5.denomCompareTo(c3) < 0 )
ic5 = ic3;
c5 = c3;
if(c5.denomCompareTo(c4) < 0 )
ic5 = ic4;
c5 = c4;
//DO NOT CHANGE CODE PAST THIS LINE.
message = "Sorted";
repaint();
}
}
} //end of inner class.
/**
* This method is called when the applet is first started. It will setup the layout of the applet.
*/
public void init() {
//This is the text that prints in the gray box towards the bottem of the applet.
message="Let us get started ";
//Sets the back ground color of the the applet
setBackground(Color.GREEN);
// Set default layout manager
setLayout(new FlowLayout() );
//setup textboxes for entering in cards
cardIn1 = new TextField("Enter",4);
add(cardIn1);
cardIn2 = new TextField("cards ",4);
add(cardIn2);
cardIn3 = new TextField("using",4);
add(cardIn3);
cardIn4 = new TextField("Chap 5",4);
add(cardIn4);
cardIn5 = new TextField("coding",4);
add(cardIn5);
//place buttons
buttonListen = new ButtonListener();
enter = new Button("Enter");
enter.addActionListener(buttonListen);
add(enter);
sort = new Button("Sort");
sort.addActionListener(buttonListen);
add(sort);
//setup dropdown
trump = new Choice();
trump.addItem("None");
trump.addItem("Hearts");
trump.addItem("Diamonds");
trump.addItem("Spades");
trump.addItem("Clubs");
add(trump);
//Since the card object variables are null each image object variable
//will hold reference to a card back image.
ic1 = getCardImage(c1);
ic2 = getCardImage(c2);
ic3 = getCardImage(c3);
ic4 = getCardImage(c4);
ic5 = getCardImage(c5);
}
/*
* This class is used to place graphics on an applet.
*/
public void paint(Graphics g) {
//places cards on applet
int linePos = 70;
g.drawImage(ic1,19,linePos,this);
g.drawImage(ic2,19+CARD_WIDTH,linePos,this);
g.drawImage(ic3,19+2*CARD_WIDTH,linePos,this);
g.drawImage(ic4,19+3*CARD_WIDTH,linePos,this);
g.drawImage(ic5,19+4*CARD_WIDTH,linePos,this);
// simple text displayed on applet
g.setColor(Color.lightGray);
g.draw3DRect(2, 175, 200, 20, true);
g.fillRect(2, 175, 200, 20);
g.setColor(Color.black);
g.drawString(message, 4, 190);
}
/**
* This will select either the correct portion of the cards image based on the suit and denomination or
* the card back image.
* #param a The card object holds the suit and denomination in state.
* #return It returns an image object variable with holds reference to a image that was created for a card that was passed in.
* #throws MalformedURLException
*/
public Image getCardImage(final Card a)
{
int cardDenom,cardSuit;
Image playingCards = null;
ImageFilter cardFilter;
ImageProducer cardProducer;
if( a == null)
{
playingCards = getImage(getCodeBase(), "cardBack.png");
}else{
playingCards = getImage(getCodeBase(),"cards.png");
cardDenom = (a.numDenom()*CARD_WIDTH)- CARD_WIDTH;
cardSuit = (a.numSuit()*CARD_HEIGHT) - CARD_HEIGHT;
cardFilter = new CropImageFilter(cardDenom,cardSuit,CARD_WIDTH,CARD_HEIGHT);
cardProducer = new FilteredImageSource(playingCards.getSource(),cardFilter);
playingCards = createImage(cardProducer);
}
return playingCards;
}
}
nIcE cOw is correct in mentioning Comparable
from http://docs.oracle.com/javase/6/docs/api/java/lang/Comparable.html
Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
Which means that your implementation of Comparable for your objects (cards) should follow that convention.
In your top code section
public int denomCompareTo(Card a)
{
if ( a.numDenom() < this.numDenom() ) //the value of card a is less
{ return -1; }
else if ( a.numDenom() == this.numDenom() ) //equality
{ return 0; }
else //otherwise.. whatever's left (a must be greater)
{ return 1;}
}
Read that over until you understand it. Comparable is the method you want to definitely work. It's going to be invoked by calling
FirstCard.CompareTo( SecondCard );
that line of code is going to return a value of either -1, 0, or 1. Depending on which is greater, or 0 if they are equal. That's all a sorting algorithm really /needs/ to be able to figure out an ordering.
So that's the code you need for Comparable. Please look it over until you understand it.
The code in the second portion,
else if( action.indexOf("Sort") >= 0)
{
//ADD YOUR CODE HERE.
...
}
Needs to be updated to reflect how Comparable works.
So I am guessing this is a button or action thingy, and if you specify Sort then we want to sort the cards. Fair enough. Well, where are the cards stored? It looks like in a bunch of variables named c(number) and ic(number) for the image. Like c1 and ic1, c2 and ic2. In the future, look into using arrays.
So your code is almost correct for this portion! It's just that you need a temporary value to store the old card. Otherwise you're overwriting it everytime.
For example: First basket is an apple, Second basket is a grape.
If you say "Hey, put the contents of the 2nd basket into the 1st" then the first one becomes grape. The second one is also (still) grape. Where did apple go? We lost it because computers are mercilessly true to your instructions. We need to store the old card in a new variable.
So when you say
if(c1.denomCompareTo(c2) < 0 ) { //for the love of jobe please use braces for multiline if statements
ic1 = ic2;
c1 = c2;
}
The original ic1 and c1 are being overwritten and lost.
You can fix this by using a temporary variable or swapping variable, or when you get really clever, using XOR (ask your nerdy friends)
Image tempImg;
Card tempCard;
if(c1.denomCompareTo(c2) < 0 ) { //meaning if card1 is less than card2
tempImg = ic1; //store card1 temporarily
tempCard = c1;
ic1 = ic2; //copy vals of card2 to card1 slots
c1 = c2;
ic2 = tempImg; //slide the original val of ic1 here
c2 = tempCard;
}
Granted, your sorting algorithm is accurate, but will require many passes if the cards are in any funky ordering. Which is why you'll probably have to loop over these instructions several times. You're doing something incrementally usually referred to as "bubble sort" ... If you need help looping over your sorting, just let us know.
Here are some examples:
I am posting a very quick reference example for you to look at. It is not that tough to understand, though, once you will understand it, things will become a bit more easier.
import java.util.*;
enum Suit {
HEART,
DIAMOND,
CLUB,
SPADE
}
class Card implements Comparable<Card> {
private int rank;
private Suit suit;
public Card ( int rank, Suit suit ) {
this.rank = rank;
this.suit = suit;
}
public int getRank () {
return rank;
}
public void setRank ( int rank ) {
this.rank = rank;
}
public Suit getSuit () {
return suit;
}
public void setSuit ( Suit suit ) {
this.suit = suit;
}
#Override
public int compareTo ( Card anotherCard ) {
return this.rank - anotherCard.rank;
}
#Override
public String toString () {
return String.format ("Suit: %8s Rank: %8s", suit, rank);
}
}
public class CardsExample {
private static final int TOTAL_CARDS = 52;
private static final int CARDS_PER_SUIT = 13;
private static final int TOTAL_SUITS = 4;
private List<Card> deck;
public CardsExample () {
deck = new ArrayList<Card> ();
}
private void createDeck () {
for ( Suit suit : Suit.values () ) {
for ( int i = 0; i < CARDS_PER_SUIT; ++i ) {
deck.add ( new Card ( i, suit ) );
}
}
}
private void displayDeck () {
for ( Card card : deck ) {
System.out.println ( card );
}
}
private void performTask () {
createDeck ();
Collections.shuffle ( deck );
System.out.println ( "Before SORTING" );
displayDeck ();
Collections.sort ( deck );
System.out.println ( "After SORTING" );
displayDeck ();
}
public static void main ( String[] args ) {
new CardsExample ().performTask ();
}
}
EDIT:
If one wants to sort cards, in terms of their Suit first, then one can use Comparatortoo, in this example, for which not much of a change is required, just change the enum part, as shown below and provide implementation for Comparator < Card >, within the Cardclass, and let Collections.sort ( deck, suitComparator )do the work, as shown in this example.
import java.util.*;
enum Suit {
HEART ( 0 ),
DIAMOND ( 1 ),
CLUB ( 2 ),
SPADE ( 3 );
private int value;
private Suit ( int value ) {
this.value = value;
}
public int retrieveValue () {
return value;
}
}
class Card implements Comparable < Card > {
private int rank;
private Suit suit;
public static Comparator < Card > suitComparator =
new Comparator < Card > () {
#Override
public int compare ( Card someCard, Card anotherCard ) {
return someCard.suit.retrieveValue () - anotherCard.suit.retrieveValue ();
}
};
public Card ( int rank, Suit suit ) {
this.rank = rank;
this.suit = suit;
}
public int getRank () {
return rank;
}
public void setRank ( int rank ) {
this.rank = rank;
}
public Suit getSuit () {
return suit;
}
public void setSuit ( Suit suit ) {
this.suit = suit;
}
#Override
public int compareTo ( Card anotherCard ) {
return this.rank - anotherCard.rank;
}
#Override
public String toString () {
return String.format ( "Suit: %8s Rank: %8s", suit, rank );
}
}
public class CardsExample {
private static final int TOTAL_CARDS = 52;
private static final int CARDS_PER_SUIT = 13;
private static final int TOTAL_SUITS = 4;
private List < Card > deck;
public CardsExample () {
deck = new ArrayList < Card > ();
}
private void createDeck () {
for ( Suit suit : Suit.values () ) {
for ( int i = 0; i < CARDS_PER_SUIT; ++i ) {
deck.add ( new Card ( i, suit ) );
}
}
}
private void displayDeck () {
for ( Card card : deck ) {
System.out.println ( card );
}
}
private void performTask () {
createDeck ();
Collections.shuffle ( deck );
System.out.println ( "Before SORTING" );
displayDeck ();
Collections.sort ( deck );
Collections.sort ( deck, Card.suitComparator );
System.out.println ( "After SORTING" );
displayDeck ();
}
public static void main ( String[] args ) {
new CardsExample ().performTask ();
}
}
Good luck
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.