Question

hello there, i have to implement this on java processing. can someone please help me regarding...

hello there,

i have to implement this on java processing.

can someone please help me regarding that?

thanks

War is the name of

a

popular children’s card game. There are

many variants. After playing War with a friend for over an

hour, they argue that this game must never end

. However!

You are convinced that it will end. As a budding computer

scientist, you decide to build a simulator to find out for sure!

You will implement the logic for the war card game.

You

have been provided with a skeleton file

that does the

drawing for

you. The drawing is not hard, but it is tedious, so

you can save time this way (but you can spice it up if you

want!).

The game works as follows. You take a full deck of cards

(52 cards) with no jokers. Shuffle the deck. Deal the whole

deck out to two pl

ayers, so that each player has 26 cards. Now you are ready to play.

To play, both players turn up their top card and show it. The highest card wins (aces are low). If

the cards are the same number, then the suit decides. The order (strongest to weakest) i

s: Hearts,

Diamonds, Spades, Clubs. There is never a tie. The winner takes both cards and puts them on the

bottom of their deck, and another round is played.

This is played until one player runs out of cards, which means they are the loser.

This is a cha

llenging assignment. The hardest part is the techniques you use on the arrays.

Strategy

: I have provided the required functions and descriptions, and an overview of some of

the globals you will need. Initially, type in all your function stubs (empty code,

returning

A

SSIGNMENT 4

DEPARTMENT AND COURSE NUMBER: COMP

10

10

2

garbage), and get the thing to run. Then work on one piece at a time.

The grading

is different for

this assignment than the others. To maximize your marks, implement the easy functions first (the

lower marks) and get them working, to maximize pa

rt marks.

Provided code

: The draw loop has been provided (it’s quite simple), which continually plays

game hands as fast as possible until a winner is found. I also use a new way to access the mouse,

a function called mousePressed (details in the file). I

f you click the right mouse button, the

simulation pauses. If you click the left mouse button, it executes just one round (very good for

debugging!!). If you click the right mouse button again, the fast simulation is continued.

Playing Cards:

Playing card

s have a number from 1

-

13 (A, 2..10, J, Q, K), and a suit (Hearts,

Diamonds, Spades, or Clubs). You can store cards nicely inside computers with a few tricks:

Each card has a unique number, from 0..51 (52 cards)

You can get the card suit by taking card/13

with integer division. Cards 0..12 will be suit

0, 13..25 will be suit 1, 26..38 will be suit 2, and the rest suit 3. (4 suits). Suit is card/13.

You can get the actual card number by taking card%13. The first 13 will be 0..12, 13..25

will also be 0..12, a

nd so forth. Number is card%13.

Array of Cards

: The use of arrays is the challenging part of this assignment. You will use arrays

to store collections of cards. For example, at the beginning you generate the card deck into one

array. Each player’s own deck

(their hand) will have its own array. These arrays store integers,

and each bin can store an integer to represent the unique card (e.g., 27). Remember you can

convert this card to a suit and number as per above. When you deal the cards to the players, you

will add each player’s cards into their respective arrays.

Partially

-

filled arrays:

your arrays will often be partially filled. For example, if you create an

array to store the players deck with 52 bins (they may collect all the cards!!) but they only ha

ve

10 cards, what goes in the other bins? You need to set these bins to impossible values. Give this

a name as a final constant, e.g., NO_CARD, and set it to an impossible value (e.g., outside the

range 0..51, maybe

-

1?).

Maintaining the arrays:

As the ga

me plays, players constantly lose and gain cards. They take

cards off the top of their decks. They place cards on the bottom. It is important to keep the card

order. This is the core tough part of the assignment. In programming, when you come across a

toug

h part like this, a good strategy is to wrap the logic into safe functions. If you implement

those functions, then everything else becomes easy. In this case, you will build

addCardToBottom, getTopCard, removeTopCard. If you can solve those three problems,

then

you’re done.

The idea behind this is that, for each player, you will have: an array to store their deck of cards,

an integer pointing at the current top card, and an integer pointing at the first empty slot at the

bottom of the deck. Look at the fol

lowing diagram. * means empty (impossible value). This

array has 5 cards stored and a range of empty bins.

*

*

*

*

43

8

21

51

1

*

*

*

*

top

bottom

A

SSIGNMENT 4

DEPARTMENT AND COURSE NUMBER: COMP

10

