11. Inheritance and Polymorphism

11.7. Case Study: A Two Player Game Hierarchy

In this section we will redesign our OneRowNim game to fit within a hi- erarchy of classes of two-player games, which are games that involve two players. Many games that this characteristic: checkers, chess, tic-tac-toe, guessing games, and so forth. However, there are also many games that involve just 1 player: blackjack, solitaire, and others. There are also games

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Generic superclass

 

 

 

 

 

 

 

 

Figure8.18:Thecurrent

OneRowNim class.


that involve two or more players, such as many card games. Thus, our redesign of OneRowNim as part of a two-player game hierarchy will not be our last effort to design a hierarchy of game-playing classes. We will certainly re-design things as we learn new Java language constructs and as we try to extend our game library to other kinds of games.

This case study will illustrate how we can apply inheritance and poly- morphism, as well as other object-oriented design principles. The justifica- tion for revising OneRowNim at this point is to make it easier to design and develop other two-player games. As we have seen, one characteristic of class hierarchies is that more general attributes and methods are defined in top-level classes. As one proceeds down the hierarchy, the methods and attributes become more specialized. Creating a subclass is a matter of specializing a given class.

Design Goals

One of our design goals is to revise the OneRowNim game so that it fits into a hierarchy of two-player games. One way to do this is to gener- alize the OneRowNim game by creating a superclass that contains those attributes and methods that are common to all two-player games. The su- perclass will define the most general and generic elements of two-player games. All two-player games, including OneRowNim, will be defined as subclasses of this top-level superclass and will inherit and possibly over- ride its public and protected variables and methods. Also, our top-level class will contain certain abstract methods, whose implementations will be given in OneRowNim and other subclasses.

A second goal is to design a class hierarchy that makes it possible for

computers to play the game, as well as human users. Thus, for a given two-player game, it should be possible for two humans to play each other, or for two computers to play each other, or for a human to play against a computer. This design goal will require that our design exhibit a certain amount of flexibility. As we shall see, this is a situation in which Java interfaces will come in handy.

Another important goal is to design a two-player game hierarchy that can easily be used with a variety of different user interfaces, including command-line interfaces and GUIs. To handle this feature, we will de- velop Java interfaces to serve as interfaces between our two-player games and various user interfaces.

Designing the TwoPlayerGame Class

To begin revising the design of the OneRowNim game, we first need to design a top-level class, which we will call the TwoPlayerGame class. What variables and methods belong in this class? One way to answer this question is to generalize our current version of OneRowNim by mov- ing any variables and methods that apply to all two-player games up to the TwoPlayerGame class. All subclasses of TwoPlayerGame—which includes the OneRowNim class—would inherit these elements. Figure 8.18 shows the current design of OneRowNim.

What variables and methods should we move up to the TwoPlayer- Game class? Clearly, the class constants, PLAYER ONE and PLAYER TWO, apply to all two-player games. These should be moved up. On the other hand, the MAX PICKUP and MAX STICKS constants apply just to the OneRowNim game. They should remain in the OneRowNim class.

 

The nSticks instance variable is a variable that only applies to the OneRowNim game, but not to other two-player games. It should stay in the OneRowNim class. On the other hand, the onePlaysNext vari- able applies to all two-player games, so we will move it up to the TwoPlayerGame class.

Because constructors are not inherited, all of the constructor meth-

ods will remain in the OneRowNim class. The instance methods, Constructors are not inherited

takeSticks() and getSticks(), are particular to OneRowNim, so they should remain there. However, the other methods, getPlayer(), gameOver(), getWinner(), and reportGameState(), are methods that would be useful to all two-player games. Therefore these methods should be moved up to the superclass. Of course, while these methods can be defined in the superclass, some of the methods can only be imple- mented in subclasses. For example, the reportGameState() method reports the current state of the game, so it has to be implemented in OneRowNim. Similarly, the getWinner() method defines how the win- ner of the game is determined, a definition that can only occur in the sub- class. Every two-player game needs methods such as these. Therefore, we will define these methods as abstract methods in the superclass. The intention is that TwoPlayerGame subclasses will provide game-specific implementations for these methods.

Given these considerations, we come up with the design shown in Fig- ure 8.19. The design shown in this figure is much more complex than designs we have used in earlier chapters. However, the complexity comes from combining ideas already discussed in previous sections of this chap- ter, so don’t be put off by it.

To begin with, notice that we have introduced two Java interfaces into our design in addition to the TwoPlayerGame superclass. As we will show, these interfaces lead to a more flexible design and one that can eas- ily be extended to incorporate new two-player games. Let’s take each element of this design separately.

 

 

The TwoPlayerGame Superclass

 

As we have stated, the purpose of the TwoPlayerGame class is to serve as the superclass for all two-player games. Therefore, it should define those variables and methods that are shared by two-player games.

