Docsity

Solitaire - Case Study - Object-Oriented Analysis and Programming | CS 582, Study notes of Computer Science

Toggle sidebar
bg1
Chapter 8
A Case Study: Solitaire
A program for playing the card game
solitaire
will illustrate the utility and power of in-
heritance and overriding. A major part of the game of Solitaire is moving cards from one
card pile to another. There are a number of dierenttypes of card piles, eachhaving some
features in common with the others, while other features are unique. A common parent class
CardPile
can therefore be used to capture the common elements, while inheritance and over-
riding can be used to produce specialized types of piles. The developement of this program
will illustrate how inheritance can be used to simplify the creation of these components and
ensure that they can all be manipulated in a similar fashion.
8.1 The Class
Card
To create a card game, we rst need to dene a class to represent a playing card. Each
instance of class
Card
(Figure 8.1) maintains a suit value and a rank. To prevent modication
of these values, the instance variables maintaining them are declared
private
and access is
mediated through accessor functions. The value of the suit and rank elds are set by the
constructor for the class. Integer constantvalues (in Java dened by the use of
nal static
constants) are dened for the height and width of the card as well as for the suits. Another
function permits the user to determine the color of the card. The Java library class
Color
is used to represent the color abstraction. The
Color
class denes constants for various
colors. The values
Color.red
,
Color.black
,
Color.yellow
and
Color.blue
are used in the solitare
program.
There are important reasons that data values representing suit and rank should be
returned through an accessor function, as opposed to dening the data elds
s
and
r
as
public
and allowing direct access to the data values. One of the most imp ortant is that
access through a function ensures that the rank and suit characteristics of a card can be
read but not altered once the card has been created.
99
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15

Partial preview of the text

Download Solitaire - Case Study - Object-Oriented Analysis and Programming | CS 582 and more Study notes Computer Science in PDF only on Docsity!

Chapter 8

A Case Study: Solitaire

A program for playing the card game solitaire will illustrate the utility and p ower of in- heritance and overriding. A ma jor part of the game of Solitaire is moving cards from one card pile to another. There are a numb er of di erent typ es of card piles, each having some features in common with the others, while other features are unique. A common parent class CardPile can therefore b e used to capture the common elements, while inheritance and over- riding can b e used to pro duce sp ecialized typ es of piles. The develop ement of this program will illustrate how inheritance can b e used to simplify the creation of these comp onents and ensure that they can all b e manipulated in a similar fashion.

8.1 The Class Card

To create a card game, we rst need to de ne a class to represent a playing card. Each instance of class Card (Figure 8.1) maintains a suit value and a rank. To prevent mo di cation of these values, the instance variables maintaining them are declared private and access is mediated through accessor functions. The value of the suit and rank elds are set by the constructor for the class. Integer constant values (in Java de ned by the use of nal static constants) are de ned for the height and width of the card as well as for the suits. Another function p ermits the user to determine the color of the card. The Java library class Color is used to represent the color abstraction. The Color class de nes constants for various colors. The values Color.red, Color.black, Color.yellow and Color.blue are used in the solitare program. There are imp ortant reasons that data values representing suit and rank should b e returned through an accessor function, as opp osed to de ning the data elds s and r as public and allowing direct access to the data values. One of the most imp ortant is that access through a function ensures that the rank and suit characteristics of a card can b e read but not altered once the card has b een created.

100 CHAPTER 8. A CASE STUDY: SOLITAIRE

import java.awt.;

public class Card f // public constants for card width and suits public final static int width = 50; public final static int height = 70; public final static int heart = 0; public final static int spade = 1; public final static int diamond = 2; public final static int club = 3; // internal data elds for rank and suit private boolean faceup; private int r; private int s;

// constructor Card (int sv, int rv) f s = sv; r = rv; faceup = false; g

// access attributes of card public int rank () f return r; g

public int suit() f return s; g

public boolean faceUp() f return faceup; g

public void flip() f faceup =! faceup; g

public Color color() f if (faceUp()) if (suit() == heart jj suit() == diamond) return Color.red; else return Color.black; return Color.yellow; g

public void draw (Graphics g, int x, int y) f ... g g

Figure 8.1: Description of the class card.

102 CHAPTER 8. A CASE STUDY: SOLITAIRE

