Link to home
Start Free TrialLog in
Avatar of phillyman2010
phillyman2010

asked on

Pig (Java Game)

Hi everyone. I am a grad student in an accelerated Java class and so it is understandably a bit difficult for me. I have never used Java in my life. I am using a custom textbook from my school that has all of the examples in the book as source code on a CD. Unfortunately I purchased a used book without a CD so I am stuck and I cannot complete my program. The problems are outlined below:

Part 1:

    * Write a Java class called Die (as in the singular of Dice) that represents one die with faces showing values between 1 and 6. It should contain :

      --one integer  instance variable, faceValue, that represents the current face value of the die, an integer constant (MAX) that represents the maximum face value of the die.

      --a constructor

      --and five regular methods: roll, setFaceValue, getFaceValue, toString and equals.

       
    * The roll method should compute a random integer between 1 and 6 and set the current face value with that as a way of simulating the rolling of the die. (What Java class and method would you use to get a random integer ?? find out..)
    * Now, write a driver (i.e., program used for testing) called RollingDice, in order to test your Die class.

Part 2:

    * Using the Die class, design and implement a class called PairOfDice, composed of two Die objects. Include methods to set and get the individual die values, toString and equals methods, a method to roll the dice (call it roll), and a method that returns the current sum of the two die values (call it getDiceSum).

 Part: 3

Properly using your PairOfDice class, write a Java program (a driver with a main function), called DiceGame.java, that allows the user to play the a game with the computer. Here are the rules of the game:  A player rolls the dice repeatedly until she rolls at least one 1 or voluntarily gives up the dice. Each time she rolls the dice the total on the faces of the dice is added to her score, except when she rolls a 1. If she rolls one 1, she loses all the points she's accumulated so far in her turn. If she rolls two 1's, she loses all of her points so far in the game. (This means you have to keep track of points in each turn and points since the beginning of the game). The first player to get a total of 100 wins. The computer follows the same rules, except that it turns over the dice as soon as its score for the current turn is at least 20.

