# Java Program to Create Card Game Assignment Solution

June 18, 2024
Ellie Icely
🇬🇧 United Kingdom
Java
PhD in Computer Science from the University of Hertfordshire, with 8 years of experience in Java assignments. Expert in delivering high-quality, efficient solutions for complex programming problems. Passionate about teaching and mentoring students.
Key Topics
• Instructions
• Objective
• Requirements and Specifications
Tip of the day
News

## Instructions

### Objective

Write a program to create card game in java.

## Requirements and Specifications

Introduction

Higher/Lower is a single-player card game that uses a standard shuffled deck of playing cards from which a number of cards have been dealt face-down. The object of the game is to turn over the first card revealing its value and then to predict whether the next card to be turned over is higher or lower in value than the previous. For example, if the game consists of 5 cards, the initial state of play might be as shown below, where the 4♥ is visible and the remaining 4 cards are face-down from left-to-right.

4♥ ! ! ! ! Your score = 0

The player is now invited to say whether they think that the next card will be higher or lower than a 4. In this instance they might guess “higher” and the next card is revealed as the 9♣. As the user’s guess was correct, the game continues.

4♥ 9♣ ! ! ! Correct guess, your score = 1

This time the user guesses that the next card will be lower than a 9, but when the card is turned over, it is revealed to be the 10♠. As they have guessed incorrectly, the game is over, and their final score is confirmed.

4♥ 9♣ 10♠ ! ! Incorrect guess, your final score = 1

If the player successfully turns over all cards with correct guesses, the game automatically ends. Where consecutive cards are the same value, for example Q♥ followed by Q♣, then the player is guaranteed to lose as the second Queen is neither higher nor lower than the first one.

In this game, the Ace is the highest value available so that the values in order from lowest to

highest are 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K, A.

Note that your application will be a pure text version – with keyboard input. There is no

requirement for a graphical or mouse-based solution.

Required Functionality

There are 7 levels

• Level 1: The facilities to create a new game are present and the game can be set up in its initial state, with 5 cards dealt from a shuffled deck, one of which is shown face-up (i.e. its value is on display) with the remaining cards face-down. You can use any appropriate text representation for the cards.
• Level 2: The basic game mechanism is in place. Users can select “higher” or “lower” when each card is displayed, and the next card is revealed or the game ends depending on their choice.
• Level 3: A full playable game is available. The application is able to prompt the player when the game is won (all cards successfully guessed) or lost (a wrong guess has been made).
• Level 4: Before the game begins, the user is prompted for the number of cards to be used. For example, if the user chooses 10 cards, then one is displayed face up and 9 correct guesses need to be made for a winning game.
• Level 5: The user can “stick” by declining to guess either “higher” or “lower”. In this case the game is won, and the user is awarded a score according to the number of correct guesses made so far. A high-score table is displayed after each game showing the top 5 winning performances so far.
• Level 6: On completion of a game (whether the player has won or lost) the application is able to replay the game guess by guess, with the user prompting each replayed move by a keypress.
• Level 7: The application is able to play a complete game in “demonstration mode”, where all 52 shuffled cards are dealt. In demonstration mode, the user’s only input is to press a key to begin the next move and the demonstration continues until an incorrect guess is made or all 52 cards have been successfully revealed. A separate “Demonstration” high score table should show the computer’s top 5 demonstration performances.

Deliverables

The deliverables for this assessment are as follows:

1. “HigherLower” Application – A Zip file containing all code developed for the application. The easiest way to create this is to Zip the contents of the src folder of your Java project. Each Java file should also be provided as a PDF document. Please include comments throughout code.
2. Design and Development Document – A PDF document that contains a written account of the design and development decisions made during the development of your application. You should provide evidence of your consideration of data structures used and algorithms developed, with justification for your decisions and rejection of alternatives.
3. Testing Document – A PDF document that describes your testing regime with details of any test classes developed. This document should also describe steps you have taken to ensure the security of your implementation. Please do not use advanced method of coding, just amateur level, Thank you.

Source Code

