CPSC 170 Lab 3: Polymorphism and Interfaces

Polymorphism

Consider the game of Monopoly. The game consists of a sequential set of 40 squares containing 28 properties, 6 Action squares (3 "Chance", 3 "Community Chest"), 2 Tax squares, "GO", "Jail", "Free Parking", and "Go To Jail.". The game is played by moving through the set of squares. Every time a player lands of a square, they take a different action, depending on the type of a square. For example, if you land on a "Tax Square", you must pay the bank a certain amount of money, but if you land on an "Action Square" you must draw a card from the appropriate pile and follow the instructions on the card.

Note that this is a perfect example of polymorphism. Take a deep breath and relax, you are not implementing Monopoly during this lab. However, you are going to use polymorphism to describe the gameplay. To accomplish this you should:

Comparable Interface

The file DrawCards.java contains a programs that draws a list of cards. It uses the classes Card.java to represent individual cards and ArrayList.java to represent a list of cards. The ArrayList class add generics and a few unimplemented methods to the ArrayList class you created in for the last assignment. It also uses the images in GPLCards.tgz (place this directory in your eclipse directory). Try running the program. Notice that the two buttons do not do anything. Fix that by doing the following.

  1. Complete the shuffle method. There are several ways to shuffle the elements in an array. One easy way to do this is to swap randomly choosen pairs of cards a sufficient number of time. In order to help with this you should write private method that swaps the objects at two specified indices.
  2. Complete the sort method. There are also several ways to sort an array. One of the simplest uses the same swap method you created for shuffling. Create a loop that searches through the array for the smallest valued element and swap it with the first element in the list. Then, search the array excluding the first element to find the second smallest element and swap it with the second element. Repeat this for all elements in the list. Note that the sort method already has an if statement to check if the array contains objects that implement the Comparable interface. Classes that implement the comparable interface must define the compareTo method. Look at the javadoc for this method in to figure out how you can use it to find the minimum in an array.
  3. Make the Card class implement Comparable. In order for the list of cards to be sorted the Card class must have the CompareTo method. Note, it is easy to decide whether a two of clubs is less than or greater than a three of clubs, but what about a two of clubs and a two of spades? It is up to you to decide what the compareTo method should return in cases like this.

To submit your code: Tar your lab3 directory and submit your code on the course Inquire site.