Here's an excerpt from a working program.

    Welcome to the DiceGame.  It's you against the computer.
    You play by rolling the dice.  The first player
    to get 100 points wins.  However, if you roll one 1
    you lose all the points you've accumulated in your
    turn.  If you roll two 1's, you lose all your
    points.  You can turn the dice over at any time.
    However, if you roll one or two 1's, you lose your
    turn.  I (the computer) play by the same rules,
    except I'll always turn over the dice when I've
    rolled 20 or more points in a single turn.
    Ready to begin? (Type 'y' when you're ready)
    y
   
    You're rolling the dice . . .
    You rolled 2 4
    This gives you a turn total of
        6
    and a grand total of
        6
    The computer has a total of
        0
    Do you want to continue rolling?  (Type 'y' or 'n')
    y
   
    You're rolling the dice . . .
    You rolled 3 3
    This gives you a turn total of
        12
    and a grand total of
        12
    The computer has a total of
        0
    Do you want to continue rolling?  (Type 'y' or 'n')
    y
   
    You're rolling the dice . . .
    You rolled 1 3
    You got a 1!
    Continue? (Type 'y' when you're ready to
    turn the dice over to me)
    y
    The score is
        You:       0
        Computer:  0
   
    I'm rolling the dice . . .
    I rolled 1 4
    I got a 1!
    Continue? (Type 'y' when you're ready)
    y
    The score is
        You:       0
        Computer:  0
   
    You're rolling the dice . . .
    You rolled 5 5
    This gives you a turn total of
        10
    and a grand total of
        10
    The computer has a total of
        0
    Do you want to continue rolling?  (Type 'y' or 'n')
    n
   
    I'm rolling the dice . . .
    I rolled 1 1
    I got two 1's!
    Continue? (Type 'y' when you're ready)
    y
    The score is
        You:       10
        Computer:  0
   
    [Many turns deleted . . .]
   
    You're rolling the dice . . .
    You rolled 1 6
    You got a 1!
    Continue? (Type 'y' when you're ready to
    turn the dice over to me)
    y
    The score is
        You:       0
        Computer:  93
   
    I'm rolling the dice . . .
    I rolled 5 4
    This gives me a turn total of
        9
    and a grand total of
        102
    The score is
        You:       0
        Computer:  102
   
    Better luck next time!


Apparently this is a modified Java game called Pig. I am asking because this seems to be a very popular program so I thought source code would be readily available. I have already done parts 1 and 2 but I have no idea how Part 3 would look like so I was wondering if anyone could help me out. Thank you in advance. Btw this my first time asking/commenting, etc so please let me know if I need to explain or format anything better. Cheers.
ASKER CERTIFIED SOLUTION
Avatar of Kyle Abrahams, PMP
Kyle Abrahams, PMP
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of phillyman2010
phillyman2010

ASKER

Hey ged325 thanks for your quick response. I also appreciate you hints and assistance but do you know where I can get the actual source code so that I can see what I need to do. I am not aware of the particulars about giving solutions but if it is against the website's policy (or even yours) to give code then I will understand. Thank you again.
Hi Philly,

The true answer for the complete source is "it depends".  This sight is normally a teaching site, to get people to understand what's going on.  Especially for homework the prescribed path is "post your code and ask questions".  
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Ok guys I am back. Sorry for the delayed response. I didn't want you think I was ignoring you. I greatly appreciate all of your assistance and advice. I have attempted to do the part of the program but I am still have problems. For some reason the output always gives the user a 1 and ends the turn and the same goes for the computer. So apparently I am not calling a method properly or something. Below is code for all of the classes and the last one is the game itself. Be forewarned that it is very lengthy (in my opinion) and apologize in advance but I think I am very close and just want finish this thing.

import java.util.Random;

public class Die
{
	  private int faceValue;
	  private final int MAX=6;
	  
	  public Die()
	  {
	  	faceValue = 1;
	  }
	  
	  //Math.random creates random integers from 1 - 6
	  public void roll()
	  {
	  	faceValue = (int)(Math.random() * MAX) +1;
	  }
	  
	  //Sets the face value
	  public void setFaceValue(int value)
	  {
	 	faceValue=value;
	  }
	  
	  //Gets the face value using the setFaceValue method
	  public int getFaceValue()
	  {
	  	return faceValue;
	  }
	  
	  //Converts values into a String
	  public String toString()
	  {
	  	String result = "You rolled a " + faceValue;
	
		return result;
	  }
	  
}// end class Die

Open in new window



public class RollingDice
{
//------------------------------------------------------
// Creates two Die objects and rolls them several times
//------------------------------------------------------
	public static void main (String[] args )
	{
		Die d1, d2 ;
		int sum ;
	
		// Creates two Die objects
		d1 = new Die() ;
		d2 = new Die() ;
		
		d1.roll() ;
		d2.roll() ;
		
		System.out.println ( " Die One: " + d1 + " , Die Two: " + d2 ) ;
		
		sum = d1.getFaceValue() + d2.getFaceValue();
		System.out.println ( " Sum: " + sum ) ;

   }// end main
}// end class RollingDice

Open in new window



public class PairOfDice
{
   private Die d1, d2;
   private int value1, value2, total;

   //-----------------------------------------------------------------
   //  Creates two six-sided Die objects, both with an initial
   //  face value of one.
   //-----------------------------------------------------------------
   public PairOfDice ()
   {
      d1 = new Die();
      d2 = new Die();
      value1 = 1;
      value2 = 1;
      total = value1 + value2;
   }

   //-----------------------------------------------------------------
   //  Rolls both dice and returns the combined result.
   //-----------------------------------------------------------------
   public void roll ()
   {
       d1.roll();
       d2.roll();
   }

   //-----------------------------------------------------------------
   //  Returns the current combined dice total.
   //-----------------------------------------------------------------
   public int getDiceSum ()
   {
	   total = getDie1() + getDie2();
      return total;
   }

   //-----------------------------------------------------------------
   //  Returns the current value of the first die.
   //-----------------------------------------------------------------
   public int getDie1 ()
   {
      return value1;
   }

   //-----------------------------------------------------------------
   //  Returns the current value of the second die.
   //-----------------------------------------------------------------
   public int getDie2 ()
   {
      return value2;
   }
	
	//-----------------------------------------------------------------
   //  Sets the FaceValue of the first die.
   //-----------------------------------------------------------------
	public void setDie1 (int value)
	{
		d1.setFaceValue(value);
	}
	
	//-----------------------------------------------------------------
   //  Sets the FaceValue of the second die.
   //-----------------------------------------------------------------
	public void setDie2(int value)
	{
		d2.setFaceValue(value);
	}
	
	//-----------------------------------------------------------------
   //  Sets the FaceValue of the second die.
   //-----------------------------------------------------------------
	public String toString()
   {
	String result = "You rolled a " + total;

	return result;
   } 
	
}

Open in new window



import java.util.Scanner;

public class DiceGame
{
	public static void main( String [] args )
	{
		//Rules of the Game
		System.out.println("______________________________________");
		System.out.println("/          Rules of the Game         /");
		System.out.println("/          -----------------         /");
		System.out.println("/  1)It's you vs computer.           /");
		System.out.println("/  2)You play by rolling the dice.   /");
		System.out.println("/  3)The first player to reach 100   /");
		System.out.println("/     points wins.                   /");
		System.out.println("/  4)When a player rolls a 1         /");
		System.out.println("/     the turn is over.              /");
		System.out.println("/  5)The computer's turn is over     /");
		System.out.println("/    when turn total reach 20 points /");
		System.out.println("/    in a single turn.               /");
		System.out.println("______________________________________");
		
		PairOfDice d1 = new PairOfDice(); //Creating PairOfDice object
		
		int turnTotal = 0;
		int computerTotal = 0; //your total
		int playerTotal = 0; //computer's total
		int turnOver = 1; //when to give up die
		int winner = 100; // amount to be reached before winning
		
		Scanner in = new Scanner( System.in );
		String answer; // named of what will take answer from user
		
		// first do-while loop is for repeating the change between user and computer
		do{
			if (playerTotal <= winner && computerTotal <= winner)
			{
				System.out.println("Your turn.");
				
				// do-while loop for the player's turn.
				do
				{
				System.out.println("Type 'y' if ready and 'n' to end turn.");
				answer = in.next();
				
				if (answer.equalsIgnoreCase("y") && playerTotal <= winner && computerTotal <= winner)
				{
					d1.roll();
					d1.getDie1();
					d1.getDie2();
					d1.toString();
					System.out.println(d1);					
					
					// if and else statement to figure out whether user's turn is over or not.
					if (d1.getDie1() == turnOver || d1.getDie2() == turnOver){
						System.out.println("You rolled a 1. Your turn is over.");
						System.out.println("Please type 'done' when you are ready to turn the dice over to the Computer.");
						answer = in.next();
					}
					else
					{
						turnTotal = turnTotal + d1.getDiceSum();
						playerTotal = playerTotal + d1.getDiceSum();
						System.out.println("Your Turn Total: " + turnTotal);
						System.out.println("Your Grand Total: " + playerTotal);
					}
				}
				}
				
				while (answer.equalsIgnoreCase("y") && playerTotal <= winner && computerTotal <= winner);
				turnTotal = 0; // turntotal assigned to 0 again.
				System.out.println();
				System.out.println("Your Grand Total is: " + playerTotal);
				System.out.println("The Computer's Grand Total is: " + computerTotal);
				System.out.println();
			
				//Begin the Computer's turn
				int endComputerTurn = 20;//when to end computer's turn
				turnOver = 1; //what die equals for turn to be over
				int answercomp = 1; 
				
				do
				{
					if (turnTotal <= endComputerTurn && answercomp == 1 && playerTotal <= winner && computerTotal <= winner)
					{
						d1.roll();
						d1.getDie1();
						d1.getDie2();
						d1.toString();
						System.out.println(d1);
								if (d1.getDie1() == turnOver || d1.getDie2() == turnOver)
								{
									System.out.println("The Computer rolled a 1. Their turn is over.");
									answercomp = 0;
								}
								
								else
								{
									turnTotal = turnTotal + d1.getDiceSum();
									computerTotal = computerTotal + d1.getDiceSum();
									System.out.println("The Computer's Turn Total is: " + turnTotal);
									System.out.println("The Computer's Grand Total is: " + computerTotal);
								}
					}
				}
				
				while (turnTotal <= endComputerTurn && answercomp == 1 && playerTotal <= winner && computerTotal <= winner);
				turnTotal = 0; //turntotal assigned to 0 again.
			
				if (playerTotal <= winner || computerTotal <= winner)
				{
					System.out.println();
					System.out.println("The Computer's Grand Total is: " + computerTotal);
					System.out.println("Your Grand Total is: " + playerTotal);
					System.out.println();
				}
			
				else
				{
				System.out.println();
				System.out.println();
				}
			}
		}
		
		while(playerTotal <= winner && computerTotal <= winner);
		
		// if-else statements to check if there is a winner
		if (playerTotal >= winner)
			System.out.println("You win!");
		else
			System.out.println("You lose ): ");
	
	}
}

Open in new window




Also, it is important to note that I am not getting any compiler errors from any of the programs just the hiccup from game itself. If there are any cosmetic issues please let me know so that I can do better next time. Thanks in advance.
Not a bad start.

There's no need for the class "rolling dice" as you have the roll method in die.  I  would comment out the class and see if you can still compile.  If you do, remove it.


In your getdie1/2 you're returning value1 and 2.  The issue with this is they're always 1 (what you're seeing).  What you actually want to return is the value of d1 & d2.  No need to have the values  at all in pair of dice.

 

In pairofdice:

public int getDie1 ()
   {
      return value1;  // should be d1.Value
   }


One other note:

you're missing a case here:
//handles when either die is a 1.   What about when both are a 1?  Which check should come first?
if (d1.getDie1() == turnOver || d1.getDie2() == turnOver){
            
Hey guys thanks for all of your help. I forgot to come back and tell you that I've figured it out and it is working perfectly thanks to your guidance. Thanks again.