The PLAYER ONE, PLAYER TWO, and onePlaysNext variables and the getPlayer(), setPlayer(), and changePlayer() methods have been moved up from the OneRowNim class. Clearly, these variables and methods apply to all two-player games. Note that we have also added three new variables: nComputers, computer1, computer2 and their corresponding methods, getNComputers() and addComputerPlayer(). We will use these elements to give our games the ability to be played by computer programs. Because we want all of our two-player games to have this capability, we define these variables and methods in the superclass rather than in OneRowNim and subclasses of TwoPlayerGame.

 

Figure 8.19: TwoPlayerGame is the superclass for OneRowNim and other two player games.


 

 

Note that the computer1 and computer2 variables are declared to be of type IPlayer. IPlayer is an interface, which contains a single method declaration, the makeAMove() method:

,,

 

 

 

J

Why do we use an interface here rather than some type of game-playing object? This is a good design question. Using an interface here makes our design more flexible and extensible because it frees us from having to know the names of the classes that implement the makeAMove() method.

 

The variables computer1 and computer2 will be assigned objects that implement IPlayer via the addComputerPlayer() method.

The algorithms used in the various implementations of makeAMove() Game-dependent algorithms

are game-dependent—they depend on the particular game being played. It would be impossible to define a game-playing object that would suf- fice for all two-player games. Instead, if we want an object that plays OneRowNim, we would define a OneRowNimPlayer and have it imple- ment the IPlayer interface. Similarly, if we want an object that plays checkers, we would define a CheckersPlayer and have it implement the IPlayer interface. By using an interface here, our TwoPlayerGame

hierarchy can deal with a wide range of differently named objects that The IPlayer interface

play games, as long as they implement the IPlayer interface. So, using the IPlayer interface adds flexibility to our game hierarchy and makes it easier to extend it to new, yet undefined, classes. We will discuss the details of how to design a game player in one of the following sections.

Turning now to the methods defined in TwoPlayerGame, we have already seen implementations of getPlayer(), setPlayer(), and changePlayer() in the OneRowNim class. We will just move those im- plementations up to the superclass. The getNComputers() method is the accessor method for the nComputers variable, and its implementa- tion is routine. The addComputerPlayer() method adds a computer player to the game. Its implementation is as follows:

,,

 

 

 

 

 

 

J

As we noted earlier, the classes that play the various TwoPlayerGames must implement the IPlayer interface. The parameter for this method is of type IPlayer. The algorithm we use checks the current value of nComputers. If it is 0, which means that this is the first IPlayer added to the game, the player is assigned to computer2. This allows the hu- man user to be associated with PLAYERONE, if this is a game between a computer and a human user.

If nComputers equals 1, which means that we are adding a second IPlayer to the game, we assign that player to computer1. In ei- ther of these cases, we increment nComputers. Note what happens

if nComputers is neither 1 nor 2. In that case, we simply return without adding the IPlayer to the game and without incrementing nComputers. This, in effect, limits the number of IPlayers to two. (A more sophisticated design would throw an exception to report an error. but we will leave that for a subsequent chapter.)

The addComputerPlayer() method is used to initialize a game after it is first created. If this method is not called, the default assumption is

 

that nComputers equals zero and that computer1 and computer2 are both null. Here’s an example of how it could be used:

,,

 

 

 

 

 

 

 

 

Overriding a method


J

Note that the NimPlayer() constructor takes a reference to the game as its argument. Clearly, our design should not assume that the names of the IPlayer objects would be known to the TwoPlayerGame superclass. This method allows the objects to be passed in at run time. We will discuss the details of NimPlayerBad in a subsequent section.

The getRules() method is a new method whose purpose is to return a string that describes the rules of the particular game. This method is implemented in the TwoPlayerGame class with the intention that it will be overridden in the various subclasses. For example, its implementation in TwoPlayerGame is:

 

,,

 

 

J

and its redefinition in OneRowNim is:

,,

 

 

 

 

 

 

 

 

 

 

 

Polymorphism


J

The idea is that each TwoPlayerGame subclass will take responsibility for specifying its own set of rules in a form that can be displayed to the user. You might recognize that defining getRules() in the superclass and allowing it to be overridden in the subclasses is a form of polymorphism. It follows the design of the toString() method, which we discussed earlier. This design will allow us to use code that takes the following form:

,,

 

 

J

In this example the call to getRules() is polymorphic. The dynamic binding mechanism is used to invoke the getRules() method that is defined in the OneRowNim class.

The remaining methods in TwoPlayerGame are defined abstractly. The gameOver() and getWinner() methods are both methods that are

 

