SlideShare a Scribd company logo
1 of 8
Download to read offline
FaceUp card game
In this assignment we will implement a made-up card game we'll call FaceUp. When the game
starts, you deal five cards face down. Your goal is to achieve as high a score as possible. Your
score only includes cards that are face up. Red cards (hearts and diamonds) award positive
points, while black cards (clubs and spades) award negative points. Cards 2-10 have points worth
their face value. Cards Jack, Queen, and King have value 10, and Ace is 11.
The game is played by flipping over cards, either from face-down to face-up or from face-up to
face-down. As you play, you are told your total score (ie, total of the face-up cards) and the total
score of the cards that are face down. The challenge is that you only get up to a fixed number of
flips and then the game is over.
Here is an example of the output from playing the game:
At each point where the program asks the user to pick a card, the game waits for user input.
Code
Well implement the game using five classes, three of which you'll leave unchanged, and two you
will modify and submit:
Card: Leave this code unchanged.
CardDealer: Leave this code unchanged.
FaceUpCard: This class extends the Card class with additional functionality. You will add two
methods needed for the FaceUp game.
FaceUpHand: This class keeps track of the state of the game. Most of the methods you will
implement are here.
FaceUpGame: This class implements the game interface. It gets data from the user, updates the
board, and repeats the process. Leave this code unchanged.
How to proceed
You may fill in the details of the FaceUpCard and FaceUpHandclasses however youd like, but
heres what we recommend.
Add the two methods to the FaceUpCard class (described in comments in the code). Add a main
method to this class and test them to make sure they work.
Read through the other two new classes FaceUpHand and FaceUpGame. Make sure you
understand what all of the methods in FaceUpHand are supposed to do and that you understand
how theyre used in the FaceUpGame class.
Implement methods in the FaceUpHand class incrementally. Write one method and then test it!
To test it, again, add a main method and write a small test or two to make sure it behaves like
youd expect. If you try to implement all of the methods and then test it by simply running
FaceUpGame, 1) its very unlikely youll get it perfect the first time and then 2) its going to be very
hard to figure out where the problem is.
Card.java
public class Card {
// min/max for the card number range
private static final int MIN_NUMBER = 1;
private static final int MAX_NUMBER = 13;
private int number;
private String suit;
/**
* Create a new card with number and suit. If the a valid
* suit/number is not input, the card defaults to 1 of hearts.
*
* @param number the card number
* @param suit the card suit
*/
public Card(int number, String suit){
this.number = number;
this.suit = suit.toLowerCase();
if (!isValidSuit(suit)) {
System.out.println(suit + "Is not a valid suit!");
System.out.println("Must be one of: clubs, diamonds, hearts or spades");
System.out.println("Defaulting to hearts");
this.suit = "hearts";
}
if (!isValidNumber(number)) {
System.out.println(number + "Is not a valid number!");
System.out.println("Must be between " + MIN_NUMBER + " and " + MAX_NUMBER);
System.out.println("Defaulting to 1");
this.number = 1;
}
}
/**
* @return the card's suit
*/
public String getSuit(){
return suit;
}
/**
* @return the card's number MIN_NUMBER .. MAX_NUMBER
*/
public int getNumber() {
return number;
}
/**
* Returns the card's rank as a string
* changing Jack, Queen, King, Ace appropriately
*
* @return the card's rank
*/
public String getRank() {
if (number == 1) {
return "Ace";
} else if (number >= 2 && number <= 10) {
return Integer.toString(number);
} else if (number == 11) {
return "Jack";
} else if (number == 12) {
return "Queen";
} else {
return "King";
}
}
/**
* The card's rank followed by the suit
*/
public String toString() {
return getRank() + " of " + getSuit();
}
/**
* Make it an Ace!
*/
public void cheat() {
number = 1; // ACE!
}
/**
* Check to make sure the card number is valid
*
* @param num potential card number
* @return whether the card number is valid
*/
private boolean isValidNumber(int num) {
return num >= MIN_NUMBER && num <= MAX_NUMBER;
}
/**
* Check to make sure the suit is valid
*
* @param s potential suit
* @return whether the suit is valid
*/
private boolean isValidSuit(String s) {
return s.equals("spades") ||
s.equals("hearts") ||
s.equals("clubs") ||
s.equals("diamonds");
}
}
CardDealer.java
public class CardDealer {
private static final int CARDS_PER_SUIT = 13; // the number of cards in the deck
private static final String[] suits = {"clubs", "diamonds", "hearts", "spades"};
private FaceUpCard[] cards; // all of the cards to be dealt
private int position; // our current position in our stack of cards
/**
* Creates a new card dealer with numDecks decks in the deck
*
* @param numDecks the number of card decks to use
*/
public CardDealer(int numDecks) {
int numCards = numDecks * CARDS_PER_SUIT * suits.length;
cards = new FaceUpCard[numCards];
int cardIndex = 0;
for (int i = 0; i < numDecks; i++) {
for (int suitIndex = 0; suitIndex < suits.length; suitIndex++) {
for (int numIndex = 1; numIndex <= CARDS_PER_SUIT; numIndex++) {
cards[cardIndex] = new FaceUpCard(numIndex, suits[suitIndex]);
cardIndex++;
}
}
}
shuffle();
}
/**
* Returns true if there are cards left in the deck, false otherwise
*/
public boolean hasNext() {
return position < cards.length;
}
/**
* Returns the next card from the deck
*
* @pre assumes there are cards left in the deck (i.e. hasNext() is true)
*/
public FaceUpCard next() {
position++;
return cards[position-1];
}
/**
* Randomly shuffles the deck and resets the card to be dealt as the first card
*/
public void shuffle() {
Random rand = new Random();
for (int i = 0; i < cards.length; i++) {
int nextPosition = rand.nextInt(cards.length);
// swap this card with the card at next position
FaceUpCard temp = cards[i];
cards[i] = cards[nextPosition];
cards[nextPosition] = temp;
}
position = 0;
}
/**
* Tests the CardDealer class
*/
public static void main(String[] args) {
CardDealer dealer = new CardDealer(2);
for (int i = 0; i < 100; i++) {
System.out.println(dealer.next());
}
}
}
FaceUpCard.java
public class FaceUpCard extends Card {
private boolean faceUp;
/**
* Create a new FaceUpCard with number and suit
* @param number the card number
* @param suit the card suit
*/
public FaceUpCard(int number, String suit) {
super(number, suit);
faceUp = false;
}
/**
* Returns whether card is face up
*/
public boolean isFaceUp() {
return faceUp;
}
/**
* Flips a card from face-down to face-up or face-up to face-down
*/
public void flip() {
faceUp = !faceUp;
}
/**
* Returns the card's value in the FaceUp game
* Number cards have their number as the value
* Ace is 11, and Jack, Queen, and King are 10
*/
public int getCardValue() {
// TODO: fill in method definition; replace placeholder on next line
return 0;
}
/**
* Returns whether card is a red card, ie with suit "hearts" or "diamonds"
*/
public boolean isRedCard() {
// TODO: fill in method definition; replace placeholder on next line
return false;
}
}
FaceUpGame.java
public class FaceUpGame {
private static final int NUM_CARDS = 5;
public static void playGame(int numRounds) {
FaceUpHand cards = new FaceUpHand(NUM_CARDS);
Scanner in = new Scanner(System.in);
int flipsLeft = numRounds;
while (flipsLeft > 0) {
System.out.println(cards);
System.out.println("Face up total: " + cards.faceUpTotal());
System.out.println("Face down total: " + cards.faceDownTotal());
System.out.println("Number of flips left: " + flipsLeft);
System.out.print("Pick a card to flip between 1 and " + NUM_CARDS + " (-1 to end game): ");
int num = in.nextInt();
System.out.println();
if (num == -1) {
flipsLeft = 0;
} else if (num < 1 || num > NUM_CARDS) {
System.out.println(num + " is not a valid card");
} else {
cards.flipCard(num-1);
flipsLeft--;
}
}
in.close();
System.out.println();
System.out.println("----------------------");
System.out.println("Your score: " + cards.faceUpTotal());
System.out.println("Best possible score: " + cards.calculateOptimal());
}
public static void main(String[] args) {
playGame(5);
FaceUpHand.java
/*** Keeps track of the cards and and answers questions
* for the FaceUp card game.
* Red cards (hearts and diamonds) award positive points, while black cards
* (clubs and spades) award negative points. Cards 2-10 have points worth
* their face value; Jack, Queen and King are 10; and Ace is 11.*/
public class FaceUpHand {
private FaceUpCard[] cards;
/*** Create a new FaceUp card game state, which consists of the
* array cards of size numCards
*
* @param numCards number of cards in the game*/
public FaceUpHand(int numCards) {
// TODO: fill in method definition to initialize the cards array
// 1. set the instance variable cards equal to a new array (size numCards) of type FaceUpCard
// 2. create a variable dealer of type CardDealer for 1 deck
// 3. loop through the cards array and set each value to dealer.next()
}
/*** Return the FaceUpCard in position cardIndex of cards
* @return the element of cards specified by cardIndex*/
public FaceUpCard getCard(int cardIndex) {
// TODO: fill in method definition; replace placeholder on next line
return null;
}
/*** Flip the card over at this index
* Card indices start at 0 and go up the cards.length-1*
* @param cardIndex the index of the card to flip over*/
public void flipCard(int cardIndex) {
// TODO: fill in method definition
}
/*** Calculate the best possible score for the current cards*
* @return the optimal score*/
public int calculateOptimal() {
// TODO: fill in method definition; replace placeholder on next line
return 0;
}
/*** Calculate the total score for the cards that are face up
* @return the total score for face-up cards*/
public int faceUpTotal() {
// Hint: use getCardValue() and remember red cards have positive value
// and black cards have negative value
// TODO: fill in method definition; replace placeholder on next line
return 0;
}
/*** Calculate the total score for the cards that are face down*
* @return the total score for face-down cards
*/
public int faceDownTotal() {
// Hint: use getCardValue() and remember red cards have positive value
// and black cards have negative value
// TODO: fill in method definition; replace placeholder on next line
return 0;
}
// TODO: add a toString method here!
}

More Related Content

Similar to FaceUp card game In this assignment we will implement a made.pdf

Comp 220 i lab 1 two dimensional arrays lab report and source code
Comp 220 i lab 1 two dimensional arrays lab report and source codeComp 220 i lab 1 two dimensional arrays lab report and source code
Comp 220 i lab 1 two dimensional arrays lab report and source codepradesigali1
 
blackjackrevised2BlackJack.hBLACKJACK#ifndef _BLACKJA.docx
blackjackrevised2BlackJack.hBLACKJACK#ifndef _BLACKJA.docxblackjackrevised2BlackJack.hBLACKJACK#ifndef _BLACKJA.docx
blackjackrevised2BlackJack.hBLACKJACK#ifndef _BLACKJA.docxAASTHA76
 
Can someone help me setup this in JAVA Im new to java. Thanks.pdf
Can someone help me setup this in JAVA Im new to java. Thanks.pdfCan someone help me setup this in JAVA Im new to java. Thanks.pdf
Can someone help me setup this in JAVA Im new to java. Thanks.pdfjeeteshmalani1
 
QuestionProblem 1 In a source file carddeck.cpp, provide an impl.pdf
QuestionProblem 1 In a source file carddeck.cpp, provide an impl.pdfQuestionProblem 1 In a source file carddeck.cpp, provide an impl.pdf
QuestionProblem 1 In a source file carddeck.cpp, provide an impl.pdffootstatus
 
PLEASE can do this in NETBEAN I need that way thank very muchManca.pdf
PLEASE can do this in NETBEAN I need that way thank very muchManca.pdfPLEASE can do this in NETBEAN I need that way thank very muchManca.pdf
PLEASE can do this in NETBEAN I need that way thank very muchManca.pdfkennithdase
 
There are 5 C++ files below- Card-h- Card-cpp- Deck-h- Deck-cpp- Main-.docx
There are 5 C++ files below- Card-h- Card-cpp- Deck-h- Deck-cpp- Main-.docxThere are 5 C++ files below- Card-h- Card-cpp- Deck-h- Deck-cpp- Main-.docx
There are 5 C++ files below- Card-h- Card-cpp- Deck-h- Deck-cpp- Main-.docxAustinIKkNorthy
 
COMP 220 HELP Lessons in Excellence--comp220help.com
COMP 220 HELP Lessons in Excellence--comp220help.comCOMP 220 HELP Lessons in Excellence--comp220help.com
COMP 220 HELP Lessons in Excellence--comp220help.comthomashard85
 
NO PAPER ANSWERS. ALL ANSWER SUBMISSIONS SHOULD BE ABLE TO RUN WIT.pdf
NO PAPER ANSWERS. ALL ANSWER SUBMISSIONS SHOULD BE ABLE TO RUN WIT.pdfNO PAPER ANSWERS. ALL ANSWER SUBMISSIONS SHOULD BE ABLE TO RUN WIT.pdf
NO PAPER ANSWERS. ALL ANSWER SUBMISSIONS SHOULD BE ABLE TO RUN WIT.pdffms12345
 
I have another assignment due for an advance java programming class .pdf
I have another assignment due for an advance java programming class .pdfI have another assignment due for an advance java programming class .pdf
I have another assignment due for an advance java programming class .pdfFORTUNE2505
 
BlackJackBlackjack.c Blackjack.c Defines the entry point .docx
BlackJackBlackjack.c Blackjack.c  Defines the entry point .docxBlackJackBlackjack.c Blackjack.c  Defines the entry point .docx
BlackJackBlackjack.c Blackjack.c Defines the entry point .docxAASTHA76
 
public interface Game Note interface in place of class { .pdf
public interface Game  Note interface in place of class { .pdfpublic interface Game  Note interface in place of class { .pdf
public interface Game Note interface in place of class { .pdfkavithaarp
 

Similar to FaceUp card game In this assignment we will implement a made.pdf (13)

Comp 220 i lab 1 two dimensional arrays lab report and source code
Comp 220 i lab 1 two dimensional arrays lab report and source codeComp 220 i lab 1 two dimensional arrays lab report and source code
Comp 220 i lab 1 two dimensional arrays lab report and source code
 
Card Games in C++
Card Games in C++Card Games in C++
Card Games in C++
 
blackjackrevised2BlackJack.hBLACKJACK#ifndef _BLACKJA.docx
blackjackrevised2BlackJack.hBLACKJACK#ifndef _BLACKJA.docxblackjackrevised2BlackJack.hBLACKJACK#ifndef _BLACKJA.docx
blackjackrevised2BlackJack.hBLACKJACK#ifndef _BLACKJA.docx
 
Can someone help me setup this in JAVA Im new to java. Thanks.pdf
Can someone help me setup this in JAVA Im new to java. Thanks.pdfCan someone help me setup this in JAVA Im new to java. Thanks.pdf
Can someone help me setup this in JAVA Im new to java. Thanks.pdf
 
Blackjack Coded in MATLAB
Blackjack Coded in MATLABBlackjack Coded in MATLAB
Blackjack Coded in MATLAB
 
QuestionProblem 1 In a source file carddeck.cpp, provide an impl.pdf
QuestionProblem 1 In a source file carddeck.cpp, provide an impl.pdfQuestionProblem 1 In a source file carddeck.cpp, provide an impl.pdf
QuestionProblem 1 In a source file carddeck.cpp, provide an impl.pdf
 
PLEASE can do this in NETBEAN I need that way thank very muchManca.pdf
PLEASE can do this in NETBEAN I need that way thank very muchManca.pdfPLEASE can do this in NETBEAN I need that way thank very muchManca.pdf
PLEASE can do this in NETBEAN I need that way thank very muchManca.pdf
 
There are 5 C++ files below- Card-h- Card-cpp- Deck-h- Deck-cpp- Main-.docx
There are 5 C++ files below- Card-h- Card-cpp- Deck-h- Deck-cpp- Main-.docxThere are 5 C++ files below- Card-h- Card-cpp- Deck-h- Deck-cpp- Main-.docx
There are 5 C++ files below- Card-h- Card-cpp- Deck-h- Deck-cpp- Main-.docx
 
COMP 220 HELP Lessons in Excellence--comp220help.com
COMP 220 HELP Lessons in Excellence--comp220help.comCOMP 220 HELP Lessons in Excellence--comp220help.com
COMP 220 HELP Lessons in Excellence--comp220help.com
 
NO PAPER ANSWERS. ALL ANSWER SUBMISSIONS SHOULD BE ABLE TO RUN WIT.pdf
NO PAPER ANSWERS. ALL ANSWER SUBMISSIONS SHOULD BE ABLE TO RUN WIT.pdfNO PAPER ANSWERS. ALL ANSWER SUBMISSIONS SHOULD BE ABLE TO RUN WIT.pdf
NO PAPER ANSWERS. ALL ANSWER SUBMISSIONS SHOULD BE ABLE TO RUN WIT.pdf
 
I have another assignment due for an advance java programming class .pdf
I have another assignment due for an advance java programming class .pdfI have another assignment due for an advance java programming class .pdf
I have another assignment due for an advance java programming class .pdf
 
BlackJackBlackjack.c Blackjack.c Defines the entry point .docx
BlackJackBlackjack.c Blackjack.c  Defines the entry point .docxBlackJackBlackjack.c Blackjack.c  Defines the entry point .docx
BlackJackBlackjack.c Blackjack.c Defines the entry point .docx
 
public interface Game Note interface in place of class { .pdf
public interface Game  Note interface in place of class { .pdfpublic interface Game  Note interface in place of class { .pdf
public interface Game Note interface in place of class { .pdf
 

More from abifancystore

Aadaki ifadelerden hangisi yanltr ltfen sadece FALSE ifad.pdf
Aadaki ifadelerden hangisi yanltr ltfen sadece FALSE ifad.pdfAadaki ifadelerden hangisi yanltr ltfen sadece FALSE ifad.pdf
Aadaki ifadelerden hangisi yanltr ltfen sadece FALSE ifad.pdfabifancystore
 
Chemical and manufacturing plants sometimes discharge toxic .pdf
Chemical and manufacturing plants sometimes discharge toxic .pdfChemical and manufacturing plants sometimes discharge toxic .pdf
Chemical and manufacturing plants sometimes discharge toxic .pdfabifancystore
 
6 Matching Match each statement with an answer from the li.pdf
6 Matching Match each statement with an answer from the li.pdf6 Matching Match each statement with an answer from the li.pdf
6 Matching Match each statement with an answer from the li.pdfabifancystore
 
Cules de los siguientes son mtodos de investigacin de ac.pdf
Cules de los siguientes son mtodos de investigacin de ac.pdfCules de los siguientes son mtodos de investigacin de ac.pdf
Cules de los siguientes son mtodos de investigacin de ac.pdfabifancystore
 
Cmo se combinaron las nuevas tecnologas con la llegada de.pdf
Cmo se combinaron las nuevas tecnologas con la llegada de.pdfCmo se combinaron las nuevas tecnologas con la llegada de.pdf
Cmo se combinaron las nuevas tecnologas con la llegada de.pdfabifancystore
 
Aadakilerden hangisi bir konak hcrede Influenza virs ya.pdf
Aadakilerden hangisi bir konak hcrede Influenza virs ya.pdfAadakilerden hangisi bir konak hcrede Influenza virs ya.pdf
Aadakilerden hangisi bir konak hcrede Influenza virs ya.pdfabifancystore
 
Washington State recently adopted two new taxes that directl.pdf
Washington State recently adopted two new taxes that directl.pdfWashington State recently adopted two new taxes that directl.pdf
Washington State recently adopted two new taxes that directl.pdfabifancystore
 
Why might the annual interest rate on a 2year US government.pdf
Why might the annual interest rate on a 2year US government.pdfWhy might the annual interest rate on a 2year US government.pdf
Why might the annual interest rate on a 2year US government.pdfabifancystore
 
In the 1300s Europe was in the midst of decline and turmoil.pdf
In the 1300s Europe was in the midst of decline and turmoil.pdfIn the 1300s Europe was in the midst of decline and turmoil.pdf
In the 1300s Europe was in the midst of decline and turmoil.pdfabifancystore
 
write on this code A Sentinel List has two special n.pdf
write on this code    A Sentinel List has two special n.pdfwrite on this code    A Sentinel List has two special n.pdf
write on this code A Sentinel List has two special n.pdfabifancystore
 
Topic Why is unemployment so high in Europe Briefly discus.pdf
Topic Why is unemployment so high in Europe Briefly discus.pdfTopic Why is unemployment so high in Europe Briefly discus.pdf
Topic Why is unemployment so high in Europe Briefly discus.pdfabifancystore
 
Can someone give simple answers to these two questions Than.pdf
Can someone give simple answers to these two questions Than.pdfCan someone give simple answers to these two questions Than.pdf
Can someone give simple answers to these two questions Than.pdfabifancystore
 
The trial balance for Best Advisors Service on December 31 .pdf
The trial balance for Best Advisors Service on December 31 .pdfThe trial balance for Best Advisors Service on December 31 .pdf
The trial balance for Best Advisors Service on December 31 .pdfabifancystore
 
Calculate the dominant allele D frequency for this populat.pdf
Calculate the dominant allele D frequency for this populat.pdfCalculate the dominant allele D frequency for this populat.pdf
Calculate the dominant allele D frequency for this populat.pdfabifancystore
 
the probabiilty of obtaining a success Round your answer to.pdf
the probabiilty of obtaining a success Round your answer to.pdfthe probabiilty of obtaining a success Round your answer to.pdf
the probabiilty of obtaining a success Round your answer to.pdfabifancystore
 
Suppose that you are given a decision situation with three p.pdf
Suppose that you are given a decision situation with three p.pdfSuppose that you are given a decision situation with three p.pdf
Suppose that you are given a decision situation with three p.pdfabifancystore
 
Sicklecell anemia is a recessive trait in humans In order .pdf
Sicklecell anemia is a recessive trait in humans In order .pdfSicklecell anemia is a recessive trait in humans In order .pdf
Sicklecell anemia is a recessive trait in humans In order .pdfabifancystore
 
Revenue Recognition for Facebook and twitter for the year 20.pdf
Revenue Recognition for Facebook and twitter for the year 20.pdfRevenue Recognition for Facebook and twitter for the year 20.pdf
Revenue Recognition for Facebook and twitter for the year 20.pdfabifancystore
 
begintabularlcc hline multicolumn1c Contribut.pdf
begintabularlcc hline multicolumn1c Contribut.pdfbegintabularlcc hline multicolumn1c Contribut.pdf
begintabularlcc hline multicolumn1c Contribut.pdfabifancystore
 
Question 26 1 pts Which of the following is NOT true of all .pdf
Question 26 1 pts Which of the following is NOT true of all .pdfQuestion 26 1 pts Which of the following is NOT true of all .pdf
Question 26 1 pts Which of the following is NOT true of all .pdfabifancystore
 

More from abifancystore (20)

Aadaki ifadelerden hangisi yanltr ltfen sadece FALSE ifad.pdf
Aadaki ifadelerden hangisi yanltr ltfen sadece FALSE ifad.pdfAadaki ifadelerden hangisi yanltr ltfen sadece FALSE ifad.pdf
Aadaki ifadelerden hangisi yanltr ltfen sadece FALSE ifad.pdf
 
Chemical and manufacturing plants sometimes discharge toxic .pdf
Chemical and manufacturing plants sometimes discharge toxic .pdfChemical and manufacturing plants sometimes discharge toxic .pdf
Chemical and manufacturing plants sometimes discharge toxic .pdf
 
6 Matching Match each statement with an answer from the li.pdf
6 Matching Match each statement with an answer from the li.pdf6 Matching Match each statement with an answer from the li.pdf
6 Matching Match each statement with an answer from the li.pdf
 
Cules de los siguientes son mtodos de investigacin de ac.pdf
Cules de los siguientes son mtodos de investigacin de ac.pdfCules de los siguientes son mtodos de investigacin de ac.pdf
Cules de los siguientes son mtodos de investigacin de ac.pdf
 
Cmo se combinaron las nuevas tecnologas con la llegada de.pdf
Cmo se combinaron las nuevas tecnologas con la llegada de.pdfCmo se combinaron las nuevas tecnologas con la llegada de.pdf
Cmo se combinaron las nuevas tecnologas con la llegada de.pdf
 
Aadakilerden hangisi bir konak hcrede Influenza virs ya.pdf
Aadakilerden hangisi bir konak hcrede Influenza virs ya.pdfAadakilerden hangisi bir konak hcrede Influenza virs ya.pdf
Aadakilerden hangisi bir konak hcrede Influenza virs ya.pdf
 
Washington State recently adopted two new taxes that directl.pdf
Washington State recently adopted two new taxes that directl.pdfWashington State recently adopted two new taxes that directl.pdf
Washington State recently adopted two new taxes that directl.pdf
 
Why might the annual interest rate on a 2year US government.pdf
Why might the annual interest rate on a 2year US government.pdfWhy might the annual interest rate on a 2year US government.pdf
Why might the annual interest rate on a 2year US government.pdf
 
In the 1300s Europe was in the midst of decline and turmoil.pdf
In the 1300s Europe was in the midst of decline and turmoil.pdfIn the 1300s Europe was in the midst of decline and turmoil.pdf
In the 1300s Europe was in the midst of decline and turmoil.pdf
 
write on this code A Sentinel List has two special n.pdf
write on this code    A Sentinel List has two special n.pdfwrite on this code    A Sentinel List has two special n.pdf
write on this code A Sentinel List has two special n.pdf
 
Topic Why is unemployment so high in Europe Briefly discus.pdf
Topic Why is unemployment so high in Europe Briefly discus.pdfTopic Why is unemployment so high in Europe Briefly discus.pdf
Topic Why is unemployment so high in Europe Briefly discus.pdf
 
Can someone give simple answers to these two questions Than.pdf
Can someone give simple answers to these two questions Than.pdfCan someone give simple answers to these two questions Than.pdf
Can someone give simple answers to these two questions Than.pdf
 
The trial balance for Best Advisors Service on December 31 .pdf
The trial balance for Best Advisors Service on December 31 .pdfThe trial balance for Best Advisors Service on December 31 .pdf
The trial balance for Best Advisors Service on December 31 .pdf
 
Calculate the dominant allele D frequency for this populat.pdf
Calculate the dominant allele D frequency for this populat.pdfCalculate the dominant allele D frequency for this populat.pdf
Calculate the dominant allele D frequency for this populat.pdf
 
the probabiilty of obtaining a success Round your answer to.pdf
the probabiilty of obtaining a success Round your answer to.pdfthe probabiilty of obtaining a success Round your answer to.pdf
the probabiilty of obtaining a success Round your answer to.pdf
 
Suppose that you are given a decision situation with three p.pdf
Suppose that you are given a decision situation with three p.pdfSuppose that you are given a decision situation with three p.pdf
Suppose that you are given a decision situation with three p.pdf
 
Sicklecell anemia is a recessive trait in humans In order .pdf
Sicklecell anemia is a recessive trait in humans In order .pdfSicklecell anemia is a recessive trait in humans In order .pdf
Sicklecell anemia is a recessive trait in humans In order .pdf
 
Revenue Recognition for Facebook and twitter for the year 20.pdf
Revenue Recognition for Facebook and twitter for the year 20.pdfRevenue Recognition for Facebook and twitter for the year 20.pdf
Revenue Recognition for Facebook and twitter for the year 20.pdf
 
begintabularlcc hline multicolumn1c Contribut.pdf
begintabularlcc hline multicolumn1c Contribut.pdfbegintabularlcc hline multicolumn1c Contribut.pdf
begintabularlcc hline multicolumn1c Contribut.pdf
 
Question 26 1 pts Which of the following is NOT true of all .pdf
Question 26 1 pts Which of the following is NOT true of all .pdfQuestion 26 1 pts Which of the following is NOT true of all .pdf
Question 26 1 pts Which of the following is NOT true of all .pdf
 

Recently uploaded

CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 

Recently uploaded (20)

CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 

FaceUp card game In this assignment we will implement a made.pdf

  • 1. FaceUp card game In this assignment we will implement a made-up card game we'll call FaceUp. When the game starts, you deal five cards face down. Your goal is to achieve as high a score as possible. Your score only includes cards that are face up. Red cards (hearts and diamonds) award positive points, while black cards (clubs and spades) award negative points. Cards 2-10 have points worth their face value. Cards Jack, Queen, and King have value 10, and Ace is 11. The game is played by flipping over cards, either from face-down to face-up or from face-up to face-down. As you play, you are told your total score (ie, total of the face-up cards) and the total score of the cards that are face down. The challenge is that you only get up to a fixed number of flips and then the game is over. Here is an example of the output from playing the game: At each point where the program asks the user to pick a card, the game waits for user input. Code Well implement the game using five classes, three of which you'll leave unchanged, and two you will modify and submit: Card: Leave this code unchanged. CardDealer: Leave this code unchanged. FaceUpCard: This class extends the Card class with additional functionality. You will add two methods needed for the FaceUp game. FaceUpHand: This class keeps track of the state of the game. Most of the methods you will implement are here. FaceUpGame: This class implements the game interface. It gets data from the user, updates the board, and repeats the process. Leave this code unchanged. How to proceed You may fill in the details of the FaceUpCard and FaceUpHandclasses however youd like, but heres what we recommend. Add the two methods to the FaceUpCard class (described in comments in the code). Add a main method to this class and test them to make sure they work. Read through the other two new classes FaceUpHand and FaceUpGame. Make sure you understand what all of the methods in FaceUpHand are supposed to do and that you understand how theyre used in the FaceUpGame class. Implement methods in the FaceUpHand class incrementally. Write one method and then test it! To test it, again, add a main method and write a small test or two to make sure it behaves like youd expect. If you try to implement all of the methods and then test it by simply running FaceUpGame, 1) its very unlikely youll get it perfect the first time and then 2) its going to be very hard to figure out where the problem is. Card.java public class Card { // min/max for the card number range private static final int MIN_NUMBER = 1; private static final int MAX_NUMBER = 13; private int number;
  • 2. private String suit; /** * Create a new card with number and suit. If the a valid * suit/number is not input, the card defaults to 1 of hearts. * * @param number the card number * @param suit the card suit */ public Card(int number, String suit){ this.number = number; this.suit = suit.toLowerCase(); if (!isValidSuit(suit)) { System.out.println(suit + "Is not a valid suit!"); System.out.println("Must be one of: clubs, diamonds, hearts or spades"); System.out.println("Defaulting to hearts"); this.suit = "hearts"; } if (!isValidNumber(number)) { System.out.println(number + "Is not a valid number!"); System.out.println("Must be between " + MIN_NUMBER + " and " + MAX_NUMBER); System.out.println("Defaulting to 1"); this.number = 1; } } /** * @return the card's suit */ public String getSuit(){ return suit; } /** * @return the card's number MIN_NUMBER .. MAX_NUMBER */ public int getNumber() { return number; } /** * Returns the card's rank as a string * changing Jack, Queen, King, Ace appropriately * * @return the card's rank */
  • 3. public String getRank() { if (number == 1) { return "Ace"; } else if (number >= 2 && number <= 10) { return Integer.toString(number); } else if (number == 11) { return "Jack"; } else if (number == 12) { return "Queen"; } else { return "King"; } } /** * The card's rank followed by the suit */ public String toString() { return getRank() + " of " + getSuit(); } /** * Make it an Ace! */ public void cheat() { number = 1; // ACE! } /** * Check to make sure the card number is valid * * @param num potential card number * @return whether the card number is valid */ private boolean isValidNumber(int num) { return num >= MIN_NUMBER && num <= MAX_NUMBER; } /** * Check to make sure the suit is valid * * @param s potential suit * @return whether the suit is valid */ private boolean isValidSuit(String s) { return s.equals("spades") ||
  • 4. s.equals("hearts") || s.equals("clubs") || s.equals("diamonds"); } } CardDealer.java public class CardDealer { private static final int CARDS_PER_SUIT = 13; // the number of cards in the deck private static final String[] suits = {"clubs", "diamonds", "hearts", "spades"}; private FaceUpCard[] cards; // all of the cards to be dealt private int position; // our current position in our stack of cards /** * Creates a new card dealer with numDecks decks in the deck * * @param numDecks the number of card decks to use */ public CardDealer(int numDecks) { int numCards = numDecks * CARDS_PER_SUIT * suits.length; cards = new FaceUpCard[numCards]; int cardIndex = 0; for (int i = 0; i < numDecks; i++) { for (int suitIndex = 0; suitIndex < suits.length; suitIndex++) { for (int numIndex = 1; numIndex <= CARDS_PER_SUIT; numIndex++) { cards[cardIndex] = new FaceUpCard(numIndex, suits[suitIndex]); cardIndex++; } } } shuffle(); } /** * Returns true if there are cards left in the deck, false otherwise */ public boolean hasNext() { return position < cards.length; } /** * Returns the next card from the deck * * @pre assumes there are cards left in the deck (i.e. hasNext() is true) */ public FaceUpCard next() {
  • 5. position++; return cards[position-1]; } /** * Randomly shuffles the deck and resets the card to be dealt as the first card */ public void shuffle() { Random rand = new Random(); for (int i = 0; i < cards.length; i++) { int nextPosition = rand.nextInt(cards.length); // swap this card with the card at next position FaceUpCard temp = cards[i]; cards[i] = cards[nextPosition]; cards[nextPosition] = temp; } position = 0; } /** * Tests the CardDealer class */ public static void main(String[] args) { CardDealer dealer = new CardDealer(2); for (int i = 0; i < 100; i++) { System.out.println(dealer.next()); } } } FaceUpCard.java public class FaceUpCard extends Card { private boolean faceUp; /** * Create a new FaceUpCard with number and suit * @param number the card number * @param suit the card suit */ public FaceUpCard(int number, String suit) { super(number, suit); faceUp = false; } /** * Returns whether card is face up */
  • 6. public boolean isFaceUp() { return faceUp; } /** * Flips a card from face-down to face-up or face-up to face-down */ public void flip() { faceUp = !faceUp; } /** * Returns the card's value in the FaceUp game * Number cards have their number as the value * Ace is 11, and Jack, Queen, and King are 10 */ public int getCardValue() { // TODO: fill in method definition; replace placeholder on next line return 0; } /** * Returns whether card is a red card, ie with suit "hearts" or "diamonds" */ public boolean isRedCard() { // TODO: fill in method definition; replace placeholder on next line return false; } } FaceUpGame.java public class FaceUpGame { private static final int NUM_CARDS = 5; public static void playGame(int numRounds) { FaceUpHand cards = new FaceUpHand(NUM_CARDS); Scanner in = new Scanner(System.in); int flipsLeft = numRounds; while (flipsLeft > 0) { System.out.println(cards); System.out.println("Face up total: " + cards.faceUpTotal()); System.out.println("Face down total: " + cards.faceDownTotal()); System.out.println("Number of flips left: " + flipsLeft); System.out.print("Pick a card to flip between 1 and " + NUM_CARDS + " (-1 to end game): "); int num = in.nextInt(); System.out.println(); if (num == -1) {
  • 7. flipsLeft = 0; } else if (num < 1 || num > NUM_CARDS) { System.out.println(num + " is not a valid card"); } else { cards.flipCard(num-1); flipsLeft--; } } in.close(); System.out.println(); System.out.println("----------------------"); System.out.println("Your score: " + cards.faceUpTotal()); System.out.println("Best possible score: " + cards.calculateOptimal()); } public static void main(String[] args) { playGame(5); FaceUpHand.java /*** Keeps track of the cards and and answers questions * for the FaceUp card game. * Red cards (hearts and diamonds) award positive points, while black cards * (clubs and spades) award negative points. Cards 2-10 have points worth * their face value; Jack, Queen and King are 10; and Ace is 11.*/ public class FaceUpHand { private FaceUpCard[] cards; /*** Create a new FaceUp card game state, which consists of the * array cards of size numCards * * @param numCards number of cards in the game*/ public FaceUpHand(int numCards) { // TODO: fill in method definition to initialize the cards array // 1. set the instance variable cards equal to a new array (size numCards) of type FaceUpCard // 2. create a variable dealer of type CardDealer for 1 deck // 3. loop through the cards array and set each value to dealer.next() } /*** Return the FaceUpCard in position cardIndex of cards * @return the element of cards specified by cardIndex*/ public FaceUpCard getCard(int cardIndex) { // TODO: fill in method definition; replace placeholder on next line return null; } /*** Flip the card over at this index * Card indices start at 0 and go up the cards.length-1*
  • 8. * @param cardIndex the index of the card to flip over*/ public void flipCard(int cardIndex) { // TODO: fill in method definition } /*** Calculate the best possible score for the current cards* * @return the optimal score*/ public int calculateOptimal() { // TODO: fill in method definition; replace placeholder on next line return 0; } /*** Calculate the total score for the cards that are face up * @return the total score for face-up cards*/ public int faceUpTotal() { // Hint: use getCardValue() and remember red cards have positive value // and black cards have negative value // TODO: fill in method definition; replace placeholder on next line return 0; } /*** Calculate the total score for the cards that are face down* * @return the total score for face-down cards */ public int faceDownTotal() { // Hint: use getCardValue() and remember red cards have positive value // and black cards have negative value // TODO: fill in method definition; replace placeholder on next line return 0; } // TODO: add a toString method here! }