10

3

The arrows represent integers you keep track of that tell you which bin is the top or bottom. You

will be puttin

g cards in left to right, and you add cards to the bottom, so the top of the deck is on

the left. When you add a new card, you put it in the bottom bin, and move along that pointer to

the next empty bin. When you take a card off the top, you get the number

(43 in this case),

replace it with impossible value (*), and move the pointer along. When the arrows hit the end of

the array you just wrap around using mod. This is detailed in the functions below.

Globals:

In addition to the drawing

-

related globals alr

eady provided, you will need (at least) the

following: a final integer representing NO_CARD, final String arrays representing the card

numbers (“A”,”1”,...”K” and “C”,”S”,”D”,”H” for suits). You will need the following non

-

final

variables

player 1 hand, pl

ayer 2 hand (make them capable of holding the whole deck), integers

for the tops and bottoms of the decks, and an integer counting how many rounds have passed.

Functions:

You must implement the following functions

(1 marks)

generateDeck

takes no parame

ters but returns a new array, size 5

2

, representing a

clean freshly

-

opened deck of cards. The array will have the numbers 0..51 stored in bins 0..51

(use a for loop). Try printing out the array for debugging purposes

.

(1.5 marks)

shuffleDeck

takes a car

d deck as the parameter and shuffles it. A good way to do

this is to go through each card in the deck (use a for loop), and swap it with a random card in the

deck. For debugging, try printing out the array and checking that you don’t have duplicates.

(1 m

arks)

resetHand

takes a hand (integer array), returns nothing. Sets every bin in the array to

have no card in it (use your final constant).

(2 marks)

resetDecks

takes no parameters and returns nothing, works on globals. Calls

generateDeck

to make a fr

esh deck, and

shuffleDeck

to shuffle it. It calls

resetHand

twice to

reset the two player hands. Sets the top and bottom pointers to 0 (the start of the hand in the

array). Finally, shuffles the cards from the deck into the hands. There are many ways to do

this

-

since the deck is already shuffled, as long as you get 26 into each hand you are fine. Make sure

to call

addCardToBottom

to add the cards, and to store it’s return value as the new bottom

pointers.

(1 marks)

countCards

takes a hand (integer array

), and returns an integer representing how

many cards are in the array. Use a for loop to go over each one and count how many are not set

to no card.

(3 marks)

addCardToBottom

takes a hand (integer array), a bottom pointer (int), and a card

(int). Retur

ns the new bottom location. Since the current bottom pointer should point to an empty

bin, put the card there. Move the bottom counter right by one, and then mod the array length so

that it wraps around if needed. Return the new bottom pointer. For debuggi

ng, before doing this,

ensure that the bottom pointer points to a bin with no card in it. If there is a card there, print out

an error message to help you debug

this means either your array is full, or, your bottom pointer

is wrong.

A

SSIGNMENT 4

DEPARTMENT AND COURSE NUMBER: COMP

10

10

4

(3 marks)

getTopCard

takes a hand (integer array) and a top pointer (int), returns the card. It

looks in the array at the top bin and gets the card out, and returns this card. For debugging, check

to make sure there is a card there. This should only happen if the array is e

mpty, or you have a

bug.

(3 marks)

removeTopCard

takes a hand (integer array), and a top pointer (int). After the top

card is removed, it returns the new top pointer. You should check that there is actually a card to

remove, and print out an error messa

ge if not (helps with debugging). Set the current top card bin

in the array to have no card. Move the top pointer right by one: add one. Mod the array length to

make it wrap around if you go off the edge. Return the new top pointer.

(.5 marks)

getSuit

t

akes a card, and returns a number 0..3 representing the suit. Basically card/13.

(.5 marks)

getNumber

takes a card, and returns a number 0..12 representing the card number.

Basically card%13.

(2 marks)

getText

takes a card and returns a string with t

wo characters: the first character is the

card number (“A”,”1”,...,”K”) and the second it the suit letter.

DO NOT USE AN IF

STATEMENT IN THIS METHOD

. The way to do it is to get the card number and suit, and

use these as indexes into your global string arrays

for the card numbers and suits.

(2 marks)

isBetter

takes two cards (as integers) and returns a boolean telling you if the first card

is better than the second. Use

getNumber

and

getSuit

on the cards first to get their suits and

numbers. If the first ca

rd is larger, then it’s better, if the second is larger, then it’s better. In the