game dependent. That is, the details of their implementations depend on the particular TwoPlayerGame subclass in which they are implemented. This is good example of how abstract methods should be used in de- signing a class hierarchy. We give abstract definitions in the superclass and leave the detailed implementations up to the individual subclasses. This allows the different subclasses to tailor the implementations to their particular needs, while allowing all subclasses to share a common signa- ture for these tasks. This allows us to use polymorphism to create flexible,

extensible class hierarchies.

Figure 8.20 shows the complete implementation of the abstract TwoPlayerGame class. We have already discussed the most important details of its implementation.

 

The CLUIPlayableGame Interface

Let’s turn now to the two interfaces shown in Figure 8.19. Taken to- gether, the purpose of these interfaces is to create a connection between any two-player game and a command-line user interface (CLUI). The interfaces provide method signatures for the methods that will imple- ment the details of the interaction between a TwoPlayerGame and a UserInterface. Because the details of this interaction vary from game to game, it is best to leave the implementation of these methods to the games themselves.

Note that CLUIPlayableGame extends the IGame interface. The Extending an interface

IGame interface contains two methods that are used to define a stan- dard form of communication between the CLUI and the game. The getGamePrompt() method defines the prompt that is used to signal the user for some kind of move—for example, “How many sticks do you take (1, 2, or 3)?” And the reportGameState() method defines how that particular game will report its current state—for example, “There are 11 sticks remaining.” CLUIPlayableGame adds the play() method to these two methods. As we will see shortly, the play() method will contain the code that will control the playing of the game.

The source code for these interfaces is very simple:

,,

 

 

 

 

 

J

Notice that the CLUIPlayableGame interface extends the IGame inter- face. A CLUIPlayableGame is a game that can be played through a CLUI. The purpose of its play() method is to contain the game depen- dent control loop that determines how the game is played via some kind

 

,,

public a b s t r a c t c l a s s TwoPlayerGame

public s t a t i c f i n a l in t PLAYER ONE = 1 ;

public s t a t i c f i n a l in t PLAYER TWO = 2 ;

 

protected boolean onePlaysNext = t rue ;

protected in t nComputers = 0 ;// How many c o m p u t e r s

// C o m p u t e r s a r e I P l a y e r s

protected I Pla ye r computer1 , computer2 ;

 

public void s e t P l a ye r ( in t s t a r t e r )

i f ( s t a r t e r == PLAYER TWO) onePlaysNext = fa l s e ;

e ls e onePlaysNext = t rue ;

// s e t P l a y e r ( )

public in t get Player ( )

i f ( onePlaysNext )

return PLAYER ONE;

e ls e return PLAYER TWO;

// g e t P l a y e r ( )

public void change Player ( )

onePlaysNext = ! onePlaysNext ;

// c h a n g e P l a y e r ( )

public in t getNComputers ( )

return nComputers ;

}p ublic S t r i n g get Rules ( )

return ”The r ul e s of t h i s game are : ;

}p ublic void addComputerPlayer ( I Pla ye r player )

i f ( nComputers == 0 ) computer2 = player ;

e ls e i f ( nComputers == 1 ) computer1 = player ;

e ls e

return ;// No m o r e t h a n 2 p l a y e r s

++nComputers ;

} public a b s t r a c t boolean gameOver ( ) ; // A b s t r a c t M e t h o d s

public a b s t r a c t S t r i n g getWinner ( ) ;

// T w o P l a y e r G a m e

\J

Figure 8.20: The TwoPlayerGame class

 

of user interface (UI). In pseudocode, a typical control loop for a game would look something like the following:

,,

 

 

 

 

 

J

 

The play loop sets up an interaction between the game and the UI. The UserInterface parameter allows the game to connect directly to a par- ticular UI. To allow us to play our games through a variety of UIs, we define UserInterface as the following Java interface:

,,

 

 

 

J

Any object that implements these three methods can serve as a UI for one of our TwoPlayerGames. This is another example of the flexibility of using interfaces in object-oriented design.

To illustrate how we use UserInterface, let’s attach it to our KeyboardReader class, thereby letting a KeyboardReader serve as a CLUI for TwoPlayerGames. We do this simply by implementing this interface in the KeyboardReader class, as follows:

,,

 

J

As it turns out, the three methods listed in UserInterface match three of the methods in the current version of KeyboardReader. This is no accident. The design of UserInterface was arrived at by identifying the minimal number of methods in KeyboardReader that were needed to interact with a TwoPlayerGame.

 

The benefit of defining the parameter more generally as a User- Generality principle

Interface, instead of as a KeyboardReader, is that we will eventu- ally want to allow our games to be played via other kinds of command- line interfaces. For example, we might later define an Internet-based CLUI that could be used to play OneRowNim among users on the Inter- net. This kind of extensibility—the ability to create new kinds of UIs and use them with TwoPlayerGames— is another important design feature of Java interfaces.

 

