Ask Question, Ask an Expert

+61-413 786 465

info@mywordsolution.com

Ask Computer Engineering Expert

Assignment: Simulating the card game of War

In this lab we will implement of the card game of War. We will implement the following features that we have covered so far in this course:

• Implement a Generic Queue using the Floating Front Design Approach (page 225).
• Use the Stack class, imported from java.util ( use peek() instead of top() )
• Define a QueueUnderflow class which extends Exception,
• Define a Card class
• Define a Deck of Card class using a static array.
• Use try/catch blocks to detect Exceptions
• Use a recursive method, battle()

Note the requirements of this lab at the end of this document. Before turning this assignment in, please verify you have fulfilled all of the requirements.

I assume you know how to play the game of war. We will cover the basic rules in class and you can reference the internet for additional information.

For this lab, please create a new Java Project called War. Then create a "staticArray" package where we will implement the Queue class and the QueueUnderflow Exception class.

In the staticArray package

QueueUnderflowException

This class should extend the Exception class. When you create the class in Eclipse, specify Exception as the super class and select "Constructors from superclass" under the "Which method stubs would you like to create". Otherwise, create 2 constructors, one default (without any parameters) and another with 1 parameter (which would be a String).Both constructors will then call their corresponding super class's constructor ( super () ).

QueueInterface(with the following method headers defined:)
voidenqueue ( T element );
T dequeue ( ) throwsQueueUnderflowException;
booleanisEmpty ( );
String toString();
int size();

Queue class - implements the QueueInterface

Implement the Queue with a static array and the Floating Front Design Approach described on page 225 in your text. Your class will have the following instance variables:

private T [] queue;
privateintfront = 0;
privateintrear;
privateintnumElements = 0;

Implement the following methods (most specified in QueueInterface):
public Queue()
- call the 1 argument constructor with the default size of 10
this(10);

public Queue( intsize )
- create the queue with the specified size.
- set rear to size - 1

publicvoidenqueue ( T element )

- add the element on to the end of the queue. If the array is full, expand the array. Increment numElements. Note,enqueue pre-increments rear with a check for wrap around.

public T dequeue ( ) throwsQueueUnderflowException

- remove the element from the front of the queue. If the queue is empty, throw the QueueUnderflowException. Decrement numElements. Note, dequeue post-increments front with a check for wrap around.

publicbooleanisEmpty ( )

- return true if numElements == 0.

public String toString()

- build a string by traversing the queue, from front to rear. You will need this for debugging purposes.

publicint size()

- returns the numElements in the Queue.

I suggest you create a main() method in Queue to verify the operation of your Queue before developing your application.

In the default package

Card class

Cards in a standard deck can be represented with an integer ranging from 0 to 51. There are 4 suites: Hearts, Spades, Clubs, and Diamonds and 13 different cards/ranks per suit: 2-10, J, Q, K, and Ace. Given an integer from 0-51, divide by 13 to get the suit and take the modulus (remainder) of 13 to get the rank (2-10, J, Q, K, and Ace), where 0 is a 2 and 12 is an Ace.

You class will include:

• array of Strings for the suits: {"H", "S", "C", "D"}
• array of Strings for the ranks: {"2", "3", .... "10", "J", "Q", "K", "A"}
• 1 argument constructor which will take an integer within the range 0-51 inclusive.
• Anaccessor/observer to get the rank of the Card
• A toString() method to display the card. Use the following formatting method:

String str = String.format("%1s-%2s", suits[suitIndex], ranks[rankIndex]);

Deck class

Use a static array and a next index to store 52 Card objects. Your constructor will initialize your deck by substantiating each Card object and storing the reference into the array. The next index will be used as the next card to be dealt from the Deck. Your class will include the following methods:

publicvoid shuffle()

- traverse the array and swap each location with another random index. Note, we are only swapping cards already in the deck. When complete, there should never be duplicates of the same card.

public Card dealCard() throwsException

- this method will return the next Card referenced by the next index. The next index should then be incremented.

publicbooleanhasNext()

- this method returns true if there exists another card in the deck.

public String toString()