case of a tie, compare the suits as explained earlier (hearts beats diamonds beats spades beats

clubs).

(2.5 marks)

doRound

takes no parameters and returns nothing. Works

on globals and own local

variables. This is the core logic of the game. First, get the top cards from the players decks and

remove them from those decks. (use

getTopCard

and

removeTopCard

for this). Call

isBetter

to find out who won. You will place the two

cards on the bottom of the winner’s deck using

addCardToBottom

, however,

IMPORTANT

: put the two cards back on the deck in random

order. Flip a coin using random, and use this to determine the order. At the end of this function

increase the number of round

s.

(2 marks)

globals, flow and play

if your program doesn’t run, this is 0. You will lose marks here

for small logic issues like off by 1, etc., that make the overall game work incorrect

0 0
Add a comment Improve this question Transcribed image text
Answer #1

public class WarGame {
    public static final int NUMBER_CARDS_DECK = 52;
    private static final int NUMBER_CARDS_TIEBREAKER = 3;

    public static void main(String[] args) {
        Card[] entireDeck = createDeck();
        Card[] shuffledDeck = shuffleDeck(entireDeck);
        // An array of size NUMBER_CARDS_DECK is created for each player.
        Card[] playerOne = new Card[NUMBER_CARDS_DECK];
        Card[] playerTwo = new Card[NUMBER_CARDS_DECK];


        for (int i = 0; i < NUMBER_CARDS_DECK; i++) {
            if (i % 2 == 0) {
                playerOne[i / 2] = shuffledDeck[i];
            } else {
                playerTwo[i / 2] = shuffledDeck[i];
            }
        }

        while (hasCards(playerOne) && hasCards(playerTwo)) {

            System.out.println("Player one has " + countCards(playerOne)
                    + " cards and player two has " + countCards(playerTwo)
                    + " cards.");

            // one round of the game.
            playRound(playerOne, playerTwo);

            // spacing to separate the rounds in the game.
            System.out.println("\n");
        }

        if (hasCards(playerOne)) {
            System.out.println("Player one won!");
        } else {
            System.out.println("Player two won!");
        }
    }

    // The createDeck method takes nothing as input and returns a Card[].

    private static Card[] createDeck() {
        Card[] entireDeck = new Card[NUMBER_CARDS_DECK];
        int z = 0;
        for (int i = 0; i < 13; i++) {
            for (int j = 0; j < 4; j++) {
                entireDeck[z] = new Card();
                entireDeck[z].setSuit(j);
                entireDeck[z].setNumber(i + 1);
                z++;
            }
        }

        return entireDeck;
    }

    // The shuffleDeck method randomly swaps cards in the array for
    // a preset number of loops.
    private static Card[] shuffleDeck(Card[] deck) {
        final int NUMBER_SWAPS = 100000;
        // creates a random number generator.
        java.util.Random generator = new java.util.Random();

        // 2 random between 0 and 52 are chosen and the cards at those indexes
        // are swapped.

        for (int i = 0; i < NUMBER_SWAPS; i++) {
            // Generate 2 random ints between 0 and 52 (counting 0 but not 52).
            int index1 = generator.nextInt(NUMBER_CARDS_DECK);
            int index2 = generator.nextInt(NUMBER_CARDS_DECK);

            Card temporaryCard = deck[index1];

            deck[index1] = deck[index2];

            deck[index2] = temporaryCard;
        }

        return deck;
    }