```CARD public class Card { /** * The following array contains the avaliable suits */ static char[] SUITS = {'c', 'd', 'h', 's'}; /** * Variable to store the rank number */ public int rank; /** * Variable to store suit character */ public char suit; /** * Variable to know if the card has been shown to user */ public boolean shown; /** * Overloaded constructor * @param rank integer * @param suit char */ public Card(int rank, char suit) { this.rank = rank; this.suit = suit; this.shown = false; } /** * Getter for rank * @return integer */ public int getRank() { return this.rank; } /** * Getter for suit * @return char */ public char getSuit() { return this.suit; } /** * Method so now when the toString method is called it will show the rank and suit */ public void show() { this.shown = true; } /** * Method to know if the card has been shown * @return boolean */ public boolean isShown() { return this.shown; } /** * ToString method. */ @Override public String toString() { return String.format("%d%s", getRank(), getSuit()); } } DECK import java.util.ArrayList; import java.util.Random; public class Deck { /** * ArrayList to store the cards in the deck */ private ArrayList cards; /** * Default constructor */ public Deck() { cards = new ArrayList(); } /** * Getter for cards * @return Array List of Card */ public ArrayList getCards() { return this.cards; } /** * Method to add a new card to the deck * @param card Card object */ public void addCard(Card card) { this.cards.add(card); } /** * Method to shuffle the cards */ public void shuffle() { // This function shuffles the deck randomly Random rnd = new Random(); for(int i = 0; i < cards.size(); i++) { int idx1 = rnd.nextInt(cards.size()); int idx2 = rnd.nextInt(cards.size()); // swap Card temp = cards.get(idx1); cards.set(idx1, cards.get(idx2)); cards.set(idx2, temp); } } /** * Method to take one card from the deck * @return Card object */ public Card draw() { // Pick a random index Random rnd = new Random(); // Select card and remove it from deck return cards.remove(rnd.nextInt(cards.size())); } } GAME import java.util.ArrayList; import java.util.Scanner; public class Game { /** * Variable to store the deck of the game */ private Deck deck; /** * Variable to store player's score */ private int score; /** * Variable to store the cards dealt from the deck */ private ArrayList cardsDealt; /** * Variable to know if the game ended because user won */ private boolean won; /** * Variable to know the number of cards to be dealt from deck */ private int n_cards; /** * Variable to count the number of correct guesses */ private int correct_guesses; /** * Scanner object used to get user's input */ private Scanner sc; /** * Constructor * @param sc Scanner object */ public Game(Scanner sc) { // Creates deck deck = new Deck(); // fill deck for(char suit: Card.SUITS) { for(int rank = 2; rank <= 14; rank++) { deck.addCard(new Card(rank, suit)); } } // Shuffle deck.shuffle(); // Initialize all other attributes score = 0; cardsDealt = new ArrayList(); won = false; this.sc = sc; n_cards = 0; correct_guesses = 0; } /** * Getter for deck * @return */ public Deck getDeck() { return deck; } /** * Getter for score */ public int getScore() { return score; } /** * Getter for number of correct guesses * @return Integer */ public int getCorrectGuesses() { return correct_guesses; } /** * Getter to get the cards dealt * @return Array List of Card */ public ArrayList getCardsDealt() { return cardsDealt; } /** * Method to know if the player won or not * @return boolean */ public boolean hasWon() { return won; } /** * Method used to display the cards in the console */ public void displayCards() { /*for(int i = 0; i < cardsDealt.size(); i++) { System.out.print("[" + cardsDealt.get(i).toString() + "] | "); } System.out.println("");*/ for(int i = 0; i < n_cards; i++) { if(cardsDealt.get(i).isShown()) { System.out.print("[" + cardsDealt.get(i).toString() + "]"); } else { System.out.print("[**]"); } } } /** * Method used to get 'low' or 'high' words from user * @return Integer */ public int getLowHigh() { String input; while(true){ // Ask for option System.out.print("What is your guess? (low/high or decline): "); input = sc.nextLine(); if(input.toLowerCase().equals("low")) { return 0; } else if (input.toLowerCase().equals("high")) { return 1; } else if (input.toLowerCase().equals("decline")) { return 2; } else { System.out.println("Please enter low, high or decline."); } } } /** * Method used to get from user the number of cards to be dealt * @return Integer */ public int askNumberOfCards() { int n; while(true) { try { System.out.print("Enter number of cards to be used in the game: "); n = Integer.valueOf(sc.nextLine()); if (n > 1 && n <= 52) { return n; } else { System.out.println("Please enter a number between 2 and 52"); } } catch(Exception ex) { System.out.println("Please enter a number between 2 and 52"); } } } /** * Main method where all the game functionality is done */ public void play() { // The following line is for Level 4. Ask user for how many cards to use in the game n_cards = askNumberOfCards(); // Deal cards for(int i = 0 ; i < n_cards; i++) { cardsDealt.add(deck.draw()); } // Show the first one cardsDealt.get(0).show(); int currentIndex = 1; // the index of the card to be guessed // Now, display cards boolean running = true; int guess; while(running) { // Display cards and score displayCards(); System.out.println("!!!! Your score = " + score); // Ask for low or high guess = getLowHigh(); // Reveal card cardsDealt.get(currentIndex).show(); // Get previous and current cards Card previous = cardsDealt.get(currentIndex-1); Card current = cardsDealt.get(currentIndex); if(guess == 0) // guess for low { if(current.getRank() < previous.getRank()) { // Player guessed correctly System.out.println("Correct!"); correct_guesses += 1; score += 1; currentIndex += 1; if(currentIndex == n_cards) // no more cards to guess, game ends { System.out.println("Congratulations! You guessed all the cards"); running = false; won = true; } } else { // Display the card System.out.println("Incorrect, the card was " + current.toString()); System.out.println("Game over!"); running = false; } } else if (guess == 1) { // guess for high if(current.getRank() > previous.getRank()) { // Player guessed correctly System.out.println("Correct!"); correct_guesses += 1; score += 1; currentIndex += 1; if(currentIndex == n_cards) // no more cards to guess, game ends { System.out.println("Congratulations! You guessed all the cards"); running = false; won = true; } } else { System.out.println("Incorrect, the card was " + current.toString()); System.out.println("Game over!"); running = false; } } else if (guess == 2) // decline { // The game is won System.out.println("You won by declining! You guessed a total of " + correct_guesses + " cards!"); running = false; won = true; } } } } ```

## Similar Samples

Discover our collection of programming homework samples at ProgrammingHomeworkHelp.com. These examples illustrate our proficiency across various languages and topics, from introductory exercises to complex projects. Explore how our solutions can assist you in mastering programming concepts and achieving academic success. Trust our expertise to guide you through your programming challenges effectively.