Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Please edit within the code that I have to the best of your abilities. I struggled with putting things in the right places to coorellate

Please edit within the code that I have to the best of your abilities. I struggled with putting things in the right places to coorellate with the code that was given. I have displayed all the classes that are needed for the program to run below. I am supposed to add and edit to this. Total of 5 classes.

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 players 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 players 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.

GV DIE CLASS

-------------------

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.

An Example

GVdice die1 = new GVdice(); die1.roll( ); int result = die1.getValue();

@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(); } } }

}

Pig GUI

----------

/*************************************************************** * GUI front end to the game of Pig * * @author Scott Grissom * @version September 14, 2012 ***************************************************************/ import java.awt.*; import javax.swing.*; import java.awt.event.*;

public class PigGUI extends JFrame { /** game */ private PigGame game;

/** buttons */ private JButton playerRollBtn, playerHoldBtn, computerBtn;

/** labels */ private JLabel roundLbl, playerLbl, computerLbl;

/** menu items */ private JMenuItem restartItem; private JMenuItem autoPlayItem; private JMenuItem quitItem;

// Indexing for game players public static final int USER = PigGame.USER; // an index for user public static final int COMP = PigGame.COMP; // an index for computer /********************* * PigGUI constructor *********************/ public PigGUI( ) { setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); this.setSize( 600, 400 );

game = new PigGame( ); setTitle( game.player[ USER ].name ); playerLbl = new JLabel( ); playerLbl.setForeground( Color.red ); roundLbl = new JLabel( ); computerLbl = new JLabel( );

// Create a Listener Listener listener = new Listener( ); playerRollBtn = new JButton( "Roll" ); playerRollBtn.addActionListener( listener );

playerHoldBtn = new JButton( "Hold" ); // -------------------------------------------------------- // 1) Add listener to the playerHoldBtn -- one line of code

// --------------------------------------------------------

computerBtn = new JButton( "Computer" ); // ------------------------------------------------------- // 2) Add listener to the computerBtn -- one line of code

// -------------------------------------------------------

updateButtonsAndLabels( ); addComponentsToGrid( ); setupMenus( listener ); setVisible( true ); }

private void addComponentsToGrid( ) { setLayout( new GridBagLayout( ) ); GridBagConstraints panelPosition = new GridBagConstraints( );

// places the player, round score, and computer labels in the top row of the grid panelPosition.gridx = 0; panelPosition.gridy = 0; add( playerLbl, panelPosition ); panelPosition.gridx = 1; panelPosition.gridy = 0; add( roundLbl, panelPosition ); panelPosition.gridx = 2; panelPosition.gridy = 0; add( computerLbl, panelPosition );

// places both dice from the game in the middle row of the grid panelPosition.gridx = 0; panelPosition.gridy = 1; add( game.getDie( 0 ), panelPosition );

panelPosition.gridx = 2; panelPosition.gridy = 1; add( game.getDie( 1 ), panelPosition ); // places the game control button in the bottom row of the grid panelPosition.gridx = 0; panelPosition.gridy = 2; add( playerRollBtn, panelPosition ); panelPosition.gridx = 1; panelPosition.gridy = 2; add( playerHoldBtn, panelPosition );

panelPosition.gridx = 2; panelPosition.gridy = 2; add( computerBtn, panelPosition ); } /****************************** * Set up a File menu of items ******************************/ private void setupMenus( Listener listener ) { JMenuBar menuBar; JMenu fileMenu;

menuBar = new JMenuBar( ); setJMenuBar( menuBar ); fileMenu = new JMenu( "File" ); menuBar.add( fileMenu );

restartItem = new JMenuItem( "Restart" ); restartItem.addActionListener( listener ); fileMenu.add( restartItem );

autoPlayItem = new JMenuItem( "Auto Play" ); autoPlayItem.addActionListener( listener ); fileMenu.add( autoPlayItem );

quitItem = new JMenuItem( "Quit" ); quitItem.addActionListener( listener ); fileMenu.add( quitItem ); }

private void updateButtonsAndLabels() { // Updates text colors and disables buttons as needed if (game.isPlayerTurn( USER )) { computerBtn.setEnabled( false ); playerRollBtn.setEnabled( true ); playerHoldBtn.setEnabled( true );

playerLbl.setForeground( Color.red ); computerLbl.setForeground( Color.black ); } else { computerBtn.setEnabled( true ); playerRollBtn.setEnabled( false ); playerHoldBtn.setEnabled( false );

playerLbl.setForeground( Color.black ); computerLbl.setForeground( Color.red ); }

