








Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!









Mehran Sahami Handout # CS 106A November 5, 2007
Based on a handout written by Eric Roberts and Julie Zelenski.
Note: Yahtzee™^ is the trademarked name of a game produced by Hasbro. We refer to this game for educational purposes only. Okay, we also like to have fun playing the game. But then again, something can be both "educational" and "fun" (hopefully, like CS106A), so we shouldn't run into any problems there. Thanks for listening. We now return to our previously scheduled assignment.
Arrays, arrays, everywhere...
Now that you have have arrays at your disposal, your ability to write interesting programs takes a dramatic leap forward. To solidify your understanding, Assignment #5 uses arrays in a variety of contexts to implement a popular multiplayer dice game. There are arrays for the dice, arrays for the dice to reroll, arrays for the player names, arrays for a player’s score, and even an array of arrays (that is, a 2-dimensional array) to handle the entire scorecard. By the time you’re done, you will be well on your way to mastering the concept of arrays.
The goal
Your task is to create a computer version of the game Yahtzee™. Some of you may have already played the game, but for those who haven’t, it’s simple to learn. There are five dice and one to four players. A round of the game consists of each player taking a turn. On each turn , a player rolls the five dice with the hope of getting them into a configuration that corresponds to one of 13 categories (see the following section on ―Dice Categories‖). If the first roll doesn’t get there, the player may choose to roll any or all of the dice again. If the second roll is still unsuccessful, the player may roll any or all of the dice once more. By the end of the third roll, however, the player must assign the final dice configuration to one of the thirteen categories on the scorecard. If the dice configuration meets the criteria for that category, the player receives the appropriate score for that category; otherwise the score for that category is 0. Since there are thirteen categories and each category is used exactly once, a game consists of thirteen rounds. After the thirteenth round, all players will have received scores for all categories. The player with the total highest score is declared the winner.
Dice categories
The thirteen categories of dice configurations and their scores are:
Running the applet
On the "Assignments" page on the CS106A web site, you will find a demo applet that you can use as a model. As outlined in the section entitled ―What is provided,‖ all the methods to implement the graphics and mouse interaction have been written for you. This section describes the way the program works as a whole.
When the program begins, it displays a welcome message and asks the user to enter the number of players. It then asks the user to enter the names of the players, one at a time. Suppose that there are two players—Eric and Julie—locked in a cutthroat, head-to-head, winner-take-all showdown. After you use the pop-up dialog boxes to enter the names Eric and Julie , the applet displays the starting Yahtzee scorecard and dice in the graphics window, as shown in Figure 1 on the next page.
Figure 2 (After Eric’s first roll)
At first glance, these numbers look wonderful, with three 5’s already! Thinking that he has a chance for the Yahtzee category, Eric wants to reroll the 3 and the 4. To indicate this choice, all Eric has to do is click on these two dice. Doing so highlights these dice as follows:
Figure 3 (Eric has selected the 3 and 4 and is ready to reroll)
To reroll the selected dice, all the player has to do is click on the Roll again button. Until this button is clicked, the player can select or deselect any particular die by clicking on it. For example, if Eric decided instead to try for some kind of straight, he could deselect the 3 and the 4 by clicking on them and then selecting new dice—presumably two of the 5’s—by clicking on these.
Always overconfident, Eric decides to go for the Yahtzee and rerolls just the 3 and 4. Unfortunately, Eric doesn’t get any more 5’s on his second roll, so he selects those same
two dice for his final roll, but is again unsuccessful in his quest for more 5’s. Eric ends up with the three 5’s, a 6, and a 3, as shown in Figure 4.
Figure 4 (After Eric’s final roll of his first turn, choosing category Three of a Kind )
While Eric didn’t manage to secure a Yahtzee , he did come up with a reasonably decent Three of a Kind. When asked to choose a category, Eric clicks Three of a Kind, and a score of 24 points will be recorded in the column.
Now it’s Julie’s turn. Julie has better karma than Eric, but we won't talk about that right now. Anyway, Figure 5 shows the configuration of the dice at the end of her three rolls: three 2’s and two 3’s. Julie is quite pleased and plans to use this configuration for a Full House , which is worth 25 points and gives her the early lead.
Figure 5 (After Julie’s final roll of her first turn, as she is choosing her category)
The game continues in a similar fashion. On each turn, players must
Note that a player will sometimes have to choose a category that doesn’t match the configuration of the dice, because there are no appropriate categories left. In such cases, the player simply scores 0 in the selected box.
Let’s fast-forward to Round #13—the final round—where we find the tide has turned:
Figure 8 (At the beginning of the final round—Eric’s up but has not yet rolled)
Eric is in trouble. Julie has already gotten her Yahtzee, and Eric desperately needs his. He rolls the dice and gets a 1, 3, 4, and two 2’s. Uggh! He keeps the 2’s and rerolls the 1, 3, and 4. Now he gets a 5, 6, and 3. He rolls these same dice yet another time. Nothing much comes of it—just a 2, 4, and 6. Eric is forced to use this motley collection in the Yahtzee category, which gets him a big, fat 0 (since it does not satisfy the criteria for an actual Yahtzee ). Too bad Eric — sometimes that's just how life turns out.
It’s Julie’s turn; all she has left is Sixes. She is already headed for victory, but she plows ahead to rub it in. Julie’s first roll gives her one 6 along with four useless numbers. She discards the junk and gathers two more 6’s during her two rerolls, earning a 18 in Sixes.
Since the game is now over, the upper and lower scores are computed and if applicable, the upper bonus is awarded. Julie earned her upper bonus, since those last 6’s pushed her upper score over 63. Eric, however, fell short. Julie shows Eric who’s boss with a final score of 273 to 192 (shown on the next page)!
Figure 9 (At the end of the game)
What is provided in the starter project
The starter project provides the following:
The YahtzeeDisplay class
As noted in the preceding section, the starter project contains a precompiled class called YahtzeeDisplay that manages the drawing and event-handling. This section of the handout offers a brief overview of the methods, which should be enough to get you started. The assignments area of the CS 106A web site contains a javadoc file for YahtzeeDisplay that displays the full story, the important parts of which are reproduced as Figure 11 on the next two pages.
As this last example illustrates, any calls to the methods in the YahtzeeDisplay class must include the variable display as the receiver. You are asking the display to print a message and therefore must use the receiver-based style of method call.
Figure 11. Entries in the YahtzeeDisplay class
public YahtzeeDisplay(GCanvas gc, String[] playerNames) Creates a new YahtzeeDisplay object that adds its objects to the GCanvas specified by gc. The playerNames parameter is an array consisting of the names of the players. Usage: YahtzeeDisplay display = new YahtzeeDisplay(gc, playerNames); Parameters: gc The GCanvas on which the board is displayed playerNames An array containing the names of the players, indexed from 0. public void waitForPlayerToClickRoll(int player) Waits for the player to click the "Roll Dice" button to start the first dice roll. You will call this method once at the beginning of each player's turn. The parameter is the index number of the player, which ranges from 1 to nPlayers , where nPlayers is the number of players in the game. The method highlights the player's name in the scorecard, erases any dice displayed from previous rolls, draws the "Roll Dice" button, and then waits for the player to click the button. This method returns when the button is pressed. At that point, it is your job to randomly roll the dice and call the displayDice method. Usage: display.waitForPlayerToClickRoll(player); Parameter: player The index of the player, ranging from 1 to nPlayers public void displayDice(int[] dice) Draws the pictures of the dice on the screen. You pass one parameter, a zero-based integer array with N_DICE entries, that contains the values to draw on the dice. Each value in the array must be a valid die roll between 1 and 6; if not, displayDice will throw an ErrorException. You will need to call this method after each roll or reroll of the dice to display the new random values. Usage: display.displayDice(dice); Parameter: dice An array of dice values, whose indices range from 0 to N_DICE - 1 public void waitForPlayerToSelectDice() Allows the player to select which dice to reroll by clicking on the dice with the mouse. You will call this method twice each player turn, giving them two additional chances to improve their roll. This method draws the "Roll Again" button, and waits for the player to click on the dice to select and deselect which ones they would like to reroll. The method returns only after the player has made a selection and clicks the "Roll Again" button. Once the method returns, you can use the isDieSelected method to determine whether the die should be rerolled. Usage: display.waitForPlayerToSelectDice(); public boolean isDieSelected(int index) Checks to see whether the die specified by index is selected. You call this method before each reroll to determine whether this die needs to be updated. Usage: if (display.isDieSelected(index))... Parameter: index The index number of the die, which ranges from 0 to N_DICE - 1 Returns: true if the die is selected, and false otherwise public int waitForPlayerToSelectCategory() Allows the user to select a category in which to place the score for this roll. You will call this method once each turn after the player finishes rolling the dice. As its name suggests, the method waits for the player to click on one of the categories and returns the index of the category, which will be one of the constants defined in YahtzeeConstants. Note that this method does not check to see whether the category is valid for the dice values or whether this category has already been used by this player. Thus, you will need to include some error-checking in your program to test the result of waitForPlayerToSelectCategory before you try to update the scorecard. Usage: int category = display.waitForPlayerToSelectCategory(); Returns: The category number selected by the player
stored in the array are valid for the category and false otherwise. Note some categories (namely, Chance and Ones , Twos , etc.) accept any dice configuration; for these categories checkCategory always returns true. The javadoc describing the class YahtzeeMagicStub is available from the "Assignments" page of the CS106A web site, but for your convenience, we note that the static method YahtzeeMagicStub.checkCategory can be called as follows (assuming we have an array of int s named dice that we want to check to see if it matches the Full House category):
boolean p = YahtzeeMagicStub.checkCategory(dice, FULL_HOUSE);
In the early stages of your development, you can use our checkCategory method to help you get up and running. Ultimately, however, you need to write this method yourself. As you develop your own version of this method, you’ll probably want to test it in stages. You could, for example, write a method that tests the validity of, say, Three of a Kind , but uses the implementation from YahtzeeMagicStub for everything else. When that works, you could move on to take care of Four of a Kind, and then Yahtzee and Full House. Once you have your own methods for checking the validity of these categories, move on to tackling Small Straight and Large Straight.
For full credit, you should not use YahtzeeMagicStub. checkCategory anywhere in the final version of your program. If you find determining the validity of a certain category or categories too difficult, you may use our method, but you will lose points for each category whose validity you do not check with your own implementation.
In a similar vein, look for other intermediate milestones you can aim for instead of heading straight for the final goal and letting it overwhelm you. For example, it is easier to get a single-player game working than a multi-player game. If there is only one player, you can work with a single array of scores. After you can reliably play a single-person game, you can move on to support an array of players’ scores where a multidimensional array will be needed.
You also might find it worthwhile to create a ―cheat‖ mode during development. If you are running in cheat mode, you can prompt the user to specify the values by typing them in instead of choosing the dice randomly. Implementing this feature will make it easier for you to check the various situations that can come up during the game, rather than waiting and hoping for them to come up randomly at some point during your testing.
Hints and other random details
Extensions
Since the standard assignment is pretty much a full implementation of the Yahtzee game, it is hard to come up with ideas for extensions, but don’t let our lack of creativity stop you from exploring things that you would find interesting. Here’s at least a few ideas that occurred to us:
As always, you should only tackle extensions after you have completed and thoroughly tested all the basic requirements. If you do create an extended version, please hand in both a basic and an extended version to make it easier for us to verify the base functionality. Small extensions that don’t disrupt the basic functionality are fine to include in one version. Be sure to describe in your comments where we should look for your fun additions!