Question
JAVA Exercise 13.5 Find and open the le War.java in the repository. The main method contains all the code from the last section of this
JAVA
Exercise 13.5 Find and open the le War.java in the repository. The main method contains all the code from the last section of this chapter. Check that you can compile and run this code before proceeding.
The program is incomplete; it does not handle the case when two cards have the same rank. Finish implementing the main method, beginning at the line that says: // it's a tie.
When there's a tie, draw three cards from each pile and store them in a collection, along with the original two. Then draw one more card from each pile and compare them. Whoever wins the tie takes all ten of these cards. If one pile does not have at least four cards, the game ends immediately. If a tie ends with a tie, draw three more cards, and so on.
Notice that this program depends on Deck.shuffle so you might have to do Exercise 13.2 rst.
Code follows:
/** * Simulates a simple card game. */ public class War {
public static void main(String[] args) {
int gameTurns = 0; // variable for tracking game interactions. // tie breaker variables // create the arraylist Pile for tie breaker //
// divide the deck into piles Pile p1 = new Pile(); p1.addDeck(deck.subdeck(0, 25)); Pile p2 = new Pile(); p2.addDeck(deck.subdeck(26, 51)); System.out.println ("Pile 1 >> " + p1.toString()); System.out.println ("Pile 2 >> " + p2.toString());
// while both piles are not empty while ((p1.size() > 0 && p2.size() > 0) && gameTurns < 5000) { gameTurns++; // increment the number of 'hands' Card c1 = p1.popCard(); Card c2 = p2.popCard();
// compare the cards int diff = c1.getRank() - c2.getRank(); if (diff > 0) { p1.addCard(c1); p1.addCard(c2); } else if (diff < 0) { p2.addCard(c1); p2.addCard(c2); } else { // Player One always wins tie by default // this must be replaced by tie breaker algorithm p1.addCard(c1); p1.addCard(c2); if (p2.size() > 0) { p1.addCard(p2.popCard()); } // cards tie, following is 'new' tie breaker logic // Replace default with 13.5 tie breaker algorithm /* * Following are psedudocode statements suggesting actions required by the exercise * After the comment/statement
// display the winner if (p1.size() > 0) { System.out.println("Player 1 wins!"); } else { System.out.println("Player 2 wins!"); } }
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started