    // playRound method plays one round of the war game.
    private static void playRound(Card[] deck1, Card[] deck2) {
        // creates an array of Card objects to store the cards in the pile.
        Card[] pile = new Card[NUMBER_CARDS_DECK];

        Card playerOneCard = deck1[0];
        Card playerTwoCard = deck2[0];

        // removes the first card from playerOneCard
        removeTopCard(deck1);
        addCardToBottom(pile, playerOneCard);
        removeTopCard(deck2);
        addCardToBottom(pile, playerTwoCard);

        int comparison = compareCards(playerOneCard, playerTwoCard);
        printRoundResults(playerOneCard, playerTwoCard);

        while (comparison == 0) {


            for (int j = 0; j < NUMBER_CARDS_TIEBREAKER; j++) {

                if (!hasCards(deck1) || !hasCards(deck2)) {
                    return;
                }

                addCardToBottom(pile, deck1[0]);
                addCardToBottom(pile, deck2[0]);
                removeTopCard(deck1);
                removeTopCard(deck2);
            }

            if (!hasCards(deck1) || !hasCards(deck2)) {
                return;
            }

            // compares two top cards again
            playerOneCard = deck1[0];
            playerTwoCard = deck2[0];

            // removes the first card from playerOneCard
            removeTopCard(deck1);
            addCardToBottom(pile, playerOneCard);
            removeTopCard(deck2);
            addCardToBottom(pile, playerTwoCard);

            comparison = compareCards(playerOneCard, playerTwoCard);
            printRoundResults(playerOneCard, playerTwoCard);
        }

        // adds all cards in the pile to the winner of the round's hand.
        if (comparison > 0) {
            while (hasCards(pile)) {
                addCardToBottom(deck1, pile[0]);
                removeTopCard(pile);
            }
        } else if (comparison < 0) {
            while (hasCards(pile)) {
                addCardToBottom(deck2, pile[0]);
                removeTopCard(pile);
            }
        }
    }

    // This method prints the output of a round given two Cards
    private static void printRoundResults(Card playerOneCard, Card playerTwoCard) {
        System.out.println("Player one plays " + playerOneCard.getNumber());
        System.out.println("Player two plays " + playerTwoCard.getNumber());

        int comparison = compareCards(playerOneCard, playerTwoCard);

        if (comparison == 0) {
            System.out.println("WAR!");
        } else if (comparison > 0) {
            System.out.println("Player one wins the round.");
        } else {
            System.out.println("Player two wins the round.");
        }
    }

    // This method removes a card from an array by taking the top card off and
    // shifting every other value in the array over.
    private static void removeTopCard(Card[] deck) {

        for (int i = 0; i < deck.length - 1; i++) {
            deck[i] = deck[i + 1];
        }
    }

    // This method takes as input, a Card array and a Card.
    private static void addCardToBottom(Card[] deck, Card newCard) {
        for (int i = 0; i < deck.length; i++) {
            if (deck[i] == null) {
                deck[i] = newCard;
                return;
            }
        }
    }

    // This method takes as input, 2 Cards.
    private static int compareCards(Card card1, Card card2) {
        int playerOneNumber = card1.getNumber();
        int playerTwoNumber = card2.getNumber();

        if (playerOneNumber == playerTwoNumber) {
            return 0;
        }

        // Check for aces.
        if (playerOneNumber == 1) {
            return 1;
        }

        if (playerTwoNumber == 1) {
            return 1;
        }

        if (playerTwoNumber > playerOneNumber) {
            return -1;
        } else {
            return 1;
        }
    }

    private static boolean hasCards(Card[] deck) {
        for (int i = 0; i < deck.length; i++) {
            if (deck[i] != null) {
                return true;
            }
        }

        return false;
    }

    private static int countCards(Card[] deck) {
        int total = 0;
        for (int i = 0; i < deck.length; i++) {
            if (deck[i] != null) {
                total++;
            }
        }

        return total;
    }
}

-----------------------------------------------------------------------
public class Card {

    private int suit;
    private int number;

    public static final int SPADES = 0;
    public static final int CLUBS = 1;
    public static final int DIAMONDS = 2;
    public static final int HEARTS = 3;

    // setSuit takes as input an int and sets the suit accordingly

    public void setSuit(int newSuit) {
        if (newSuit >= 0 && newSuit <= 3) {
            this.suit = newSuit;
        }
    }

    public int getSuit() {
        return this.suit;
    }

    public void setNumber(int newNumber) {
        this.number = newNumber;
    }

    public int getNumber() {
        return this.number;
    }

    public void setSuitFromString(String suit) {
        if (suit.equals("SPADES")) {
            this.suit = Card.SPADES;
        } else if (suit.equals("CLUBS")) {
            this.suit = Card.CLUBS;
        } else if (suit.equals("DIAMONDS")) {
            this.suit = Card.DIAMONDS;
        } else if (suit.equals("HEARTS")) {
            this.suit = Card.HEARTS;
        } else {
            System.out.println("Illegal suit!");
        }
    }

    public String getSuitAsString() {

        if (this.suit == Card.SPADES) {
            return "SPADES";
        } else if (this.suit == Card.CLUBS) {
            return "CLUBS";
        } else if (this.suit == Card.HEARTS) {
            return "DIAMONDS";
        } else {
            return "HEARTS";
        }
    }
}

