Java Code for Playing Craps

 

You may all think that you have some real expertise in playing craps considering that you've been in school for at least 15 years.  We are going to make this notion more precise and relate it to a particular dice game that you might find at a casino.  We will create this game as an applet.  First we will describe the rules of the game, then present the code.

Rules of the Game.  A player rolls two dice where each die has six faces in the usual way.  After the dice have come to rest the sum of the two upward faces is calculated.

 

The first roll

  1. If the sum is 7 or 11 on the first throw the roller/player wins.
  2. If the sum is 2, 3 or 12 the roller/player loses, that is the house wins.
  3. If the sum is 4, 5, 6, 8, 9, or 10, that sum becomes the roller/player's "point".

Continue given the player's point

  1. Now the player must roll the "point" total before rolling a 7 in order to win.  If they roll a 7 before rolling the point value they got on the first roll the roller/player loses.

This game can get even more complicated when you play it at a "casino" because the player and everyone else can bet on whether the player or house wins.

The Code.  Now we present the code for a GUI to play the game.  I have modified the code from an example out of Deitel and Deitel.  You should call the applet Craps.java.

You should first implements the code and play the game some before we discuss the code.

 

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Craps extends JApplet implements ActionListener
{

// constant variables for the status of the game
final int WON = 0, LOST = 1, CONTINUE = 2;

// other variables used in the program
boolean firstRoll = true;
int sumOfDice = 0;
int myPoint = 0;
int gameStatus = CONTINUE;
int numberHouseWins = 0;
int numberPlayerWins = 0;
String divider = "* * * * * * * *";

// graphical user interface components
JLabel die1Label, die2Label, sumLabel, rollLabel, pointLabel;
JLabel lblHouseWins, lblPlayerWins;
JLabel leftDivider, rightDivider;
JTextField firstDie, secondDie, sum, point;
JTextField txtHouseWins, txtPlayerWins;
JButton roll;

public void init( )
{

// setup graphical user interface components
JPanel display = new JPanel();
display.setLayout( new GridLayout(8,2,10,10) );

die1Label = new JLabel( "Die 1: ", SwingConstants.RIGHT);
display.add(die1Label);
firstDie = new JTextField(3);
firstDie.setEditable(false);
display.add(firstDie);

die2Label = new JLabel( "Die 2: ", SwingConstants.RIGHT );
display.add(die2Label);
secondDie = new JTextField(3);
secondDie.setEditable(false);
display.add(secondDie);

sumLabel = new JLabel( "Their sum is: ", SwingConstants.RIGHT );
display.add(sumLabel);
sum = new JTextField(4);
sum.setEditable(false);
display.add(sum);

rollLabel = new JLabel( "Roll Again: ", SwingConstants.RIGHT );
display.add(rollLabel);
roll = new JButton("Roll Dice");
roll.addActionListener( this );
display.add(roll);

pointLabel = new JLabel( "Point is: ", SwingConstants.RIGHT );
display.add(pointLabel);
point = new JTextField(3);
point.setEditable(false);
display.add(point);

leftDivider = new JLabel( divider, SwingConstants.RIGHT );
display.add(leftDivider);
rightDivider = new JLabel( divider, SwingConstants.LEFT );
display.add(rightDivider);

lblPlayerWins = new JLabel( "Player wins: ", SwingConstants.RIGHT );
display.add(lblPlayerWins);
txtPlayerWins = new JTextField(4);
txtPlayerWins.setEditable(false);
display.add(txtPlayerWins);

lblHouseWins = new JLabel( "House wins: ", SwingConstants.RIGHT );
display.add(lblHouseWins);
txtHouseWins = new JTextField(4);
txtHouseWins.setEditable(false);
display.add(txtHouseWins);

setContentPane(display);

//  end method init( )

// call method play when button is pressed
public void actionPerformed(ActionEvent e)
{

play( );

}


public void play( )
{

// process one roll of the dice
if (firstRoll)
{

sumOfDice = rollDice( );

switch (sumOfDice)
{

//  player wins on first roll
case 7: case 11:

gameStatus = WON;
point.setText("");
break;

//  house wins - player loses on first roll
case 2: case 3: case 12:

gameStatus = LOST;
point.setText("");
break;

//  neither wins and point is set
//  for game to continue

default:

gameStatus = CONTINUE;
myPoint = sumOfDice;
point.setText(Integer.toString(myPoint));
firstRoll = false;
break;

}

}
//  if not the firstRoll then need to
//  process continuation and/or
//  completion possibilities

else
{

sumOfDice = rollDice( );

//  when gameStatus == continue
//  need to test whether new roll
//  results in win for player
//  win for house - loss for player
//  or coninuation with current point

if (sumOfDice == myPoint)

gameStatus = WON;

else

if (sumOfDice == 7)

gameStatus = LOST;

}

//  checking to see whether game is a continuation
//  or has been completed and requires adjustments

if (gameStatus == CONTINUE)

showStatus("Roll Again");

else
{

//  section of code to deal with the end of a game
//  where gameStatus is no longer continue
//  where wither the player or house has won

if (gameStatus == WON)
{

showStatus("Player wins. " + "Click Roll Dice to play again");
numberPlayerWins++;
txtPlayerWins.setText(Integer.toString(numberPlayerWins));

}
else
{

showStatus("House wins. " + "Click Roll Dice to play again.");
numberHouseWins++;
txtHouseWins.setText(Integer.toString(numberHouseWins));

}

firstRoll = true;

}

}

// roll the dice
public int rollDice( )
{

int die1, die2, workSum;

die1 = 1 + (int) (Math.random( ) * 6);
die2 = 1 + (int) (Math.random( ) * 6);
workSum = die1 + die2;

firstDie.setText(Integer.toString(die1));
secondDie.setText(Integer.toString(die2));
sum.setText(Integer.toString(workSum));

return workSum;

}

//  end class Craps

 

Now it helps to have the Craps.html file since the size of the window impacts the display.

 

<html>
<APPLET CODE = "Craps.class" WIDTH = 230 HEIGHT = 300>
</APPLET>
</html>

 

When you run the program you should see something like the following after you have played a few games.

 

 

Or you can run the game through a recent browser at the following link.

http://cisdev.quinnipiac.edu/fox/javaApplets/basicCraps/Craps.html

Now we will discuss the code, which really is quite elaborate.

  • The first section of code imports the usual appropriate packages and classes
    • java.awt.*
    • java.awt.event.*
    • javax.swing.*
  • the overall inclusive class Craps
    • extends JApplet from swing
    • implements ActionListener from java.awt.event
  • a variable is defined for the status of the game
  • other variables associated with certain aspects of the game are declared and initialized
    • whether or not this is a firstRoll in a game
    • what is the sumOfDice
    • what is myPoint that the plyer hopes to match before rolling a seven
    • the gameStatus in terms of the player has WON, LOST or it CONTINUEs
    • numberHouseWins to increment and display each time the house wins
    • numberPlayerWins to increment and display each time the player wins
    • a sting to help partition the GUI
  • a bunch of GUI components
    • JLabels for leeting the program user know the meaning of other entries
      • die1Label
      • die2Label
      • sumLabel
      • rollLabel
      • pointLabel
      • lblHouseWins
      • lblPlayerWins
      • leftDivider
      • rightDivider
    • JTextFields for reporting the results of different aspects of the game
      • firstDie value
      • secondDie value
      • sum
      • point
      • txtHouseWins to display numberHouseWins
      • txtPlayerWins to display numberPlayerWins
    • a JButton roll to cause the dice to be rolled
  • the method init( ) is used to develop the GUI and add the components to the GridLayout with 8 rows and 2 columns
    • this code should be pretty self explanatory by now
  • the actionPerformed( ) method that responds to the user clicking on the roll button by invoking the play( ) method
  • the play( ) method which contains the rules of the game in code
    • first need to distinguish between if it is the firstRoll
      • roll the dice using rollDice( ) so results are returned and displayed
      • run a switch on the outcome
        • case: player wins on a sum of 7 or 11
          • adjust gameStatus to WON
          • blank text field displaying the point
        • case: house wins on a sum of 2, 3 12
          • adjust gameStatus to LOST
          • blank text field displaying the point
        • case: neither wins on remaining outcomes of roll
          • adjust gameStatus to CONTINUE
          • set myPoint to sumOfDice
          • display myPoint in point text field
          • change status of dirstRoll boolean variable to false
    • else not the firstRoll
      • roll the dice using rollDice( ) so results are returned and displayed
      • test whether someone wins or game continues based on whether the roll matches myPoint
      • if sumOfDice == myPoint
        • set gameStatus to WON for player wins
      • else if sumOfDice == 7
        • set gameStatus to LOST for player loses
    • if gameStatus == continue
      • tell player to roll again through message in the status bar
    • else someone has won
      • if player has won so gameStatus == WON
        • show result in status bar
        • increment the number of player wins
        • setText to display the number of player wins
      • else house has won
        • show result in status bar
        • increment the number of house wins
        • setText to display the number of house wins
      • in either case need to set firstRoll back to true to start a new game

 

  • the method to rollDice( )
  • declare variables to contain result of roll on each die and their sum
  • generate the random roll on the first die using
    • 1 + (int) (Math.random( ) * 6)
  • generate the random roll on the second die using
    • 1 + (int) (Math.random( ) * 6)
  • find workSum the sum of the two dies
  • display all of these in the appropriate text field
    • notice how the integers must be formed into strings using the toString( ) method of the Integer class
  • return workSum, the sum of the dice

Finally, did you here about the woman who was home crying because her husband was out shooting craps and she didn't know how to cook it?