As Figure 8.19 shows, OneRowNim implements the CLUIPlayable- Game interface, which means it must supply implementations of all three abstract methods: play(), getGamePrompt(), and reportGame- State().

 

 

 

 

 

 

 

Interfaces vs. abstract methods

 

 

 

 

 

 

 

 

 

Flexibility of interfaces

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Inheritance and generality


Object Oriented Design:Interfaces or Abstract Classes

Why are these methods defined in interfaces? Couldn’t we just as easily define them in the TwoPlayerGame class and use inheritance to extend them to the various game subclasses? After all, isn’t the net result the same, namely, that OneRowNim must implement all three methods.

These are very good design questions, exactly the kinds of questions

one should ask when designing a class hierarchy of any sort. As we pointed out in the Animal example earlier in the chapter, you can get the same functionality from a abstract interface and from an abstract super- class method. When should we put the abstract method in the superclass and when does it belong in an interface? A very good discussion of these and related object-oriented design issues is available in Java Design, 2nd Edition, by Peter Coad and Mark Mayfield (Yourdan Press, 1999). Our dis- cussion of these issues follows many of the guidelines suggested by Coad and Mayfield.

We have already seen that using Java interfaces increases the flexibility and extensibility of a design. Methods defined in an interface exist inde- pendently of a particular class hierarchy. By their very nature, interfaces can be attached to any class, which makes them very flexible to use.

Another useful guideline for answering this question is that the super- class should contain the basic common attributes and methods that define a certain type of object. It should not necessarily contain methods that define certain roles that the object plays. For example, the gameOver() and getWinner() methods are fundamental parts of the definition of a TwoPlayerGame. One cannot define a game without defining these methods. By contrast, methods such as play(), getGamePrompt(), and reportGameState() are important for playing the game but they do not contribute in the same way to the game’s definition. Thus these methods are best put into an interface. So, one important design guideline is:

 

JAVA EFFECTIVE DESIGN

Abstract Methods. Methods defined

abstractly in a superclass should contribute in a fundamental way toward the basic definition of that type of object, not merely toward one of its roles or its functionality.

 

The Revised OneRowNim Class

Figure 8.21 provides a listing of the revised OneRowNim class, one that fits into the TwoPlayerGame class hierarchy. Our discussion in this section will focus on just those features of the game that are new or revised.

The gameOver() and getWinner() methods, which are now inher- ited from the TwoPlayerGame superclass, are virtually the same as in the previous version. One small change is that getWinner() now returns a String instead of an int. This makes that method more generally useful as a way of identifying the winner for all TwoPlayerGames.

Similarly, the getGamePrompt() and reportGameState() meth-

ods merely encapsulate functionality that was present in the earlier ver- sion of the game. In our earlier version the prompts to the user were generated directly by the main program. By encapsulating this infor-

 

,,

public c l a s s OneRowNim extends TwoPlayerGame

implements CLUIPlayableGame

public s t a t i c f i n a l in t MAX PICKUP = 3 ; public s t a t i c f i n a l in t MAX STICKS = 1 1 ; private in t n St i c ks = MAX STICKS ;

 

public OneRowNim( )// C o n s t r u c t o r s

public OneRowNim( in t s t i c k s ) n St i c ks = s t i c k s ;

// One Row Nim ( )

public OneRowNim( in t s t i c k s , in t s t a r t e r ) n St i c ks = s t i c k s ;

s e t P l a ye r ( s t a r t e r ) ;

// One Row Nim ( )

public boolean t a k e S t i c k s ( in t num)

i f (num < 1num > MAX PICKUPnum > n S t i c k s )

return fa l s e ;// E r r o r

e ls e// V a l i d move

n St i c ks = n St i c ksnum;

return t rue ;

} // e l s e

// t a k e S t i c k s ( )

public in t g e t S t i c k s ( )

return n S t i c k s ;

// g e t S t i c k s ( )

public S t r i n g get Rules ( )

return nThe Rules of One Row Nimn” +

( 1 ) A number of s t i c k s between 7 and + MAX STICKS + i s chosen . \ n” +

( 2 ) Two players a l t e r n a t e making moves . \ n” +

( 3 ) A move c o n s i s t s of s ub t r a c t i n g between 1 and\n\ t +

MAX PICKUP + s t i c k s from the current number of s t i c k s . \ n” + ( 4 ) A player who cannot leave a p o s i t i v e \n\ t +

number of s t i c k s fo r the other player l o s e s . \ n” ;

} // g e t R u l e s ( )

public boolean gameOver ( )/ F r o m T w o P l a y e r G a m e /

return ( n St i c ks <= 0 ) ;

}// g a m e O v e r ( )