WarGame fideaProjects/WarGame] - .../src/WarGame.java [WarGame) WarGame src WarGame Proiect return 0 189 idea out WarGame mai

Add a comment
Know the answer?
Add Answer to:
hello there, i have to implement this on java processing. can someone please help me regarding...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • CS102 : JAVA Object-Oriented Programming. 1 Write a class Card whose instances represent a single playing...

    CS102 : JAVA Object-Oriented Programming. 1 Write a class Card whose instances represent a single playing card from a deck of cards. Playing cards have two distinguishing properties an integer for the rank (1 (corresponding to Ace) ,2,3, 13 (correspond ing to King) and suit (Spades, Hearts, Diamonds, or Clubs). Make the suit an enumerated data type. Include getters and setters and a method that tests if a card is valid. Write a class named Deck whose instances are full...

  • I am just curious about this question... please can you answer with applying indent and space...

    I am just curious about this question... please can you answer with applying indent and space clearly. Furthermore, can you make answer shortly as possible..? This is a python question Question 6.34 The two-player card game war is played with a standard deck of 52 cards. A shuffled deck is evenly split among the two players who keep their decks face-down. The game consists of battles until one of the players runs out of cards. In a battle, each player...

  • NEED HELP TO CREATE A BLACKJACK GAME WITH THE UML DIAGRAM AND PROBLEM SOLVING TO GET...

    NEED HELP TO CREATE A BLACKJACK GAME WITH THE UML DIAGRAM AND PROBLEM SOLVING TO GET CODE TO RUN!! THANKS Extend the DeckofCards and the Card class in the book to implement a card game application such as BlackJack, Texas poker or others. Your game should support multiple players (up to 5 for BlackJack). You must build your game based on the Cards and DeckofCards class from the book. You need to implement the logic of the game. You can...

  • C++ program This program involves writing a VERY simplified version of the card game War. You...

    C++ program This program involves writing a VERY simplified version of the card game War. You may know this game or not but my rules are these 1. Split the deck between player1 and player2. Only the face values matter (2-14) and not the suits 2. Each player puts a card down on the table. The higher face value wins that hand. If the card values match, you will simply indicate tie and neither player wins.The original rules would require...

  • please help me answer this question please. the first two pictures are questions please help. then...

    please help me answer this question please. the first two pictures are questions please help. then the table and the graph pictures are provided to help answer here are the directions if you need to know what happened 1. Did the host or the parasite win the game? Explain The 2. The Red Queen Hypothesis predicts that host-parasite coevolution maintains genetic variation. Was this prediction met for the host population? For the parasite population? What evolutionary forces were responsible for...

  • Deck of Cards Program I need help printing a flush, which is showing the top 5...

    Deck of Cards Program I need help printing a flush, which is showing the top 5 cards of the same suite. Below is the code I already have that answers other objectives, such as dealing the cards, and finding pairs. Towards the end I have attempted printing a flush, but I cannot figure it out. public class Shuffler {    /**    * The number of consecutive shuffle steps to be performed in each call    * to each sorting...

  • Complete a program In C#: some code is included, you edit the areas that have not...

    Complete a program In C#: some code is included, you edit the areas that have not been filled. For your C# program you will complete code that plays the War card game. In this game, the deck of cards is evenly divided among two players. The players are not allowed to look at the cards in their hand. On each round of the game, both players lay down the top card from their hand. The player with the higher value...

  • C++ help This assignment gives you practice with inheritance and pure virtual functions. You will implement...

    C++ help This assignment gives you practice with inheritance and pure virtual functions. You will implement some code that could be part of a program to play a popular card game called “Crazy 8’s”, which is the basis for the game “Uno”. You will start to implement the rules, as described at: https://www.pagat.com/eights/crazy8s.html . Note that the inheritance relationship below is also based on the organization of card games described on that website. Requirements: your work will be split into...

  • C++ Purpose: To practice arrays of records, and stepwise program development. 1. Define a record data...

    C++ Purpose: To practice arrays of records, and stepwise program development. 1. Define a record data type for a single playing card. A playing card has a suit ('H','D','S',or 'C'), and a value (1 through 13). Your record data type should have two fields: a suit field of type char, and a value field of type int. 2. In main(), declare an array with space for 52 records, representing a deck of playing cards. 3. Define a function called initialize()...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT