Computer Science 101 Lab 4: Loops, Craps, and the Game of Nim
Due: February 18, 2002

Objectives and Overview: The purpose of this lab is to gain more experience with loops and their use in problem solving. The lab has two parts. The first is a series of questions related to the program 'craps.java' which was developed in class.  The second is a programming problem that monitors a user's actions while playing the game of Nim.

Part 1. Exercising the Craps Program

The following program solves the Game of Craps problem that was handed out in class.  To Exercise this program, drag a copy of the folder MyProject from the CS105 server to the desktop and then drag the file craps.java into that folder on the desktop.

import cs1.Keyboard;
public class craps {
// Program to simulate playing several games of craps with the user
// Authors: CS105 class              Date: February 12, 2002

  public static void main(String[] args) {
  // variable declarations
     int die1, die2, roll, firstroll;
                     // Each die is a random integer from 1-6; each of

                     // 'roll' and 'firstroll' is the sum of two dice.
     char game = 'y';             // User decides when to quit playing
     System.out.println("Welcome to craps!");
     // Each time through the loop, play one game and display the result
     while (game == 'y') {
        // compute first roll
        die1 = (int)(Math.random()*6 + 1);
        die2 = (int)(Math.random()*6 + 1);
        firstroll = die1 + die2;

        // check for immediate win or loss (and display result)
        if (firstroll == 7 || firstroll == 11)
           System.out.println("You rolled " + firstroll + " and won!");
        else if (firstroll == 2 || firstroll == 3 || firstroll == 12)
           System.out.println("You rolled " + firstroll + " and lost!");
        else {
        // if not, continue rolling (and display intermediate rolls)
           System.out.print("You rolled " + firstroll);
           die1 = (int)(Math.random()*6 + 1);
           die2 = (int)(Math.random()*6 + 1);
           roll = die1 + die2;        
           while (roll != firstroll && roll != 7) {
              System.out.print(", " + roll);
              die1 = (int)(Math.random()*6 + 1);
              die2 = (int)(Math.random()*6 + 1);
              roll = die1 + die2;          
           } // end of while loop
           System.out.print(", " + roll);
           if (roll == firstroll)
              System.out.println(" and made your point!");
           else
              System.out.println(" and crapped out!");
        }
        System.out.println("Want to play again? (y/n)");
        game = Keyboard.readChar();
     } // end of while loop
  }
}

Below is the result of a sample run of this program in which the user wants to play exactly 10 games.  Hmmm... two wins and 8 losses... looks like a very bad day at the tables!


 

Part 1 Questions

  1. Run the program once yourself, playing 5 games.  Do you get the same results as above?  Explain.
  2. How would you change the program so that it keeps track of the user's total number of wins and losses, and then reports that number at the end of the run?  For the above example, the program should display the message at the end:

  3. You won 3 games and lost 2.

  4. How would you alter the program so that it learns the user's name at the outset, and then addresses the user by name at the end of each game?  For example, the following message and response would precede the first line above:

  5. Welcome to craps! Please enter your name:
    Allen

    And at the beginning of each new game, the user would be addressed by name, as in:

    Want to play again, Allen?

Part 2. Game of Nim

The other game described on the handout is the ancient game of Nim.  Programming the game of Nim is similar to Craps, except that there are two players (the computer and the user) rather than one.  At each play, the user is prompted to pick up 1, 2, or 3 coins (but no more than the number remaining), and then the computer picks up a random number (1, 2, or 3) coins.  

The structure of your solution should contain a general loop which repeats once for every game played and a nested loop that controls a series of plays in a single game.  Read the problem description for the Game of Nim that appears in the handout before continuing.

Step 1 - Design a Program to Monitor the Game

Before writing this program, it is useful to sit down and determine its overall design by answering for yourself the following questions:

  1. What are the key variables in your program, and what are their uses?
  2. What kind of loop is required to control the playing of a series of games, and how will it terminate?
  3. For a single game of Nim, two moves are needed - one for the user and one for the computer.  The computer's move is dictated by a random number generated in the range 1 - 3.  Both moves must be subtracted from the total number of coins that remain before the game continues.
  4. What kind of loop is required to control the playing of a series of moves within a single game?  When will it terminate?  How will the program determine who wins when this loop terminates?
Use meaningful names for the variables you declare. Your program should provide clear and concise output on the screen, both in the form of prompts for user input and displaying results. The program should also be well-documented with explanatory comments.

A typical dialog between the program and the user should look like this:  

Welcome to Nim; What is your name?
Allen
20 coins left.  How many do you want to remove? 3
You removed 3.  I removed 1.
16 coins left.  How many do you want to remove? 2
You removed 2.  I removed 2.
12 coins left.  How many do you want to remove? 1
You removed 1.  I removed 2.
9 coins left.  How many do you want to remove? 3
You removed 3.  I removed 2.
4 coins left.  How many do you want to remove? 1
You removed 1.  I removed 3.
I lost!
Want to play again, Allen?
n
You won 1 games and lost 0, Allen.
Thank you for playing Nim.


Step 2 - Type and Run the Program

When you type your program, it should be saved with a file name that identifies you uniquely, such as lab4atucker.java . Be sure to add this program to your project (in place of the craps.java program) before you run it.

Step 3 - Debugging

As you test the program, try using the Debug option to single-step through it and observe the values of the variables as they change.  Also, observe how control changes from one method to another as you enter and return from each call.

Step 4 (Optional) - A Perfect Strategy?

Rather than use a random number to govern the computer's next move, is there a better strategy that can be used to guarantee that the computer never loses?  If so, how would you alter the program so the computer never loses?

Lab 4 Deliverables

By 5:00pm on the due date, a copy of your completed program from Part 2 should be dragged to the Drop Box in the CS105 (Tucker) folder. A printed copy of your program, along with your written answers to the questions in Part 1, should be turned in with your name at the top.

If you need extra help with this problem, I'll be here during weekdays, and remember that Dave Harden will be in the lab on Sunday nights from 9-11.