public S t r i n g getWinner ( ){/ F r o m T w o P l a y e r G a m e /

i f ( gameOver ( ) ) // {

return ”” + get Player ( ) + Nice game . ;

return ”The game i s not over yet . ;// Game i s n o t o v e r

// g e t W i n n e r ( )

\J

Figure 8.21: The revised OneRowNim class, Part I.

 

mation in an inherited method, we make it more generally useful to all

TwoPlayerGames.

The major change to OneRowNim comes in the play() method, which controls the playing of the OneRowNim (Fig. 8.22). Because this version of the game incorporates computer players, the play loop is a bit more complex than in earlier versions of the game. The basic idea is still the same: The method loops until the game is over. On each iteration of the

 

,,

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

J

Figure 8.22: The revised OneRowNim class, continued from previous page.

 

 

loop, one or the other of the two players, PLAYER ONE or PLAYER TWO, takes a turn making a move—that is, deciding how many sticks to pick up. If the move is a legal move, then it becomes the other player’s turn.

 

Let’s look now at how the code distinguishes between whether it is a computer’s turn to move or a human player’s turn. Note that at the beginning of the while loop, it sets the computer variable to null. It then assigns computer a value of either computer1 or computer2, de- pending on whose turn it is. But recall that one or both of these vari- ables may be null, depending on how many computers are playing the game. If there are no computers playing the game, then both variables will be null. If only one computer is playing, then computer1 will be null. This is determined during initialization of the game, when the addComputerPlayer() is called. (See above.)

In the code following the switch statement, if computer is not null, then we call computer.makeAMove(). As we know, the makeAMove() method is part of the IPlayer interface. The makeAMove() method takes a String parameter that is meant to serve as a prompt, and returns a String that is meant to represent the IPlayer’s move:

,,

 

 

 

 

In OneRowNim the “move” is an integer, representing the number of sticks the player picks. Therefore, in play() OneRowNim has to convert the String into an int, which represents the number of sticks the IPlayer picks up.

On the other hand, if computer is null, this means that it is a human user’s turn to play. In this case, play() calls ui.getUserInput(), em- ploying the user interface to input a value from the keyboard. The user’s input must also be converted from String to int. Once the value of sticks is set, either from the user or from the IPlayer, the play() method calls takeSticks(). If the move is legal, then it changes whose turn it is, and the loop repeats.

There are a couple of important points to notice about the design of the play() method. First, the play() method has to know what to do with the input it receives from the user or the IPlayer. This is game- dependent knowledge. The user is inputting the number of sticks to take in OneRowNim. For a tic-tac-toe game, the “move” might repre- sent a square on the tic-tac-toe board. This suggests that play() is a method that should be implemented in OneRowNim, as it is here, because OneRowNim encapsulates the knowledge of how to play the One Row Nim game.

A second point is to notice that the method call computer.make- AMove() is another example of polymorphism at work. The play() method does not know what type of object the computer is, other than that it is an IPlayer—that is, an object that implements the IPlayer interface. As we will show in the next section, the OneRowNim game can be played by two different IPlayers: one named NimPlayer and an- other named NimPlayerBad. Each has its own game-playing strategy, as implemented by their own versions of the makeAMove() method. Java uses dynamic binding to decide which version of makeAMove() to in- voke depending on the type of IPlayer whose turn it is. Thus, by defin- ing different IPlayers with different makeAMove() methods, this use of


J

 

 

 

 

 

 

 

 

 

Encapsulation of game-dependent knowledge

 

 

 

 

 

 

Polymorphism

 

polymorphism makes it possible to test different game-playing strategies against each other.

The IPlayer Interface

The last element of our design is the IPlayer interface, which, as we just saw, consists of the makeAMove() method. To see how we use this interface, let’s design a class to play the game of OneRowNim. We will call the class NimPlayerBad and give it a very weak playing strategy. For each move it will pick a random number between 1 and 3, or between 1 and the total number of sticks left, if there are fewer than 3 sticks. (We will leave the task of defining NimPlayer, a good player, as an exercise.)

As an implementer of the IPlayer interface, NimPlayerBad will implement the makeAMove() method. This method will contain NimPlayerBad’s strategy (algorithm) for playing the game. The result of this strategy will be the number of sticks that the player will pick up.

What other elements (variables and methods) will a NimPlayerBad

need? Clearly, in order to play OneRowNim, the player must know the

rules and the current state of the game. The best way to achieve this is to

give the Nim player a reference to the OneRowNim game. Then it can call

getSticks() to determine how many sticks are left, and it can use other

 

Figure 8.23:Design of the

NimPlayerBad class.


public elements of the OneRowNim game. Thus, we will have a variable of type OneRowNim, and we will assign it a value in a constructor method.

Figure 8.23 shows the design of NimPlayerBad. Note that we have added an implementation of the toString() method. This will be used to give a string representation of the NimPlayerBad. Also, note that we have added a private helper method named randomMove(), which will simply generate an appropriate random number of sticks as the player’s move.

 

 

,,

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Figure 8.24: The NimPlayerBad class.

 

The implementation of NimPlayerBad is shown in Figure 8.24. The makeAMove() method converts the randomMove() to a String and returns it, leaving it up to OneRowNim, the calling object, to convert that move back into an int. Recall the statement in OneRowNim where makeAMove() is invoked:

,,

 

J

In this context, the computer variable, which is of type IPlayer, is bound to a NimPlayerBad object. In order for this interaction between the game and a player to work, the OneRowNim object must know what type of data is being returned by NimPlayerBad. This is a perfect use for a Java interface, which specifies the signature of makeAMove() without committing to any particular implementation of the method. Thus, the association between OneRowNim and IPlayer provides a flexible and effective model for this type of interaction.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Finally, note the details of the randomMove() and toString() meth- ods. The only new thing here is the use of the getClass() method in toString(). This is a method that is defined in the Object class and inherited by all Java objects. It returns a String of the form “class X” where X is the name of that object’s class. Note here that we are removing the word “class” from this string before returning the class name. This allows our IPlayer objects to report what type of players they are, as in the following statement from OneRowNim:

,,

 

J

If computer1 is a NimPlayerBad, it would report “Player1 is a Nim- PlayerBad.”

 

SELF-STUDY EXERCISES

EXERCISE 8.13Define a class NimPlayer that plays the optimal strat- egy for OneRowNim. This strategy was described in Chapter 5.

Playing OneRowNim

Let’s now write a main() method to play OneRowNim:

,,

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Generality


J

After creating a KeyboardReader and then creating an instance of OneRowNim, we prompt the user to determine how many computers are playing. We then repeatedly prompt the user to identify the names of the IPlayer and use the addComputerPlayer() method to initialize the game. Finally, we get the game started by invoking the play() method, passing it a reference to the KeyboardReader, our UserInterface.

Note that in this example we have declared a OneRowNim variable to represent the game. This is not the only way to do things. For example, suppose we wanted to write a main() method that could be used to play a variety of different TwoPlayerGames. Can we make this code more general? That is, can we rewrite it to work with any TwoPlayerGame?

A OneRowNim object is also a TwoPlayerGame, by virtue of inheri- tance, and it is also a CLUIPlayableGame, by virtue of implementing that interface. Therefore, we can use either of these types to represent the game. Thus, one alternative way of coding this is as follows:

 

,,

 

 

 

J

Here we use a TwoPlayerGame variable to represent the game. However, note that we now have to use a cast expression, (CLUIPlayableGame),

 

in order to call the play() method. If we don’t cast game in this way, Java will generate the following syntax error:

,,

 

 

 

J

The reason for this error is that play() is not a method in the TwoPlayerGame class, so the compiler cannot find the play() method. By using the cast expression, we are telling the compiler to consider game to be a CLUIPlayableGame. That way it will find the play() method. Of course, the object assigned to nim must actually implement the CLUIPlayableGame interface in order for this to work at run time. We also need a cast operation in the NimPlayer() constructor in or- der to make the argument (computer) compatible with that method’s parameter.

Another alternative for the main() method would be the following:

,,

 

 

 

 

 

J

By representing the game as a CLUIPlayableGame variable, we don’t need the cast expression to call play(), but we do need a different cast expression, (TwoPlayerGame), to invoke addComputerPlayer(). Again, the reason is that the compiler cannot find the addComputer- Player() method in the CLUIPlayableGame interface, so we must tell it to consider game as a TwoPlayerGame, which of course it is. We still need the cast operation for the call to the NimPlayer() constructor.

All three of the code options that we have considered will generate

something like the interactive session shown in Figure 8.25 for a game in which two IPlayers play each other.

Given our object-oriented design for the TwoPlayerGame hierarchy, we can now write generalized code that can play any TwoPlayerGame that implements the CLUIPlayableGame interface. We will give a spe- cific example of this in the next section.

Extending the TwoPlayerGame Hierarchy

Now that we have described the design and the details of the TwoPlayerGame class hierarchy, let’s use it to develop a new game. If we’ve gotten the design right, developing new two-player games and adding them to the hierarchy should be much simpler than developing them from scratch.

The new game is a guessing game in which the two players take turns guessing a secret word. The secret word will be generated randomly from

 

,,

 

 

 

 

 

 

 

 

.

 

 

 

 

 

 

J

Figure 8.25: A typical run of the OneRowNim using a command-line user interface.

 

a collection of words maintained by the game object. The letters of the word will be hidden with question marks, as in “????????.” On each turn a player guesses a letter. If the letter is in the secret word, it replaces one or more question marks, as in “??????E?.” A player continues to guess until an incorrect guess is made and then it becomes the other player’s turn. Of course, we want to develop a version of this game that can be played either by two humans, or by one human against a computer—that is, against an IPlayer—or by two different IPlayers.

Let’s call the game class WordGuess. Following the design of OneRowNim, we get the design shown in Figure 8.26. The WordGuess class extends the TwoPlayerGame class and implements the CLUIPlayableGame interface. We don’t show the details of the inter- faces and the TwoPlayerGame class, as these have not changed. Also, following the design of NimPlayerBad, the WordGuesser class imple- ments the IPlayer interface. Note how we show the association between WordGuess and zero or more IPlayers. A WordGuess uses between zero and two instances of IPlayers, which in this game are implemented as WordGuessers.

Let’s turn now to the details of the WordGuess class, whose source

code is shown in Figures 8.27 and 8.28. The game needs to have a supply of words from which it can choose a secret word to present to the players. The getSecretWord() method will take care of this task. It calculates a random number and then uses that number, together with a switch statement, to select from among several words that are coded right into the switch statement. The secret word is stored in the secretWord vari- able. The currentWord variable stores the partially guessed word. Ini- tially, currentWord consists entirely of question marks. As the players

 

Figure 8.26: Design of the WordGuess class as part of TwoPlayerGame hierarchy.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

make correct guesses, currentWord is updated to show the locations of the guessed letters. Because currentWord will change as the game pro- gresses, it is stored in a StringBuffer, rather than in a String. Recall that Strings are immutable in Java, whereas a StringBuffer contains methods to insert letters and remove letters.

The unguessedLetters variable stores the number of letters remain- ing to be guessed. When unguessedLetters equals 0, the game is over. This condition defines the gameOver() method, which is inherited from TwoPlayerGame. The winner of the game is the player who guessed the last letter in the secret word. This condition defines the getWinner() method, which is also inherited from TwoPlayerGame. The other meth- ods that are inherited from TwoPlayerGame or implemented from the CLUIPlayableGame are also implemented in a straightforward manner. A move in the WordGuess game consists of trying to guess a let- ter that occurs in the secret word. The move() method processes the player’s guesses. It passes the guessed letter to the guessLetter() method, which checks whether the letter is a new, secret letter. If so, guessLetter() takes care of the various housekeeping tasks. It adds the letter to previousGuesses, which keeps track of all the players’ guesses. It decrements the number of unguessedLetters, which will become 0 when all the letters have been guessed. And it updates currentWord to show where all occurrences of the secret letter are located. Note how

 

,,

public c l a s s WordGuess extends TwoPlayerGame implements CLUIPlayableGame

private S t r i n g secretWord ;

private S t r i n g B u f fe r currentWord ;

private S t r i n g B u f fe r previous Guesses ;

private in t unguessed Letters ;

 

public WordGuess ( )

secretWord = get Secret Word ( ) ;

currentWord = new S t r i n g B u f fe r ( secretWord ) ; previous Guesses = new S t r i n g B u f fe r ( ) ;

for ( in t k = 0 ; k < secretWord . length ( ) ; k++) currentWord . set Char At ( k , ? ) ;

unguessed Letters = secretWord . length ( ) ;

// WordGuess ( )

public S t r i n g get Previous Guesses ( )

return previous Guesses . t o S t r i n g ( ) ;

// get Previous Guesses ( )

public S t r i n g getCurrentWord ( )

return currentWord . t o S t r i n g ( ) ;

// getCurrentWord ( )

private S t r i n g get Secret Word ( )

in t num = ( in t ) ( Math . random ( ) 1 0 ) ;

switch (num)

case 0 : return ”SOFTWARE” ; case 1 : return ”SOLUTION” ; case 2 : return ”CONSTANT” ; case 3 : return ”COMPILER” ; case 4 : return ”ABSTRACT” ; case 5 : return ”ABNORMAL” ; case 6 : return ”ARGUMENT” ; case 7 : return ”QUESTION” ; case 8 : return ”UTILIZES” ; case 9 : return ”VARIABLE” ; default : return ”MISTAKES” ;

//switch

// get Secret Word ( )

private boolean gue ss Le t t er ( char l e t t e r ) previous Guesses . append ( l e t t e r ) ;

i f ( secretWord . indexOf ( l e t t e r ) ==1)

return fa l s e ; // l e t t e r i s not in secretWord

e ls e // f ind p o s i t i o n s of l e t t e r in secretWord

for ( in t k = 0 ; k < secretWord . length ( ) ; k++)

i f ( secretWord . charAt ( k ) == l e t t e r )

i f ( currentWord . charAt ( k ) == l e t t e r )

return fa l s e ; //// already guessed currentWord . set Char At ( k , l e t t e r ) ;

unguessed Letters; //one l e s s to f ind

// i f

// fo r

return t rue ;

} // e l s e

} // gues s Le t te r ( )