- this method should traverse (what's left of) the deck, calling the Card's toString() method and concatenate the results. A new line, "\n", should be added every 10 entries. Note, if you concatenate a reference to a String, it calls the Card's toString(). This method should be used for debugging purposes.

War class

Define the following static variables:

static Deck deck;
static Queueplayer1;
static Queueplayer2;
static Stackplayer1stack;
static Stackplayer2stack;
staticbooleangameOver;
staticintnumIterations=0;
staticintmaxIterations=0;
staticinttotalIterations = 0;
staticintnumTies=0;
staticintmaxTies=0;
staticinttotalTies = 0;

Note, you'll import the Queue class from the staticArray package and you'll import the Stack class from java.util.

In main(), create the Deck, the 2 Queues, and the 2 Stacks. Shuffle the Deck and display the contents before and after the shuffle so that you can verify we are starting with a valid deck. You will then deal out all the cards from the Deck, queuing them in an alternating manner to each player's Queue (player1 and player2).

Then use the following while loop:

while (!gameOver)
{
battle();
if (debug)
{
System.out.println("pl:\n" + player1);
System.out.println("p2:\n" + player2);
System.out.println("hit return");
String str = input.nextLine();
}
}

The method, battle(), will set the booleangameOver when one of the players runs out of cards.

In the method battle(), dequeue a Card from each player's queue and push them on to their corresponding stacks. Then compare the card's rank. If player 1 wins, pop all Cards off both stacks and enqueue them onto player 1's queue. If player 2 wins, pop all Cards off both stacks and enqueue them onto player 2's queue. If they tie, then push 2 additional cards onto each player's stack and recursively call battle again. The method battle() should use a try/catch block to detect if a player runs out of cards and set the static boolean variable, gameOver, accordingly.

As mentioned above, when a player wins in battle(), you need to move the Cards from both Stacks to the winning player's Queue. I suggest you randomly select which Stack to take from first. When I ran this program 10,000 times, I ran into a situation where I went into an endless loop because the cards get into a certain order and it just repeated. When I randomized the order of how they are put back onto the winner's Queue, I did not run into the problem.

The variable numIterations tracks the number of calls to battle(). Once you get the program running, add a for loop at the beginning of main() and repeat 10000 times. Note, you'll also need to reinitialize some variables. Determine the max number of iterations and the average number of iterations. You can also add an additional counter when you detect a tie in battle. Compare them with my results below. Note, comment out all print statements when you run this test. When I ran it 10,000 times, it took less than 20 seconds.

Requirements of this lab:

- Card class
- Deck class
- Generic Queue using the Floating Point Design Approach described on page 225.
- A queue for each player, holding their Cards.
- A stack for each player, used in battle().
- Output detailing the max number of iterations and the average number of iterations for 10,000 games played.

In my implementation, I saw the following results with 10,000 games:

Iterations: max=2664, avg=349
Ties: max=146, avg = 20

Computer Engineering, Engineering

  • Category:- Computer Engineering
  • Reference No.:- M92752895

Have any Question?


Related Questions in Computer Engineering

Question please review the description of the organization

Question: Please review the description of the organization that is the subject of your semester project. The description of that organization, CITY GENERAL HOSPITAL, is described in the instructions for Phase I that you ...

Pablo bought some rural property in oconee county that is

Pablo bought some rural property in Oconee County that is rumored to be part of an expansion of the Epps Bridge Center phenomenon. The developer of the party told him that the property could triple in value under the exp ...

Java program that prompts the user to enter the base and

Java program that prompts the user to enter the base and slant height for a regular pyramid shape, then calculates and outputs its volume and surface area. A and B are requirements A It is required to use JOptionPane's I ...

Anbspthe reaction of an aqueous monoprotic strong acid such

a: The reaction of an aqueous monoprotic strong acid (such as HBr (aq)) with an aqueous alkali strong base (such as LiOH (aq)) always has the same heat of reaction regardless of which strong acids and strong base were us ...

Question please read this instruction and section 5 and 6

Question: Please read this instruction, and section 5 and 6 in particular, CAREFULLY as it affects all future programming assignments. 1. Setup Android Studio Development Environment 1.1 Download necessary packages using ...

Question this is a scholarly post and your responses should

Question: This is a scholarly post and your responses should have more depth than "I agree" and should demonstrate critical reflection of the problem in order to promote vigorous discussion of the topic within the forum. ...

Question explain the need for designing procedures for

Question: Explain the need for designing procedures for simple tasks such as creating or modifying access controls. Create a procedure guide that provides clear instructions that anyone with a basic technical knowledge b ...

A scavenger hunt question from the assigned

A scavenger hunt question from the assigned readings.) Consider the statement if ((a! = null)&&(a.x()))a.y(); What feature of the a && b makes it classify as a control structure? Rewrite this as 2 nested if statements. W ...

Suppose there are n people in a team the coach wants to

Suppose there are n people in a team. The coach wants to know how many different pairs of people he can choose in a team. Write a program in C that shows the coach, the total number of different pairs he can choose in th ...

What steps are required in determining the big-oh notation

What steps are required in determining the Big-Oh notation for the algorithm when sorting an array of integers 5 7 4 9 8 5 6 3 and showing the contents each time a selection sort changes it while sorting the array into a ...

  • 4,153,160 Questions Asked
  • 13,132 Experts
  • 2,558,936 Questions Answered

Ask Experts for help!!

Looking for Assignment Help?

Start excelling in your Courses, Get help with Assignment

Write us your full requirement for evaluation and you will receive response within 20 minutes turnaround time.

Ask Now Help with Problems, Get a Best Answer

Why might a bank avoid the use of interest rate swaps even

Why might a bank avoid the use of interest rate swaps, even when the institution is exposed to significant interest rate

Describe the difference between zero coupon bonds and

Describe the difference between zero coupon bonds and coupon bonds. Under what conditions will a coupon bond sell at a p

Compute the present value of an annuity of 880 per year

Compute the present value of an annuity of $ 880 per year for 16 years, given a discount rate of 6 percent per annum. As

Compute the present value of an 1150 payment made in ten

Compute the present value of an $1,150 payment made in ten years when the discount rate is 12 percent. (Do not round int

Compute the present value of an annuity of 699 per year

Compute the present value of an annuity of $ 699 per year for 19 years, given a discount rate of 6 percent per annum. As