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

Does bmw have a guided missile corporate culture and

Does BMW have a guided missile corporate culture, and incubator corporate culture, a family corporate culture, or an Eiffel tower corporate culture?

Rebecca borrows 10000 at 18 compounded annually she pays

Rebecca borrows $10,000 at 18% compounded annually. She pays off the loan over a 5-year period with annual payments, starting at year 1. Each successive payment is $700 greater than the previous payment. (a) How much was ...

Jeff decides to start saving some money from this upcoming

Jeff decides to start saving some money from this upcoming month onwards. He decides to save only $500 at first, but each month he will increase the amount invested by $100. He will do it for 60 months (including the fir ...

Suppose you make 30 annual investments in a fund that pays

Suppose you make 30 annual investments in a fund that pays 6% compounded annually. If your first deposit is $7,500 and each successive deposit is 6% greater than the preceding deposit, how much will be in the fund immedi ...

Question -under what circumstances is it ethical if ever to

Question :- Under what circumstances is it ethical, if ever, to use consumer information in marketing research? Explain why you consider it ethical or unethical.

What are the differences between four types of economics

What are the differences between four types of economics evaluations and their differences with other two (budget impact analysis (BIA) and cost of illness (COI) studies)?

What type of economic system does norway have explain some

What type of economic system does Norway have? Explain some of the benefits of this system to the country and some of the drawbacks,

Among the who imf and wto which of these governmental

Among the WHO, IMF, and WTO, which of these governmental institutions do you feel has most profoundly shaped healthcare outcomes in low-income countries and why? Please support your reasons with examples and research/doc ...

A real estate developer will build two different types of

A real estate developer will build two different types of apartments in a residential area: one- bedroom apartments and two-bedroom apartments. In addition, the developer will build either a swimming pool or a tennis cou ...

Question what some of the reasons that evolutionary models

Question : What some of the reasons that evolutionary models are considered by many to be the best approach to software development. The response must be typed, single spaced, must be in times new roman font (size 12) an ...

  • 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