Implement the queue with a static array

Assignment Help Computer Engineering
Reference no: EM131914231

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<T>(with the following method headers defined:)
voidenqueue ( T element );
T dequeue ( ) throwsQueueUnderflowException;
booleanisEmpty ( );
String toString();
int size();

Queue <T>class - implements the QueueInterface<T>

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 Queue<Card>player1;
static Queue<Card>player2;
static Stack<Card>player1stack;
static Stack<Card>player2stack;
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

Reference no: EM131914231

Questions Cloud

Assess riskfactors for obesity : A study is conducted in 100 children to assess riskfactors for obesity.Children are enrolled and undergo a complete physical examination.
Explain why it is important for organizations like the case : Give examples of internal and external stakeholders and where do you fit them in the stakeholder's matrix? Be thoughtful.
Write research proposal on an IT prototype system : Task: Applying IT R&D Methodology - Write a short research proposal (500 words) on an IT prototype system to solving one the problems
Estimate for the population proportion of travelers : Construct a 95?% confidence interval estimate for the population proportion of travelers who said that location was very important for choosing a hotel.
Implement the queue with a static array : Implement the Queue with a static array and the Floating Front Design Approach described on page 225 in your text.
In addition to operating cash flow from assets approach : In addition to Operating Cash Flow from Assets approach there are three alternative ways to calculate the same thing. What are those three ways?
Smallest of the standard normal quantile values covers : With 41 ?observations, the smallest of the standard normal quantile values covers an area under the normal curve of __/42 = __ .
NPV and IRR Analysis : After discovering a new gold vein in the Colorado mountains, CTC Mining Corporation must decide whether to go ahead and develop the deposit.
What is the hypothesis of interest : Assume an investigator is wanting to test the hypothesis that female athletes consume on average more than 2403.7 calories a day.

Reviews

Write a Review

Computer Engineering Questions & Answers

  Develop a scheme for solving the problem

Develop a scheme for solving the problem as an unconstrained minimization problem

  Plot the positions of the poles and zeros in the z-plane

In this problem. the degrees of the numerator and denominator polynomials are different, so there should be zeros (or poles) at z = 0 or z = 8.

  What is the goal of the implementation phase of the sdlc

Describe generalization/specializatDescribe generalization/specialization class relationship and how this relationship relates to the concept of inheritance. Explain what is the goal of the Implementation phase of the SDLC.

  What do you suggest that brian tell joe

Because Brian has a little inside knowledge about Joe's agenda for this meeting, he has been considering how to handle Joe. What do you suggest that Brian tell Joe?

  Create a logical data model

Create a logical data model. (You may have done this already in Chapter 7.) Apply the rules of normalization to the model to check the model for processing efficiency.

  Find out the retail price for each product

A mail-order house sells five products whose retail prices are as follows: Product 1, $2.98; product 2, $4.50; product 3, $9.98; product 4, $4.49; product 5, $6.87.

  Write a program for policy iteration problem

Write a program for policy iteration and re-solve Jack's car rental problem with the following changes.

  Dns servers and dhcp servers

Assume that both the DNS servers and the DHCP servers send your client PC and IP addresses. Write down the differences between these two addresses.

  How each diagram relates to the solution

Your submission should include 6 to 8 pages of Visio developed UML diagrams (minimum of six different ones), hierarchy chart, and flowcharts; copy/paste into a MS Word document that also contains the pseudo code and data dictionary for the solutio..

  Write a java program that inputs a document

Write a Java program that inputs a document and then outputs a bar-chart plot of the frequencies of each alphabet character that appears in that document.

  Write a java console application

Write a java console application that allows the user to keep track of various items in a grocery shop - Calculate and store shop price for all items

  Assume you are a wireless network contractor

How would you describe the OSI model to somebody like this potential client who does not have a technical background? Come up with an analogy, that would help clarify your explanation. Note: If you decide to use an analogy it should be original an..

Free Assignment Quote

Assured A++ Grade

Get guaranteed satisfaction & time on delivery in every assignment order you paid with us! We ensure premium quality solution document along with free turntin report!

All rights reserved! Copyrights ©2019-2020 ExpertsMind IT Educational Pvt Ltd