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.
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 am programming a very basic bot for planet wars in java and I cant seem to find the errors in my code. I am receiving a few different error messages but the main issue for me is the error: class, interface, or enum expected. Ive checked my brackets about a thousand times. Any help would be appreciated. Here's my bot code:
import java.util.List;
import java.util.Random;
import shared.Planet;
import shared.PlanetWars;
public class MyNewBot {
public static void doTurn(PlanetWars pw) {
// (1) If we currently have a fleet in flight, then do nothing until
// it arrives.
if (pw.myFleets().size() >= 10) {
return;
}
// (2) Pick one of my planets based on the number of ships
Planet source = null;
int largestForce = 0;
for (Planet p : pw.myPlanets()){
int force = pw.numShips();
if( force > largestForce){
largestForce = force;
source = p;
}
}
// (3) Pick a target planet at random.
Planet dest = null;
int highestGrowthRate = 0;
int shortestDistance = 9999;
for (Planet p = pw.notMyPlanets()){
int growthRate = pw.growthRate();
if( growthRate > highestGrowthRate){
highestGrowthRate = growthRate;
dest = p;
}else if (growthRate == highestGrowthRate){
int distance = pw.distance(source,p);
if (distance < shortestDistance){
shortestDistance = distance;
dest = p;
}
}
}
// (4) Send half the ships from source to destination.
if (source != null && dest != null) {
int numShips = source.numShips() / 2;
pw.issueOrder(source, dest, numShips);
}
}
// Ignore the main method unless you know what you're doing.
// Refer to the doTurn function to code your bot.
public static void main(String[] args) {
String line = "";
String message = "";
int c;
try {
while ((c = System.in.read()) >= 0) {
switch (c) {
case '\n':
if (line.equals("go")) {
PlanetWars pw = new PlanetWars(message);
doTurn(pw);
pw.finishTurn();
message = "";
} else {
message += line + "\n";
}
line = "";
break;
default:
line += (char) c;
break;
}
}
} catch (Exception e) {
// Owned.
}
}
}
and the supporting class files:
package shared;
public class Planet implements Cloneable {
private int planetID;
private int owner;
private int numShips;
private int growthRate;
private double x, y;
public Planet(int planetID, int owner, int numShips, int growthRate,
double x, double y) {
this.planetID = planetID;
this.owner = owner;
this.numShips = numShips;
this.growthRate = growthRate;
this.x = x;
this.y = y;
}
public int planetID() {
return planetID;
}
public int owner() {
return owner;
}
public int numShips() {
return numShips;
}
public int growthRate() {
return growthRate;
}
public double x() {
return x;
}
public double y() {
return y;
}
public void owner(int newOwner) {
this.owner = newOwner;
}
public void numShips(int newNumShips) {
this.numShips = newNumShips;
}
public void addShips(int amount) {
numShips += amount;
}
public void removeShips(int amount) {
numShips -= amount;
}
private Planet(Planet _p) {
planetID = _p.planetID;
owner = _p.owner;
numShips = _p.numShips;
growthRate = _p.growthRate;
x = _p.x;
y = _p.y;
}
public Object clone() {
return new Planet(this);
}
}
package shared;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
public class PlanetWars {
// Constructs a PlanetWars object instance, given a string containing a
// description of a game state.
public PlanetWars(String gameStateString) {
planets = new ArrayList<Planet>();
fleets = new ArrayList<Fleet>();
parseGameState(gameStateString);
}
// Returns the number of planets. Planets are numbered starting with 0.
public int numPlanets() {
return planets.size();
}
// Returns the planet with the given planet_id. There are NumPlanets()
// planets. They are numbered starting at 0.
public Planet getPlanet(int planetID) {
return planets.get(planetID);
}
// Returns the number of fleets.
public int numFleets() {
return fleets.size();
}
// Returns the fleet with the given fleet_id. Fleets are numbered starting
// with 0. There are NumFleets() fleets. fleet_id's are not consistent from
// one turn to the next.
public Fleet getFleet(int fleetID) {
return fleets.get(fleetID);
}
// Returns a list of all the planets.
public List<Planet> planets() {
return planets;
}
// Return a list of all the planets owned by the current player. By
// convention, the current player is always player number 1.
public List<Planet> myPlanets() {
List<Planet> r = new ArrayList<Planet>();
for (Planet p : planets) {
if (p.owner() == 1) {
r.add(p);
}
}
return r;
}
// Return a list of all neutral planets.
public List<Planet> neutralPlanets() {
List<Planet> r = new ArrayList<Planet>();
for (Planet p : planets) {
if (p.owner() == 0) {
r.add(p);
}
}
return r;
}
// Return a list of all the planets owned by rival players. This excludes
// planets owned by the current player, as well as neutral planets.
public List<Planet> enemyPlanets() {
List<Planet> r = new ArrayList<Planet>();
for (Planet p : planets) {
if (p.owner() >= 2) {
r.add(p);
}
}
return r;
}
// Return a list of all the planets that are not owned by the current
// player. This includes all enemy planets and neutral planets.
public List<Planet> notMyPlanets() {
List<Planet> r = new ArrayList<Planet>();
for (Planet p : planets) {
if (p.owner() != 1) {
r.add(p);
}
}
return r;
}
// Return a list of all the fleets.
public List<Fleet> fleets() {
List<Fleet> r = new ArrayList<Fleet>();
for (Fleet f : fleets) {
r.add(f);
}
return r;
}
// Return a list of all the fleets owned by the current player.
public List<Fleet> myFleets() {
List<Fleet> r = new ArrayList<Fleet>();
for (Fleet f : fleets) {
if (f.owner() == 1) {
r.add(f);
}
}
return r;
}
// Return a list of all the fleets owned by enemy players.
public List<Fleet> enemyFleets() {
List<Fleet> r = new ArrayList<Fleet>();
for (Fleet f : fleets) {
if (f.owner() != 1) {
r.add(f);
}
}
return r;
}
// Returns the distance between two planets, rounded up to the next highest
// integer. This is the number of discrete time steps it takes to get
// between the two planets.
public int distance(int sourcePlanet, int destinationPlanet) {
Planet source = planets.get(sourcePlanet);
Planet destination = planets.get(destinationPlanet);
double dx = source.x() - destination.x();
double dy = source.y() - destination.y();
return (int) Math.ceil(Math.sqrt(dx * dx + dy * dy));
}
// Returns the distance between two planets, rounded up to the next highest
// integer. This is the number of discrete time steps it takes to get
// between the two planets.
public int distance(Planet source, Planet destination) {
double dx = source.x() - destination.x();
double dy = source.y() - destination.y();
return (int) Math.ceil(Math.sqrt(dx * dx + dy * dy));
}
// Sends an order to the game engine. An order is composed of a source
// planet number, a destination planet number, and a number of ships. A
// few things to keep in mind:
// * you can issue many orders per turn if you like.
// * the planets are numbered starting at zero, not one.
// * you must own the source planet. If you break this rule, the game
// engine kicks your bot out of the game instantly.
// * you can't move more ships than are currently on the source planet.
// * the ships will take a few turns to reach their destination. Travel
// is not instant. See the Distance() function for more info.
public void issueOrder(int sourcePlanet, int destinationPlanet, int
numShips) {
System.out.println("" + sourcePlanet + " " + destinationPlanet + " "
+ numShips);
System.out.flush();
}
// Sends an order to the game engine. An order is composed of a source
// planet number, a destination planet number, and a number of ships. A
// few things to keep in mind:
// * you can issue many orders per turn if you like.
// * the planets are numbered starting at zero, not one.
// * you must own the source planet. If you break this rule, the game
// engine kicks your bot out of the game instantly.
// * you can't move more ships than are currently on the source planet.
// * the ships will take a few turns to reach their destination. Travel
// is not instant. See the Distance() function for more info.
public void issueOrder(Planet source, Planet dest, int numShips) {
System.out.println("" + source.planetID() + " " + dest.planetID() + " "
+ numShips);
System.out.flush();
}
// Sends the game engine a message to let it know that we're done sending
// orders. This signifies the end of our turn.
public void finishTurn() {
System.out.println("go");
System.out.flush();
}
// Returns true if the named player owns at least one planet or fleet.
// Otherwise, the player is deemed to be dead and false is returned.
public boolean isAlive(int playerID) {
for (Planet p : planets) {
if (p.owner() == playerID) {
return true;
}
}
for (Fleet f : fleets) {
if (f.owner() == playerID) {
return true;
}
}
return false;
}
// If the game is not yet over (ie: at least two players have planets or
// fleets remaining), returns -1. If the game is over (ie: only one player
// is left) then that player's number is returned. If there are no
// remaining players, then the game is a draw and 0 is returned.
public int winner() {
Set<Integer> remainingPlayers = new TreeSet<Integer>();
for (Planet p : planets) {
remainingPlayers.add(p.owner());
}
for (Fleet f : fleets) {
remainingPlayers.add(f.owner());
}
switch (remainingPlayers.size()) {
case 0:
return 0;
case 1:
return ((Integer) remainingPlayers.toArray()[0]).intValue();
default:
return -1;
}
}
// Returns the number of ships that the current player has, either located
// on planets or in flight.
public int numShips(int playerID) {
int numShips = 0;
for (Planet p : planets) {
if (p.owner() == playerID) {
numShips += p.numShips();
}
}
for (Fleet f : fleets) {
if (f.owner() == playerID) {
numShips += f.numShips();
}
}
return numShips;
}
// Returns the production of the given player.
public int production(int playerID) {
int prod = 0;
for (Planet p : planets) {
if (p.owner() == playerID) {
prod += p.growthRate();
}
}
return prod;
}
// Parses a game state from a string. On success, returns 1. On failure,
// returns 0.
private int parseGameState(String s) {
planets.clear();
fleets.clear();
int planetID = 0;
String[] lines = s.split("\n");
for (int i = 0; i < lines.length; ++i) {
String line = lines[i];
int commentBegin = line.indexOf('#');
if (commentBegin >= 0) {
line = line.substring(0, commentBegin);
}
if (line.trim().length() == 0) {
continue;
}
String[] tokens = line.split(" ");
if (tokens.length == 0) {
continue;
}
if (tokens[0].equals("P")) {
if (tokens.length != 6) {
return 0;
}
double x = Double.parseDouble(tokens[1]);
double y = Double.parseDouble(tokens[2]);
int owner = Integer.parseInt(tokens[3]);
int numShips = Integer.parseInt(tokens[4]);
int growthRate = Integer.parseInt(tokens[5]);
Planet p = new Planet(planetID++, owner, numShips, growthRate,
x, y);
planets.add(p);
} else if (tokens[0].equals("F")) {
if (tokens.length != 7) {
return 0;
}
int owner = Integer.parseInt(tokens[1]);
int numShips = Integer.parseInt(tokens[2]);
int source = Integer.parseInt(tokens[3]);
int destination = Integer.parseInt(tokens[4]);
int totalTripLength = Integer.parseInt(tokens[5]);
int turnsRemaining = Integer.parseInt(tokens[6]);
Fleet f = new Fleet(owner, numShips, source, destination,
totalTripLength, turnsRemaining);
fleets.add(f);
} else {
return 0;
}
}
return 1;
}
// Store all the planets and fleets. OMG we wouldn't wanna lose all the
// planets and fleets, would we!?
private ArrayList<Planet> planets;
private ArrayList<Fleet> fleets;
}
package shared;
public class Fleet implements Comparable<Fleet>, Cloneable {
private int owner;
private int numShips;
private int sourcePlanet;
private int destinationPlanet;
private int totalTripLength;
private int turnsRemaining;
public Fleet(int owner, int numShips, int sourcePlanet,
int destinationPlanet, int totalTripLength, int turnsRemaining) {
this.owner = owner;
this.numShips = numShips;
this.sourcePlanet = sourcePlanet;
this.destinationPlanet = destinationPlanet;
this.totalTripLength = totalTripLength;
this.turnsRemaining = turnsRemaining;
}
public Fleet(int owner, int numShips) {
this.owner = owner;
this.numShips = numShips;
this.sourcePlanet = -1;
this.destinationPlanet = -1;
this.totalTripLength = -1;
this.turnsRemaining = -1;
}
public int owner() {
return owner;
}
public int numShips() {
return numShips;
}
public int sourcePlanet() {
return sourcePlanet;
}
public int destinationPlanet() {
return destinationPlanet;
}
public int totalTripLength() {
return totalTripLength;
}
public int turnsRemaining() {
return turnsRemaining;
}
public void removeShips(int amount) {
numShips -= amount;
}
// Subtracts one turn remaining. Call this function to make the fleet get
// one turn closer to its destination.
public void TimeStep() {
if (turnsRemaining > 0) {
--turnsRemaining;
} else {
turnsRemaining = 0;
}
}
#Override
public int compareTo(Fleet f) {
return this.numShips - f.numShips;
}
private Fleet(Fleet _f) {
owner = _f.owner;
numShips = _f.numShips;
sourcePlanet = _f.sourcePlanet;
destinationPlanet = _f.destinationPlanet;
totalTripLength = _f.totalTripLength;
turnsRemaining = _f.turnsRemaining;
}
public Object clone() {
return new Fleet(this);
}
}
for (Planet p = pw.notMyPlanets()){ should be for (Planet p : pw.notMyPlanets()){.
You've not posted the Fleet class, so as it is the code won't compile for me. However, the above is the only other error I could see.
All of the program's templates. This was a past assignment but at this point, I'm just trying to understand what's going on.
Under the Apartment class, I'm confused on how to correctly return an array of window orders for one unit, all units, and then the #Override method under ThreeBedroom.
Just for reference of what I've done so far (probably not all correct):
public class Window {
private final int width, height;
public Window(int width, int height) {
this.width = width;
this.height = height;
}
// print text like: 4 X 6 window
public String toString() {
String s = "";
s = width + " x " + height + " window";
return s;
}
// compare window objects by their dimensions
public boolean equals(Object that) {
if (that instanceof Window) {
Window w = (Window) that;
return this.width == w.width && this.height == w.height;
}
else { return false; }
}
}
class WindowOrder {
final Window window; // window description (its width and height)
int num; // number of windows for this order
WindowOrder(Window window, int num) {
this.window = window;
this.num = num;
}
// add the num field of the parameter to the num field of this object
//
// BUT
//
// do the merging only of two windows have the same size
// do nothing if the size does not match
//
// return the current object
WindowOrder add(WindowOrder order) {
if (order.equals(window)) {
this.num -= num;
return order;
}
else {
return order;
}
}
// update the num field of this object by multiplying it with the parameter
// and then return the current object
WindowOrder times(int number) {
WindowOrder window = new WindowOrder(this.window, this.num);
this.num *= number;
return window;
}
// print text like: 20 4 X 6 window
#Override
public String toString() {
String s = "";
s = num + " " + window.toString();
return s;
}
// Two orders are equal if they contain the same number of windows of the same size.
#Override
public boolean equals(Object that) {
if (that instanceof WindowOrder) {
WindowOrder order = (WindowOrder) that;
return this.num == order.num && this.window == order.window;
}
else { return false; }
}
}
public class Room {
Window window;
int numOfWindows;
Room(Window window, int numOfWindows) {
this.window = window;
this.numOfWindows = numOfWindows;
}
WindowOrder order() {
return new WindowOrder(window, numOfWindows);
}
// Print text like: 5 (6 X 8 window)
#Override
public String toString() {
String s = "";
s = numOfWindows + " (" + window.toString() + ")";
return s;
}
// Two rooms are equal if they contain the same number of windows of the same size
#Override
public boolean equals(Object that) {
if (that instanceof Room) {
Room room = (Room) that;
return this.window == room.window && this.numOfWindows == room.numOfWindows;
}
else { return false; }
}
}
class MasterBedroom extends Room {
MasterBedroom() {
super(new Window(4, 6), 3);
}
// Call parent's toString method
//
// return text like: Master bedroom: 3 (4 X 6 window)
#Override
public String toString() {
String s = "";
s = "Master bedroom: " + numOfWindows + " " + window.toString();
return s;
}
}
class GuestRoom extends Room {
GuestRoom() {
super(new Window(5, 6), 2);
}
// Call parent's toString method
//
// return text like: Guest room: 2 (5 X 6 window)
#Override
public String toString() {
String s = "";
s = "Guest room: " + numOfWindows + " " + window.toString();
return s;
}
}
class LivingRoom extends Room {
LivingRoom() {
super(new Window(6, 8), 5);
}
// Call parent's toString method
//
// return text like: Living room: 5 (6 X 8 window)
#Override
public String toString() {
String s = "";
s = "Living room: " + numOfWindows + " " + window.toString();
return s;
}
}
For Apartment's orderForOneUnit() method, I wrote this, but it seems to simplistic and I feel like I should be using a for loop..
WindowOrder[] orderForOneUnit() {
WindowOrder[] order = new WindowOrder[rooms.length];
return order;
}
Am I even close to correctly understanding this? What should be under the Apartment methods?
Didn't looks at the templates but from what you've provided, you're close. All you've done so far is create a WindowOrder[] array of length rooms. You need to add new WindowOrder(desc, num) to these arrays before return order;
/**
* All apartment rooms have the same number of windows, with the
* same size window for each of those.
*/
public class Apartment
{
private int numRooms_;
private int windowsPerRoom_;
private Window window_;
/**
* Constructor
*/
public Apartment(numRooms, windowsPerRoom, desiredWindowHeight, desiredWindowLength)
{
numRooms_ = numRooms;
windowsPerRoom_ = windowsPerRoom;
window_ = new Window(desiredWindowHeight, desiredWindowLenght);
}
/**
* Orders for one room in apartment
*/
public WindowOrder orderForOneUnit()
{
WindowOrder order = new WindowOrder(window_, 1);
return order;
}
/**
* Orders for all rooms in apartment
*/
public List<WindowOrder> orderForAllUnits()
{
List<WindowOrder> orders = new ArrayList<WindowOrder>();
WindowOrder order;
for(i=0; i<numRooms_; i++)
{
orders.add(new WindowOrder(window_, windowsPerRoom_);
}
return orders;
}
}
Now when you're in your code and you're ready for a new Apartment(x, x, x, x) you can do the following (I'll assume you're just in main())
public class ApartmentComplex
{
public static void main(String[] args)
{
int numWindowsPerRoom = 3;
int desiredWindowHeight = 10;
int desiredWindowWidth = 10;
int numRooms = 5;
Apartment aptWithFiveRooms = new Apartment(numRooms, numWindowsPerRoom, desiredWindowHeight, desiredWindowWidth);
WindowOrder singleSingleOrder = apt.orderForOneUnit();
List<WindowOrder> allRoomsOrder = apt.orderForAllUnits();
numRooms = 3;
Apartment aptWithThreeRooms = new Apartment(numRooms, numWindowsPerRoom, desiredWindowHeight, desiredWindowWidth);
List<WindowOrder> threeRoomsOrder = apt.orderForAllUnits();
}
}
You do need a for loop. At the moment you are returning an Array where each entry in the array is null.
Here is an example of filling an array:
for (int i = 0; i < array.length; i++) { // iterate over an array
array[i] = getValueFor(i); // put value in the array
}
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;
}