public class Card f ... public void draw (Graphics g, int x, int y) f String names[] = f"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"g; // clear rectangle, draw b order g.clearRect(x, y, width, height); g.setColor(Color.blue); g.drawRect(x, y, width, height); // draw b o dy of card g.setColor(color()); if (faceUp()) f g.drawString(names[rank()], x+3, y+15); if (suit() == heart) f g.drawLine(x+25, y+30, x+35, y+20); g.drawLine(x+35, y+20, x+45, y+30); g.drawLine(x+45, y+30, x+25, y+60); g.drawLine(x+25, y+60, x+5, y+30); g.drawLine(x+5, y+30, x+15, y+20); g.drawLine(x+15, y+20, x+25, y+30); g else if (suit() == spade) f ... g else if (suit() == diamond) f ... g else if (suit() == club) f g.drawOval(x+20, y+25, 10, 10); g.drawOval(x+25, y+35, 10, 10); g.drawOval(x+15, y+35, 10, 10); g.drawLine(x+23, y+45, x+20, y+55); g.drawLine(x+20, y+55, x+30, y+55); g.drawLine(x+30, y+55, x+27, y+45); g g else f // face down g.drawLine(x+15, y+5, x+15, y+65); g.drawLine(x+35, y+5, x+35, y+65); g.drawLine(x+5, y+20, x+45, y+20); g.drawLine(x+5, y+35, x+45, y+35); g.drawLine(x+5, y+50, x+45, y+50); g g g

Figure 8.2: Pro cedure to draw a playing card.

8.2. THE GAME 103

Table Piles

Discard Deck

Suit Piles

Figure 8.3: Layout for the solitaire game.

game is to build all 52 cards into the suit piles.

The cards that are not part of the tableau are initially all in the deck. Cards in the deck are face down, and are drawn one by one from the deck and placed, face up, on the discard pile. From there, they can b e moved onto either a tableau pile or a foundation. Cards are drawn from the deck until the pile is empty; at this p oint, the game is over if no further moves can b e made.

Cards can b e placed on a tableau pile only on a card of next-higher rank and opp osite color. They can b e placed on a foundation only if they are the same suit and next higher card or if the foundation is empty and the card is an ace. Spaces in the tableau that arise during play can b e lled only by kings. The topmost card of each tableau pile and the topmost card of the discard pile are always available for play. The only time more than one card is moved is when an entire collection of face-up cards from a tableau (called a build) is moved to another tableau pile. This can b e done if the b ottommost card of the build can b e legally played on the topmost card of