// ------------------------------------------------------------ // 3) Update the three score labels in place of "REPLACE THIS" roundLbl.setText( "Round: " + game.getRoundScore() ); playerLbl.setText( "REPLACE THIS" ); computerLbl.setText( "REPLACE THIS" ); // ------------------------------------------------------------ }

/************************************************************* * Display winning message if either player or computer wins. *************************************************************/ private void reportWinner( String message ) { JOptionPane.showMessageDialog( this, message, "Game of Pig", JOptionPane.INFORMATION_MESSAGE ); }

private class Listener implements ActionListener { /****************************************************** * Respond to the user action from * * listener.actionPerformed( actionEvent ) * * @param e - the JComponent triggering the event/call ******************************************************/ public void actionPerformed( ActionEvent e ) { JComponent eventSource = (JComponent) e.getSource( );

if (eventSource == restartItem) { game.restart( ); } else if (eventSource == autoPlayItem) { game.autoPlay( ); } else if (eventSource == quitItem) { System.exit( 1 ); } else if (eventSource == playerRollBtn) { // -------------------------------------------- // 4) Call game play method -- a one line call

// --------------------------------------------

// In case the user rolled at least a single 1, the player involuntarily holds if (game.getRoundScore( ) == 0 && !game.player[ USER ].isOnAuto ) { game.playerHolds( ); } } else if (eventSource == playerHoldBtn) { // --------------------------------------------------------------------- // 5) Call the game method so that the player holds -- one line of code

// --------------------------------------------------------------------- } else if (eventSource == computerBtn) { // ------------------------------------------------ // 6) Call the game play method -- a one line call

// ------------------------------------------------ }

if (game.playerWon( USER )) { reportWinner( "The winner is " + game.player[ USER ].toString( ) ); } else if (game.playerWon( COMP )) { reportWinner( "The winner is " + game.player[ COMP ].toString( ) ); }

updateButtonsAndLabels( ); } }

/******************************************* * Create the GUI, for an event driven game *******************************************/ public static void main( String[ ] args ) { PigGUI gui = new PigGUI( ); } }

Pig Game

------------------