public S t r i n g get Rules ( ) {// Overridden from TwoPlayerGame

return \n∗∗∗ The Rules of Word Guess ∗∗∗\n” + ” ( 1 ) The game generates a s e c r e t word.\ n” +

( 2 ) Two players a l t e r n a t e taking moves .\ n” +

( 3 ) A move c o n s i s t s of guessing a l e t t e r in the word.\ n” +

( 4 ) A player continues guessing u n t i l a l e t t e r i s wrong.\ n” +

” ( 5 ) The game i s over when a l l l e t t e r s of the word are guessed\n” + ” ( 6 ) The player guessing the l a s t l e t t e r of the word wins .\ n” ;

\} // get Rules ( )J

Figure 8.27: The WordGuess class, Part I.

 

 

guessLetter() uses a for-loop to cycle through the letters in the secret word. As it does so, it replaces the question marks in currentWord with the correctly guessed secret letter. The guessLetter() method returns false if the guess is incorrect. In that case, the move() method changes the

 

,,

public boolean gameOver ( )// From TwoPlayerGame

return ( unguessed Letters <= 0 ) ;

// gameOver ( )

public S t r i n g getWinner ( )// From TwoPlayerGame

i f ( gameOver ( ) )

return Player + get Player ( ) ;

e ls e return ”The game i s not over . ;

