Skip to main content
Logo image

Java, Java, Java: Object-Oriented Problem Solving, 2024E

Section 5.4 Using Booleans in OneRowNim

Now that we have introduced the boolean data type, let’s use it to improve the OneRowNim class, the latest version of which, from Chapter 3, is given in Listing 3.7.1. Previously we used an int variable, player, to represent who’s turn it is. For a two-person game, such as One Row Nim, a boolean variable is well suited for this purpose, because it can toggle between true and false. For example, let’s declare a variable, onePlaysNext, and initialize it to true, to represent the fact that player one will play first:
private boolean onePlaysNext = true;
When onePlaysNext is true, it will be player one’s turn. When it is false, it will be player two’s turn. Note that we are deliberately remaining uncommitted as to whether one or the other player is the computer.
Given this new variable, it is necessary to redefine the methods that had previously used the player variable. The first method that needs revision is the constructor:
public OneRowNim(int sticks, int starter)
{   nSticks = sticks;
    onePlaysNext = (starter == 1);
}  // OneRowNim() constructor3
In the constructor, the starter parameter is used with a value of 1 or 2 to set which player goes first. Note how we use an assignment statement to set onePlaysNext to true if starter equals 1; otherwise it is set to false. The assignment statement first evaluates the expression on its right hand side (starter == 1). Because this is a boolean expression, it will have a value of true or false, which will be assigned to onePlaysNext. Thus, the assignment statement is equivalent to the following if/else statement:
if (player == 1)
   onePlaysNext = true;
else
   onePlaysNext = false;
The remaining changes are shown in Listing 5.4.1. There are only two instance methods that need revision to accommodate the use of boolean variables. The takeSticks() method contains two revisions. The first uses the boolean OR operator to test whether a move is valid:
public boolean takeSticks(int num)
{   if (num < 1 || num > 3 || num > nSticks)
        return false;                // Error
    else                             // Valid move
    {   nSticks = nSticks - num;
        onePlaysNext = !onePlaysNext;
        return true;
    } //else
} // takeSticks()
It also uses the boolean NOT operator to toggle the value of onePlaysNext, to switch to the other player’s turn:
onePlaysNext = !onePlaysNext;
Finally, the getPlayer() method now uses a if/else statement to return either 1 or 2 depending on who’s turn it is:
public int getPlayer()
{   if (onePlaysNext)
        return 1;
    else return 2;
} // getPlayer()
The full listing of the revised OneRowNim is given in Listing 5.4.1. Run to see this code in action.
Listing 5.4.1. The revised OneRowNim uses a boolean variable to keep track of who’s turn it is.
You have attempted of activities on this page.