public class PigGame { private Dice dice; public Player[ ] player; private int turn; private int turnsTaken; private int roundScore; // the current round score

// CONSTANTS public static final int USER = 0; // user index public static final int COMP = 1; // computer index private static final int WINNING_SCORE = 100;

public PigGame( ) { this.dice = new Dice( 2 ); this.player = new Player[ 2 ]; this.player[ USER ] = new Player( ); this.player[ COMP ] = new Player( "computer" );

this.restart( ); } /** * resets appropriate instance variables to start a new game. * Do not instantiate new dice objects. */ public void restart( ) { System.out.print( "\f" ); System.out.println( "Welcome to the game of Pig. " );

this.player[ USER ].score = 0; this.player[ COMP ].score = 0;

this.turn = COMP; // or USER this.turnsTaken = 0; this.nextTurn( ); }

/** * advances turn by 1 modulus 2, * increments turnsTaken, and * resets the round score to zero */ private void nextTurn( ) {

} /** * returns the roundScore */ public int getRoundScore( ) { return -1; }

/** * This method is needed by the PigQUI class. * * returns the requested die, * dice.die[0] or dice.die[ 1 ], * from the public dice field. * * Legal values for the parameter n are 0 or 1. */ public GVdie getDie( int n ) { return this.dice.die[ 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. */ public boolean playerWon( int n ) { return false; }

/** * returns true if neither the USER player nor the * COMPuter player is yet a winner, otherwise returns false. */ public boolean noWinnerYet( ) { return false; }

/** * performs the first half of the player turn */ public void playerRolls( ) { // 1) print the player's name and score if the round score is 0.

// 2) invoke the dice.roll( )

// 3) If either die value is '1' then set the round score to 0. // Otherwise, increment the round score by the new total.

// 4) Print the dice followed by the round score. // See the sample output in the project description.

}

/** * performs the second half of the player's turn */ public void playerHolds( ) { //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 name and score. See the sample output in the project description.

// 3) print an appropriate message if the player wins.

//4) invoke nextTurn

}

/** * 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) */ private boolean autoPlayContinues() { return ( true ); }

/** * performs an entire turn */ public void play( ) { if (this.player[turn].isOnAuto) { // 1) For a whole turn, use a do ... while loop to repeatedly call // playerRolls as long as autoPlayContinues returns true

// 2) Call playerHolds, which completes the turn.

} else { // 3) Call playerRolls once for one round as this is not the whole turn

} }

/** * This method is needed by the PigQUI class * * this one line method returns true if it is the * player's turn or false if it is the computer's turn. */ public boolean isPlayerTurn( int n ) { return false; }

/** * Restarts the game, * sets both players to isOnAuto, and * repeatedly calls play in a do .. while loop * as long as there is no winner. */ public void autoPlay( ) { this.restart( ); this.player[ USER ].isOnAuto = true; this.player[ COMP ].isOnAuto = true;

} public static void main( String[ ] args ) { PigGame pig = new PigGame(); pig.autoPlay( ); } }

--------------------------------

DICE

/** * The Dice class encapsulates a die array of GVdie objects * and a tally array of length 7. * * The roll method rolls all of the dice and tallies, in the * tally array, the number of the 0s, 1s, 2s, 3s, 4s, 5s, 6s * rolled. Obviously tally[ 0 ] is always 0, but * tally[ 1 ] contains how many 1s, * tally[ 2 ] contains how many 2s, etc. * * @author (your name) * @version (a version number or a date) */ public class Dice { public GVdie[ ] die; private int[ ] tally = {0, 0, 0, 0 , 0, 0, 0};

public Dice( int count ) { die = new GVdie[ count ]; // create the die array for (int n = 0; n < count; n++) // populate the die array { die[ n ] = new GVdie( ); } }

// public GVdie getDie( int num ) // { // return this.die[ num ]; // }

/** * rolls all the dice and tallies the results */ public void roll( ) { for (int n = 0; n < tally.length; n++) { tally[ n ] = 0; }

for (int n = 0; n < die.length; n++) { die[ n ].roll( );

tally[ die[ n ].getValue( ) ]++; } }

/** * returns the sum of the dice values rolled */ public int getValue( ) { int total = 0; for (int n = 0; n < die.length; n++) { total += die[ n ].getValue( ); } return total; }

/** * returns true if any of the dice rolled * matched number, otherwise returns false. */ public boolean rolled( int number ) { for (int n = 0; n < die.length; n++) { if ( die[ n ].getValue( ) == number ) { return true; } } return false; }

/** * returns a string description of the dice configuration */ public String toString( ) { if (die.length < 4 ) { String str = "" + die[ 0 ].getValue( ); for (int n = 1; n < die.length; n++) { str += ", " + die[ n ].getValue( ); } return str; } else { return toString4( ); } }

/** * returns a string description for the tally * of the dice configuration */ private String toString4( ) { String str = "";

for ( int n = 1; n < tally.length; n++) { if (tally[ n ] > 0) { str += n + "s: " + tally[ n ] + ", "; } } return str.substring( 0, str.length() - 2 ); }

public static void main( String[ ] args ) { Dice dice = new Dice( 2 );

dice.roll( ); System.out.println( "Rolling two dice" ); System.out.println( dice.toString( ) ); System.out.println( dice.toString4( ) ); System.out.println( "Sum of dice: " + dice.getValue( ) ); System.out.println( "Rolled a 1: " + dice.rolled( 1 ) ); } }

-------------------------------

Player class

import javax.swing.JOptionPane;

/** * Player encapsulates the name, the score, and * an autoplay switch for a single player. * * All fields are public. */ public class Player { public String name; public int score; public boolean isOnAuto;

public Player( String playerName ) { this.name = playerName; this.score = 0;

this.isOnAuto = true; }

public Player( ) { this.name = MyDialog.getString( "Enter player name", "Amanda" ); this.score = 0;

this.isOnAuto = false; }

public String toString( ) { return this.name + ": " + this.score; }

public static void main( String[ ] args ) { Player player = new Player( ); JOptionPane.showMessageDialog( null, player.toString( ) ); MyDialog.showMessage( player.toString( ) ); System.out.println( player.toString( ) + " \tisOnAuto = " + player.isOnAuto ); Player computer = new Player( "computer" ); JOptionPane.showMessageDialog( null, computer.toString( ) ); MyDialog.showMessage( computer.toString( ) ); System.out.println( computer.toString( ) + " \tisOnAuto = " + computer.isOnAuto); } }

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Hands On Database

Authors: Steve Conger

1st Edition

013610827X, 978-0136108276

More Books

Students also viewed these Databases questions

Question

In an Excel Pivot Table, how is a Fact/Measure Column repeated?

Answered: 1 week ago