// getWinner ( )

public S t r i n g report Game State ( )

i f ( ! gameOver ( ) )

return \nCurrent word + currentWord . t o S t r i n g ( ) + Previous guesses

 

 

e ls e


+ previous Guesses + \ n Player + get Player ( ) + guesses next . ;

return \nThe game i s now over ! The s e c r e t word i s + secretWord

+ \n” + getWinner ( ) + has won!\ n” ;

 

// report Game State ( )

public S t r i n g getGamePrompt ( )// From CLUIPlayableGame

return nGuess a l e t t e r t h a t you think i s in the s e c r e t word : ;

// getGamePrompt ( )

public S t r i n g move( S t r i n g s )

char l e t t e r = s . toUpperCase ( ) . charAt ( 0 ) ;

i f ( gue s s Le t t e r ( l e t t e r ) )// i f c o r r e c t

return ”Yes , the l e t t e r + l e t t e r + IS in the s e c r e t word\n” ;

e ls e

change Player ( ) ;

return Sorry , + l e t t e r + i s NOT a + ”new l e t t e r in the s e c r e t word\n” ;

// m} ove ( )

public void play ( Us e r I n t e r fa c e ui )// From CLUIPlayableGame ui . report ( get Rules ( ) ) ;

i f ( computer1 ! = null )