8.3. CARD PILES{INHERITANCE IN ACTION 105

import java.util.Stack; import java.util.EmptyStackException;

public class CardPile f protected int x; // co ordinates of the card pile protected int y; protected Stack thePile; // the collection of cards

CardPile (int xl, int yl) f x = xl; y = yl; thePile = new Stack(); g

public final Card top() f return (Card) thePile.peek(); g

public final boolean isEmpty() f return thePile.empty(); g

public final Card pop() f try f return (Card) thePile.pop(); g catch (EmptyStackException e) f return null; g g

// the following are sometimes overridden public boolean includes (int tx, int ty) f return x <= tx && tx <= x + Card.width && y <= ty && ty <= y + Card.height; g

public void select (int tx, int ty) f g

public void addCard (Card aCard) f thePile.push(aCard); g

public void display (Graphics g) f g.setColor(Color.blue); if (isEmpty()) g.drawRect(x, y, Card.width, Card.height); else top().draw(g, x, y); g

public boolean canTake (Card aCard) f return false; g g

Figure 8.4: Description of the class CardPile.

106 CHAPTER 8. A CASE STUDY: SOLITAIRE

same suit as the current topmost card in the pile and has the next-higher value. A card can b e added to a tableau pile, on the other hand, only if the pile is empty and the card is a king, or if it is of the opp osite color as the current topmost card in the pile and has the next lower value. The actions of the ve virtual functions de ned in CardPile can b e characterized as follows:

includes {Determines if the co ordinates given as arguments are contained within the b ound- aries of the pile. The default action simply tests the topmost card; this is overridden in the tableau piles to test all card values.

canTake {Tells whether a pile can take a sp eci c card. Only the tableau and suit piles can take cards, so the default action is simply to return no; this is overridden in the two classes mentioned.

addCard {Adds a card to the card list. It is rede ned in the discard pile class to ensure that the card is face up.

display {Displays the card deck. The default metho d merely displays the topmost card of the pile, but is overridden in the tableau class to display a column of cards. The top half of each hidden card is displayed. So that the playing surface area is conserved, only the topmost and b ottommost face-up cards are displayed (this p ermits us to give de nite b ounds to the playing surface).

select {Performs an action in resp onse to a mouse click. It is invoked when the user selects a pile by clicking the mouse in the p ortion of the playing eld covered by the pile. The default action do es nothing, but is overridden by the table, deck, and discard piles to play the topmost card, if p ossible.

The following table illustrates the imp ortant b ene ts of inheritance. Given ve op er- ations and ve classes, there are 25 p otential metho ds we might have had to de ne. By making use of inheritance we need to implement only 13. Furthermore, we are guaranteed that each pile will resp ond in the same way to similar requests.

CardPile SuitPile DeckPile DiscardPile TableauPile includes   canTake    addCard   display   select    

108 CHAPTER 8. A CASE STUDY: SOLITAIRE

p otentially b e negative, the math library function abs is called to make it p ositive. The mo dular division op eration is nally used to pro duce a randomly selected integer value b etween 0 and 52.

A subtle feature to note is that we are here p erforming a random access to the elements of a Stack. The conventional view of a stack do es not allow access to any but the topmost element. However, in the Java library the Stack container is constructed using inheritance from the Vector class. Thus, any legal op eration on a Vector, such as the metho d elementAt(), can also b e applied to a Stack.

The metho d select is invoked when the mouse button is used to select the card deck. If the deck is empty, it do es nothing. Otherwise, the topmost card is removed from the deck and added to the discard pile.

Java do es not have global variables. Where a value is shared b etween multiple instances of similar classes, such as the various piles used in our solitaire game, an instance variable can b e declared static. As we will noted in Chapter 2, one copy of a static variable is created and shared b etween all instances. In our present program, static variables will b e used to maintain all the various card piles. These will b e held in an instance of class Solitaire, which we will subsequently describ e. To access these values we use a complete quali ed name, which includes the name of the class as well as the name of the variable. This is shown in the select metho d in Figure 8.6, which refers to the variable Solitare.discardPile to access the discard pile.

8.3.3 The Discard Pile

The class DiscardPile (Figure 8.7) is interesting in that it exhibits two very di erent forms of inheritance. The select metho d overrides or replaces the default b ehavior provided by class CardPile, replacing it with co de that when invoked (when the mouse is pressed over the card pile) checks to see if the topmost card can b e played on any suit pile or, alternatively, on any tableau pile. If the card cannot b e played, it is kept in the discard pile.

The metho d addCard is a di erent sort of overriding. Here the b ehavior is a re nement of the default b ehavior in the parent class. That is, the b ehavior of the parent class is completely executed, and, in addition, new b ehavior is added. In this case, the new b ehavior ensures that when a card is placed on the discard pile it is always face up. After satisfying this condition, the co de in the parent class is invoked to add the card to the pile by passing the message to the pseudo-variable named sup er.

Another form of re nement o ccurs in the constructors for the various sub classes. Each must invoke the constructor for the parent class to guarantee that the parent is prop erly initialized b efore the constructor p erforms its own actions. The parent constructor is in- voked by the pseudo-variable sup er b eing used as a function inside the constructor for the child class. In Chapter ?? we will have much more to say ab out the distinction b etween replacement and re nement in overriding.

8.3. CARD PILES{INHERITANCE IN ACTION 109

class DeckPile extends CardPile f

DeckPile (int x, int y) f // rst initialize parent super(x, y); // then create the new deck // rst put them into a lo cal pile for (int i = 0; i < 4; i++) for (int j = 0; j <= 12; j++) addCard(new Card(i, j));

// then shue the cards Random generator = new Random(); for (int i = 0; i < 52; i++) f int j = Math.abs(generator.nextInt()) % 52; // swap the two card values Object temp = thePile.elementAt(i); thePile.setElementAt(thePile.elementAt(j), i); thePile.setElementAt(temp, j); g g

public void select(int tx, int ty) f if (isEmpty()) return; Solitare.discardPile.addCard(pop()); g g

Figure 8.6: The class DeckPile.

8.4. THE APPLICATION CLASS 111

8.3.4 The Tableau Piles

The most complex of the sub classes of CardPile is that used to hold a tableau, or table pile. It is shown in Figures 8.8 and 8.9. Table piles di er from the generic card pile in the following ways:

 When initialized (by the constructor), the table pile removes a certain numb er of cards from the deck, placing them in its pile. The numb er of cards so removed is determined by an additional argument to the constructor. The topmost card of this pile is then displayed face up.

 A card can b e added to the pile (metho d canTake) only if the pile is empty and the card is a king, or if the card is the opp osite color from that of the current topmost card and one smaller in rank.

 When a mouse press is tested to determine if it covers this pile (metho d includes) only the left, right, and top b ounds are checked; the b ottom b ound is not tested since the pile may b e of variable length.

 When the pile is selected, the topmost card is ipp ed if it is face down. If it is face up, an attempt is made to move the card rst to any available suit pile, and then to any available table pile. Only if no pile can take the card is it left in place.

 To display the pile, each card in the pile is drawn in turn, each moving down slightly. To access the individual elements of the stack, an Enumeration is created. Enumeration ob jects are provided by all the containers in the Java library, and allow one to easily lo op over the elements in the container.

8.4 The Application Class

Figure 8.10 shows the central class for the solitare application. As in our earlier case studies, the control is initially given to the static pro cedure named main, which creates an instance of the application class. The constructor for the application creates a window for the application, by constructing an instance of a nested class SolitareFrame that inherits from the library class Frame. After invoking the init metho d, which p erforms the application initialization, the window is given the message show, which will cause it to display itself. We noted earlier that the variables maintaining the di erent piles, which are shared in common b etween all classes, are declared as static data elds in this class. These data elds are initialized in the metho d name init. Arrays in Java are somewhat di erent from arrays in most languages. Java distinguishes the three activities of array declaration, array allo cation, and assignment to an array lo- cation. Note that the declaration statements indicate only that the named ob jects are an array and not that they have any sp eci c b ound. One of the rst steps in the initialization

112 CHAPTER 8. A CASE STUDY: SOLITAIRE

class TablePile extends CardPile f

TablePile (int x, int y, int c) f // initialize the parent class super(x, y); // then initialize our pile of cards for (int i = 0; i < c; i++) f addCard(Solitare.deckPile.pop()); g // ip topmost card face up top().flip(); g

public boolean canTake (Card aCard) f if (isEmpty()) return aCard.rank() == 12; Card topCard = top(); return (aCard.color() != topCard.color()) && (aCard.rank() == topCard.rank() - 1); g

public boolean includes (int tx, int ty) f // don't test b ottom of card return x <= tx && tx <= x + Card.width && y <= ty; g

public void display (Graphics g) f int localy = y; for (Enumeration e = thePile.elements(); e.hashMoreElements(); ) f Card aCard = (Card) e.nextElement(); aCard.draw (g, x, localy); localy += 35; g g ... g

Figure 8.8: The class TablePile, part 1.

114 CHAPTER 8. A CASE STUDY: SOLITAIRE

public class Solitare f static public DeckPile deckPile; static public DiscardPile discardPile; static public TablePile tableau [ ]; static public SuitPile suitPile [ ]; static public CardPile allPiles [ ]; private Frame window;

static public void main (String [ ] args) f Solitare world = new Solitare(); g

public Solitare () f window = new SolitareFrame(); init(); window.show(); g

public void init () f // rst allo cate the arrays allPiles = new CardPile[13]; suitPile = new SuitPile[4]; tableau = new TablePile[7]; // then ll them in allPiles[0] = deckPile = new DeckPile(335, 30); allPiles[1] = discardPile = new DiscardPile(268, 30); for (int i = 0; i < 4; i++) allPiles[2+i] = suitPile[i] = new SuitPile(15 + (Card.width+10)  i, 30); for (int i = 0; i < 7; i++) allPiles[6+i] = tableau[i] = new TablePile(15+(Card.width+5)i, Card.height+35, i+1); g

private class SolitareFrame extends Frame f ... g g

Figure 8.10: The class Solitaire.

8.5. PLAYING THE POLYMORPHIC GAME 115

routine is to allo cate space for the three arrays (the suit piles, the tableau, and the array allPiles we will discuss shortly). The new command allo cates space for the arrays, but do es not assign any values to the array elements. The next step is to create the deck pile. Recall that the constructor for this class creates and shues the entire deck of 52 cards. The discard pile is similarly constructed. A lo op then creates and initializes the four suit piles, and a second lo op creates and initializes the tableau piles. Recall that as part of the initialization of the tableau, cards are removed from the deck and inserted in the tableau pile. The inner class SolitareFrame, used to manage the application window, is shown in Fig- ure 8.11. In addition to the cards, a button will b e placed at the b ottom of the window. Listeners are created b oth for mouse events (see Chapter 5) and for the button. When pressed, the button will invoke the button listener metho d. This metho d will reinitialize the game, then repaint the window. Similarly, when the mouse listener is invoked (in resp onse to a mouse press) the collection of card piles will b e examined, and the appropriate pile will b e displayed.

8.5 Playing the Polymorphic Game

Both the mouse listener and the repaint metho d for the application window make use of the array allPiles. This array is used to represent all 13 card piles. Note that as each pile is created it is also assigned a lo cation in this array, as well as in the appropriate static variable. We will use this array to illustrate yet another asp ect of inheritance. The principle of substitutability is used here: The array allPiles is declared as an array of CardPile, but in fact is maintaining a variety of card piles. This array of all piles is used in situations where it is not imp ortant to distinguish b etween various typ es of card piles; for example, in the repaint pro cedure. To repaint the display, each di erent card pile is simply asked to display itself. Similarly, when the mouse is pressed, each pile is queried to see if it contains the given p osition; if so, the card is selected. Rememb er, of the piles b eing queried here seven are tableau piles, four are foundations, and the remaining are the discard pile and the deck. Furthermore, the actual co de executed in resp onse to the invo cation of the includes and select routines may b e di erent in each call, dep ending up on the typ e of pile b eing manipulated. The use of a variable declared as an instance of the parent class holding a value from a sub class is one asp ect of polymorphism, a topic we will return to in more detail in a subsequent chapter.

8.6 Building a More Complete Game

The solitaire game describ ed here is minimal and exceedingly hard to win. A more realistic game would include at least a few of the following variations:

8.6. BUILDING A MORE COMPLETE GAME 117

 The metho d select in class TablePile would b e extended to recognize builds. That is, if the topmost card could not b e played, the b ottommost face-up card in the pile should b e tested against each tableau pile; if it could b e played, the entire collection of face-up cards should b e moved.

 Our game halts after one series of moves through the deck. An alternative would b e that when the user selected the empty deck pile (by clicking the mouse in the area covered by the deck pile) the discard pile would b e reshued and copied back into the deck, allowing execution to continue.

Various other alternatives are describ ed in the exercises.

Study Questions

  1. What data values are maintained by class Card? What b ehaviors can a card p erform? (That is, what metho ds are implemented by the class Card?)
  2. Explain why the suit and rank data elds are declared as private.
  3. What is a default constructor? What is a copy constructor?
  4. What is an accessor function? What is what advantage of using an accessor function as opp osed to direct access to a data memb er?
  5. Why might you want to make accessor functions into inline functions? What factors should you consider in deciding whether to declare a function in an inline fashion?
  6. What are the 13 di erent card piles that are used in the solitare game?
  7. What is a virtual memb er function? Describ e the ve virtual functions implemented in class CardPile and overridden in at least one child class.
  8. How do es the use of inheritance reduce the amount of co de that would otherwise b e necessary to implement the various typ es of card piles?
  9. Explain the di erence b etween overriding used for replacment and overriding used for re nement. Find another example of each in the metho ds asso ciated with class CardPile and its various sub classes.
  10. Explain how p olymorphism is exhibited in the solitare game application.

118 CHAPTER 8. A CASE STUDY: SOLITAIRE

Exercises

  1. The solitaire game has b een designed to b e as simple as p ossible. A few features are somewhat annoying, but can b e easily remedied with more co ding. These include the following:

(a) The topmost card of a tableau pile should not b e moved to another tableau pile if there is another face-up card b elow it. (b) An entire build should not b e moved if the b ottommost card is a king and there are no remaining face-down cards.

For each, describ e what pro cedures need to b e changed, and give the co de for the up dated routine.

  1. The following are common variations of klondike. For each, describ e which p ortions of the solitaire program need to b e altered to incorp orate the change.

(a) If the user clicks on an empty deck pile, the discard pile is moved (p erhaps with shuing) back to the deck pile. Thus, the user can traverse the deck pile multiple times. (b) Cards can b e moved from the suit pile back into the tableau pile. (c) Cards are drawn from the deck three at a time and placed on the discard pile in reverse order. As b efore, only the topmost card of the discard pile is available for playing. If fewer than three cards remain in the deck pile, all the remaining cards (as many as that may b e) are moved to the discard pile. (In practice, this variation is often accompanied by variation 1, p ermitting multiple passes through the deck). (d) The same as variation 3, but any of the three selected cards can b e played. (This requires a slight change to the layout as well as an extensive change to the discard pile class). (e) Any royalty card, not simply a king, can b e moved onto an empty tableau pile.

  1. The game \thumb and p ouch" is similar to klondike except that a card may b e built on any card of next-higher rank, of any suit but its own. Thus, a nine of spades can b e played on a ten of clubs, but not on a ten of spades. This variation greatly improves the chances of winning. (According to Morehead [?], the chances of winning Klondike are 1 in 30, whereas the chances of winning thumb and p ouch are 1 in 4.) Describ e what p ortions of the program need to b e changed to accommo date this variation.
  2. The game \whitehead" is sup er cially similar to klondike, in the sense that it uses the same layout. However, uses di erent rules for when card can b e played in the tableau: