Game of Pig Rules •The game requires two dice. •Players take turns until someone
ID: 3597934 • Letter: G
Question
Game of Pig Rules
•The game requires two dice.
•Players take turns until someone wins by earning at least 100 points.
•A Player begins a round (for a player’s turn), by rolling both dice and tallying the points. The current player may continue to roll and accumulate points until rolling a 1 on either of the two dice or choosing to hold. Whenever a player rolls a 1 on either of the two dice, all points for the round are lost. Whenever a player rolls a pair of 1s, (i.e. 1, 1) all player points are lost, and the player’s score starts over at 0.
•The game turn advances to the next player.
•For this Game of Pig project, the game will be between you and the computer, where you may have the first turn.
Project Requirements
For each of the provided classes that make up the project, do not create additional methods or fields. Do not make any changes to the following requirements without approval from your instructor.
Step 0: Download the zipped Game of Pig startup.
From Blackboard Assignments for project 3, right-click on the file
GameOfPig.zip
and do a save target as to
162 Project Organizer/3 Semester projects/Project 3
within your BlueJ project organizer.
Step 1: Unzip the Game of Pig project
For Windows users, navigate with Windows Explorer to find
162 Project Organizer/3 Semester projects/Project 3/Game of Pig.zip
within your BlueJ project organizer subfolder, right-click on this file, and select extract all.
Step 2: Open your Game of Pig project
Within your Game of Pig project, find each of the following classes:
GVdie and GVdieTester. Do not change the GVdie class!
Dice
Player and MyDialog
PigGame
PigGUI
Compile all six classes in your Game of Pig project. Each class should compile with no errors. Review and execute the main methods in the GVdieTester, Dice, and Player classes.
To quickly preview a preliminary execution of the whole project, start the program by invoking the PigGUI main method. The application should prompt for your name, create a graphical user interface similar to the screen shot on the next page, and print a welcome message on the BlueJ Terminal Window. At this point, nothing will happen when the player clicks on the roll button.
Sample PigGUI Screenshot (see Step 7)
Step 3: Review the provided GVdie class
You will need to understand how to use each of the following GVdie class methods.
Gvdie methods
Method specifications
void roll( )
randomly changes the value of the die to 1,2,3,4,5, or 6.
int getValue( )
returns the current value of the last roll.
void setBlank( )
sets the die value to zero with a blank face.
void setHeld( boolean b )
marks the die as selected (true) or unselected (false).
boolean isHeld( )
returns true if the die is selected, otherwise, returns false.
Step 4: Implement methods in the Dice class
Dice fields
dice
An array for 2 Die objects: die[0] and die[1]
tally
An array of seven integers to record the number of 1s, 2s, 3s, 4s, 5s, and 6s rolled in the last roll
Dice methods
Method specifications
public Dice( )
instantiates an array for two Die, and populates it with die[0] and die[1] (See the start up for Dice.)
Accessor methods
An accessor method does not modify class fields.
public GVdie getDie( int n )
returns die[ n ]. legal values for n: 0 or 1
public int getValue( )
returns die[0].getValue( ) + die[1].getValue( )
public String toString( )
returns a comma separated string, e.g. 6, 6
Mutator method
A mutator method may modify class fields.
public void roll( )
rolls both die[ 0 ] and die[ 1 ]
Step 5: Implement methods in the Player class
Player fields
type
name
String
score
int
isOnAuto
boolean
true – the turn is played by algorithm, without user input.
false – the play is under user control. The player chooses to roll or to hold
Player methods
Method specifications
Two constructors
public Player( )
this constructor prompts the user
public Player( String name )
Accessor methods
An accessor method does not modify class fields.
public String toString( )
returns a string in the form:
name + ": " + score
Step 6: Implement methods in the PigGame class
Class Fields
dice as a Dice object, player, turn as 0 or 1, turnsTaken, and the roundScore.
Constant identifiers for a user index, a computer index, and the winning score.
Constructor
public PigGame( ) - a constructor that prints a welcome message and
instantiates dice
instantiates and populates the player array,
initializes turn, turnsTaken, and roundScore
Accessor Methods do not modify class fields.
public int getRoundScore( ) returns the round score.
public GVdie getDie( int n ) - returns the requested die. Legal values for the parameter n are 0 or 1.
public boolean playerWon( int n ) - returns true if either the player score or the computer score is currently high enough to win. Otherwise, returns false. Legal values for the parameter n are 0 or 1.
private boolean noWinnerYet( ) – returns true if neither the USER player nor the COMPuter player is a winner, otherwise returns false.
Mutator Methods
The playerRolls and playerHolds methods, as designed below, are used by both players: user and computer.
public void restart( ) – resets appropriate instance variables to start a new game. Do not instantiate new dice objects.
public void nextTurn( ) – advances turn by 1 modulus 2, increments turnsTaken, and resets the round score to zero
public void playerRolls( ) - performs the first half of the player turn:
print the player’s name and score if the round score is 0.
invoke the dice.roll( )
If either die value is '1' then set the round score to 0. Otherwise, increment the round score by the new total.
Print the round score. Refer to the sample output below.
public void playerHolds( ) - performs the second half of the player's turn:
1) update the player's score by either adding the roundScore to the player score or setting the player score to zero if double 1s are rolled.
2) print the player's name and score. Refer to the sample output below.
3) print an appropriate message if the player wins.
4) invoke nextTurn to transfer control to the next player
private Boolean autoPlayContinues – returns the boolean value for an expression where the roundScore is not 0, the players score plus the round score is less than 100, and the round score is less than 19 (i.e. game strategy)
public void play( ) - performs an entire turn
if the player[ turn ] is on auto
Uses a do while loop to repeatedly call playerRolls as long as autoPlayContinues is true
Calls playerHolds.
else call playerRolls once for one roll
public void autoPlay( ) - Restarts the game, sets both players to isOnAuto, and
repeatedly calls the play method in a do .. while loop as long as there is no winner.
public boolean isPlayerTurn( int n ) - this one line method returns true if it is the player's turn or false if it is the computer's turn.
--------------------------------------------------------------GVdie--------------------------------------------
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
/*****************************************************************
A graphical representation of a six-sided die with various controls
over the appearance. Current value is constrained between 1 and 6.
You can control the size and color of the dice.
<h4>An Example</h4>
<blockquote><pre><code>
GVdice die1 = new GVdice();
die1.roll( );
int result = die1.getValue();
</code></pre></blockquote>
<p>
@author Scott Grissom
@version 1.4 October 10, 2006
*****************************************************************/
public class GVdie extends JPanel implements MouseListener, Comparable{
/** current value of the die */
private int myValue, displayValue;
/** is the dice currently on hold? */
private boolean held;
/** current size in pixels */
private int mySize;
/** dot size in pixels defined by overall die size */
private int dotSize;
/** offset in pixels for the left row of dots */
private int left;
/** offset in pixels for the right row of dots */
private int right;
/** offset in pixels for the middle dot */
private int middle;
/** color of the dice when held */
private Color HELD_COLOR = Color.pink;
/** default color of dice */
private Color BACKGROUND = Color.white;
/** repeats for animation */
private int NUM_ROLLS;
/** Timer for animation */
private javax.swing.Timer myTimer;
/*****************************************************************
constructor creates a die of specified size X size pixels
@param size the length of each side in pixels
*****************************************************************/
public GVdie(int size) {
// initialize the die and determine display characteristics
mySize = size;
held = false;
dotSize = mySize / 5;
int spacer = (mySize - (3*dotSize))/4;
left = spacer;
right = mySize - spacer - dotSize;
middle = (mySize - dotSize) /2;
setBackground(BACKGROUND);
setForeground(Color.black);
setSize(size,size);
setPreferredSize(new Dimension(size, size));
setMinimumSize(new Dimension(size, size));
setMaximumSize(new Dimension(size, size));
// create the fancy border
Border raised = BorderFactory.createRaisedBevelBorder();
Border lowered = BorderFactory.createLoweredBevelBorder();
Border compound = BorderFactory.createCompoundBorder(raised, lowered);
setBorder(compound);
// set default values
displayValue = myValue = (int) (Math.random()*6)+1;
setNumRolls(6);
myTimer = new javax.swing.Timer(250, new Animator());
addMouseListener(this);
}
/*****************************************************************
* default constructor creates a die of size 100 X 100 pixels
*****************************************************************/
public GVdie() {
this(100);
}
/*****************************************************************
Is the dice currently held?
@return true if the die is held. Otherise, false.
*****************************************************************/
public boolean isHeld(){
return held;
}
/*****************************************************************
Set the die face to blank
*****************************************************************/
public void setBlank(){
displayValue = 0;
repaint();
}
/*****************************************************************
Set whether the die is held or not
@param h true if die is currently held
*****************************************************************/
public void setHeld(boolean h){
held = h;
if(held){
setBackground(HELD_COLOR);
}else{
setBackground(BACKGROUND);
}
repaint();
}
/*****************************************************************
Sets the color of the dots
@param c a Java Color object such as Color.red
*****************************************************************/
public void setForeground(Color c){
super.setForeground(c);
}
/*****************************************************************
Updates the image after obtaining a random value in the range 1 - 6.
@param none
@return the new value between 1 - 6
*****************************************************************/
public void roll (){
myValue = (int) (Math.random()*6)+1;
// start the animated roll
myTimer.restart();
}
/*****************************************************************
Set the delay in milliseconds between frames of the animation.
Default value is 250.
@param msec milliseconds to delay
*****************************************************************/
public void setDelay (int msec){
if (msec > 0)
myTimer = new javax.swing.Timer(msec, new Animator());
}
/*****************************************************************
Set the number of rolls before stopping the animation.
Default value is 6.
@param num number of rolls before stopping
*****************************************************************/
public void setNumRolls (int num){
NUM_ROLLS = 0;
if (num > 0)
NUM_ROLLS = num;
}
/*****************************************************************
gets the current value of the die (1 - 6)
@return the current value of the die
*****************************************************************/
public int getValue(){
return myValue;
}
/*****************************************************************
Display the current value of the die. Called automatically
after rolling. There is no need to call this method directly.
@param g the graphics context for the panel
@return none
*****************************************************************/
public void paintComponent(Graphics g){
super.paintComponent(g);
// paint dots
switch (displayValue){
case 1:
g.fillOval (middle,middle,dotSize,dotSize);
break;
case 2:
g.fillOval (left,left,dotSize,dotSize);
g.fillOval (right,right,dotSize,dotSize);
break;
case 3:
g.fillOval (middle,left,dotSize,dotSize);
g.fillOval (middle,middle,dotSize,dotSize);
g.fillOval (middle,right,dotSize,dotSize);
break;
case 5: g.fillOval (middle,middle,dotSize,dotSize);
// fall throught and paint four more dots
case 4:
g.fillOval (left,left,dotSize,dotSize);
g.fillOval (left,right,dotSize,dotSize);
g.fillOval (right,left,dotSize,dotSize);
g.fillOval (right,right,dotSize,dotSize);
break;
case 6:
g.fillOval (left,left,dotSize,dotSize);
g.fillOval (left,middle,dotSize,dotSize);
g.fillOval (left,right,dotSize,dotSize);
g.fillOval (right,left,dotSize,dotSize);
g.fillOval (right,middle,dotSize,dotSize);
g.fillOval (right,right,dotSize,dotSize);
break;
}
}
/*****************************************************************
respond to the dice being clicked
@param e the mouse event
*****************************************************************/
public void mouseClicked(MouseEvent e){
if(held){
held = false;
setBackground(BACKGROUND);
}else{
held = true;
setBackground(HELD_COLOR);
}
repaint();
}
public void mousePressed(MouseEvent e){}
public void mouseReleased(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
/*****************************************************************
allows dice to be compared if necessary
@param o compare the dice with this object
@return -1 if dice is less than passed object
*****************************************************************/
public int compareTo(Object o){
GVdie d = (GVdie) o;
return getValue() - d.getValue();
}
/******************************************************
INNER class to roll the dice as an animation
******************************************************/
private class Animator implements ActionListener{
int count = 0;
public void actionPerformed(ActionEvent e){
displayValue = (int) (Math.random()*6)+1;
repaint();
count++;
// Should we stop rolling?
if (count == NUM_ROLLS){
count=0;
myTimer.stop();
displayValue = myValue;
repaint();
}
}
}
}
Gvdie methods
Method specifications
void roll( )
randomly changes the value of the die to 1,2,3,4,5, or 6.
int getValue( )
returns the current value of the last roll.
void setBlank( )
sets the die value to zero with a blank face.
void setHeld( boolean b )
marks the die as selected (true) or unselected (false).
boolean isHeld( )
returns true if the die is selected, otherwise, returns false.
Explanation / Answer
import java.util.Scanner;
public class Assignment
{
Boolean humanTurn = true;
Boolean computerTurn = true;
int dice;
int humanTurnPoints, computerTurnPoints;
int humanTotalPoints = 0;
int computerTotalPoints = 0;
public void roll()
{
dice = (int)(Math.random()*6) + 1;
}
public int humanTurnScore()
{
{
humanTurnPoints = dice + humanTurnPoints;
System.out.println("You threw: " + dice);
System.out.println("You have scored: " + humanTurnPoints + " in your turn.");
} return humanTurnPoints;
}
public void humanTurnZero()
{
humanTurnPoints = 0;
}
public int computerTurnScore()
{
{
computerTurnPoints = dice + computerTurnPoints;
System.out.println("Computer has scored: " + computerTurnPoints + " in its turn.");
} return computerTurnPoints;
}
public void computerTurnZero()
{
computerTurnPoints = 0;
}
public Assignment()
{
humanGame();
if(!humanTurn)
{
computerTurn();
}
}
public int humanGame()
{
System.out.println("To start the game please press 'r'.");
Scanner key = new Scanner(System.in);
String start = key.nextLine();
if(!start.equalsIgnoreCase("R"))
{
System.out.println("Make sure you are pressing 'r'.");
humanGame();
}
if(start.equalsIgnoreCase("R"))
{
System.out.println("You pressed 'r'.");
System.out.println("Lets start.");
do{
roll();
if(dice == 1)
{
System.out.println("You got 1 and you lost your turn.");
System.out.println("Computer's GRAND TOTAL score is: " + computerTotalPoints);
humanTurnZero();
computerTurn();
}
else if(dice != 1)
{
humanTotalPoints += dice;
if(humanTotalPoints >= 100)
{
System.out.println("You threw: " + dice);
System.out.println("Your GRAND TOTAL score is: " + humanTotalPoints);
System.out.println("Congratulations, you win!");
System.exit(0);
}
humanTurnScore();
System.out.println("Your GRAND TOTAL score is: " + humanTotalPoints);
System.out.println("Computer's GRAND TOTAL score is: " + computerTotalPoints);
System.out.println("You can hold or roll again.");
System.out.println("To roll again press 'r' or 'h' to hold.");
Scanner keyboard = new Scanner(System.in);
String choice = keyboard.nextLine();
if(choice.equalsIgnoreCase("R"))
{
System.out.println("You pressed 'r'.");
System.out.println("Lets roll again.");
roll();
if(!choice.equalsIgnoreCase("R"))
{
System.out.println("You didn't press 'r'. To make sure the program is running correctly please press 'r' to roll or 'h' to hold.");
humanGame();
}
}
if(choice.equalsIgnoreCase("h"))
{
System.out.println("You pressed 'h' and loose your turn.");
System.out.println("Your Grand total is: " + humanTotalPoints);
humanTurnZero();
computerTurn();
}
}
}while(humanTurn);
}return dice;
}
public int computerTurn()
{
System.out.println("Now it's computer turn.");
do {
roll();
if(dice != 1)
{
computerTotalPoints += dice;
if(computerTotalPoints >=100)
{
System.out.println("Computer threw: " + dice);
System.out.println("Computer's GRAND TOTAL score is: " + computerTotalPoints);
System.out.println("Game Over! the computer wins");
System.exit(0);
}
System.out.println("Computer threw: " + dice);
System.out.println("Computer's GRAND TOTAL score is: " + computerTotalPoints);
System.out.println("Your Grand total is: " + humanTotalPoints);
computerTurnScore();
roll();
}
if(dice == 1)
{
System.out.println("Computer thrown 1 therefore it's your turn now.");
computerTurnZero();
humanGame();
}
if(computerTurnPoints >= 20)
{
System.out.println("Computer scored already " + computerTurnPoints + " you'd better start to focus.");
System.out.println("Please play again");
humanGame();
}
}while (computerTurn);
return dice;
}
public static void main(String[] args)
{
new Assignment();
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.