ui . report ( n Player 1 i s a + computer1 . t o S t r i n g ( ) ) ;

i f ( computer2 ! = null )

ui . report ( \ n Player 2 i s a + computer2 . t o S t r i n g ( ) ) ;

while ( ! gameOver ( ) )

I Pla ye r computer = null ;// Assume no computers playing ui . report ( report Game State ( ) ) ;

switch ( get Player ( ) )

case PLAYER ONE:// Player 1 ’ s turn computer = computer1 ;

break ;

case PLAYER TWO:// Player 2 ’ s turn computer = computer2 ;

break ;

} // cases

i f ( computer ! = null )// I f computer ’ s turn ui . report ( move( computer . makeAMove( ”” ) ) ) ;

e ls e// otherwise , user s turn ui . prompt ( getGamePrompt ( ) ) ;

ui . report ( move( ui . get User Input ( ) ) ) ;

//} while

ui . report ( report Game State ( ) ) ; // The game i s now over

} //play ( )

\} //WordGuess c l a s s J

Figure 8.28: The WordGuess class, continued.

 

 

player’s turn. When correct guesses are made, the current player keeps the turn.

The WordGuess game is a good example of a string-processing prob- Reusing code

lem. It makes use of several of the String and StringBuffer meth- ods that we learned in Chapter 7. The implementation of WordGuess, as an extension of TwoPlayerGame, is quite straight forward. One advan-

 

,,

 

 

 

 

 

 

 

 

 

 

 

 

 

J

Figure 8.29: The WordGuesser class.

 

tage of the TwoPlayerGame class hierarchy is that it decides many of the important design issues in advance. Developing a new game is largely a matter of implementing methods whose definitions have already been determined in the superclass or in the interfaces. This greatly simplifies the development process.

Let’s now discuss the details of WordGuesser class (Fig. 8.29). Note that the constructor takes a WordGuess parameter. This allows WordGuesser to be passed a reference to the game, which accesses the game’s public methods, such as getPreviousGuesses(). The toString() method is identical to the toString() method in the NimPlayerBad example. The makeAMove() method, which is part of the IPlayer interface, is responsible for specifying the algorithm that the player uses to make a move. The strategy in this case is to repeatedly pick a random letter from A to Z until a letter is found that is not contained in previousGuesses. That way, the player will not guess letters that have already been guessed.