Wednesday, July 17, 2013

Finished

I would suggest that you read my Yahtzee postings in reverse order.

I finished writing the Yahtzee program.  I ended up with these classes:  Die, DiceTray, Scorer, Player, Game, and Yahtzee.  Here is a link to a UML diagram that summarizes the structure of my code:
http://www.cs.appstate.edu/~dap/classes/1440/yahtzee.jpg

The takeTurn method in the Player class does the following:

  • Say whose turn it is.
  • Print the Scorer object.
  • Roll the dice.
  • Print the DiceTray object.
  • Ask the user which dice to reroll.
  • for two more times:
    • Read the user's answer to the reroll question.
    • Make the boolean array to pass to the roll method.
    • Pass the array to the roll method.
    • Print the Scorer object.
    • Print the DiceTray object.
    • If it's the first of two rerolls, ask the user again which ones to reroll.
  • Ask the user how to score the roll.
  • Get the answer.
  • Call the tally method.

My Yahtzee class is very simple:

import java.util.Scanner;

public class Yahtzee
{
    public static void main(String[] args)
    {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("How many players? ");
        int numPlayers = keyboard.nextInt();
        Game g = new Game(numPlayers);
        g.play();
    }
}

The constructor of the Game class gets passed the number of players.  It makes an array of Player objects of that size and then runs a loop that same number of times.  Each time through the loop it asks for a player's name, allocates a new Player object, sets its name, and adds it to the array of Players.

The play method in the Game class does the following:

  • Run a loop 13 times.  Each time through that loop, run another loop that goes through the array of players calling the takeTurn method on each one.
  • Find the largest score by going through the array of players and calling the getScore method on each one.
  • Declare the winner.



1 comment:

  1. My implementation of the game is very similar to Dr. Parks's.

    The major difference is where we decided to handle scoring a particular roll.

    My Game class goes through pretty much the same sequence of game events for each player until the game is over. I decided to also include a way to handle ties in my winner declaration.

    I also have only one set of dice for the Game, instead of one for each Player.

    There are many ways to organize the components of the game, but the sequence of events is always the same: roll dice > ask player to re-roll or stand > ask player for scoring category > calculate and record score, with print statements for the dice and score thrown in as things change.

    ReplyDelete