Click here to Skip to main content
15,885,890 members
Articles / Web Development / HTML
Article

JavaScript Yahtzee

Rate me:
Please Sign up or sign in to vote.
3.00/5 (1 vote)
27 Jun 20065 min read 53.8K   751   8   1
This article describes a single-user version of the game Yahtzee, written in JavaScript.

JavaScript Yahtzee

JavaScript Yahtzee

Introduction

The JavaScript code provided here allows a single user to play the game of Yahtzee. Games are useful for honing one's skills because they not only incorporate interesting logic but also motivate one to design better interfaces. The fun of the game will be lessened by a poorly designed interface.

The game of Yahtzee consists of thirteen rounds in which the player rolls five dice. The player may then select any number of the dice to be held fixed (using the checkboxes) while the other dice are re-rolled. Two such re-rolls are allowed per round; the Roll button becomes disabled after the second re-roll. The player must then select one of the thirteen scoring options for the round (using the radio buttons). If the dice do not satisfy the condition of the chosen scoring category, a score of zero is issued. Once a scoring category has been selected, it cannot be used again; this rule is realized by disabling the previously selected radio buttons. The categories are divided into two groups, and a subtotal for each group is maintained as well as an overall total. In addition, the first group of scoring categories has an associated 35-point bonus if its subtotal exceeds 62. The player can review the rules and scoring options page (YahtzeeRules.htm) by clicking on the Yahtzee Rules image at the top of the main page (YahtzeeMain.htm).

Using the code

After establishing the basic game logic, i.e., determining whether a particular scoring condition has been met, most of the effort went into user-interfacing considerations. An important tactic is to disable an element unless it is meaningful for the player to use it. For example, in the first screen capture shown above, the Roll Dice button is disabled because the player used his/her two re-rolls and cannot roll any more in the present round; the Next button is also disabled since the player has not scored the current round and so cannot move on to the next round before doing so. Similarly, all of the textboxes are read-only since the scores will be determined by the program and not the user.

Another instance of attention to user-interfacing is in the re-roll situation. Consider that a player may have selected a single die for re-rolling. If the re-rolled die value matches the original die value (which would happen on an average of one-sixth of the time), then the player does not get a visual sense that the die has been rolled. To remedy this predicament, two JavaScript timers, one of each type, were introduced, as seen in the code below:

JavaScript
timerID = setInterval("TimerRoll()", 50);
timerID2 = setTimeout("StopTimer()", 800);

The first timer calls the function TimerRoll() periodically, every 50 milliseconds; that function then selects a new random number for the appropriate dice and displays the corresponding image. The second (one-shot) timer calls the function, StopTimer(), once after 800 milliseconds; the latter function stops the first timer. In this way, the dice values and, more importantly, the displays are changed several times during a roll, giving the user a more visual (though by no means realistic) sense of dice rolling. With rolling now taking place over an extended period of time, code was introduced so that the user could not use any of the other functionalities mid-roll. The setInterval function returns a system-generated number which is assigned to the variable timerID in the code above. Testing whether the timer is active is achieved by setting the timerID variable to -1 when the roll is finished and testing for this condition in the other event handlers.

One feature of the JavaScript radio buttons (and checkboxes) is that the associated text is not part of the element. As a consequence, more precision is required of the user in clicking a JavaScript radio button than in, say, a Visual-Basic radio button. To alleviate this situation, the text associated with the radio buttons is placed in a <div> tag, and the <div>'s Click event selects the corresponding radio button (provided the timing event is not in effect and the radio button is not disabled). For each checkbox, a Click event method is added to the <td> element that contains it. The method toggles the checkbox's Checked attribute. Since clicking on the checkbox is also clicking in the table cell, this had the undesired outcome that clicking on the checkbox toggles it twice. To remedy this situation, the same method is used to handle the checkbox's Click event, thus clicking on the checkbox now toggles the checkbox's checked state three times, giving the desired effect.

To allow for some indecision on the player's part, the radio button click events are not used to "register" the player's scoring-category choice. Instead, an Enter Score button is introduced. However, a more experienced player might resent the extra steps involved in clicking the Enter Score button. For this reason, both the radio button and the <div> are given a double-click event handler that calls the Enter Score button's Click-event method under the right circumstances. This built-in redundancy accommodates both the novice and the experienced users.

After rolling the dice, the player can preview the result for a particular scoring category by placing the cursor over the corresponding <div> element. As can be seen in the first screen capture above, the selected <div> changes color, and the prospective score appears in the corresponding textbox in a gray font color. With this addition, the <div>, not a traditionally dynamic element, has four event methods as seen in the example below:

HTML
<div id="divScore13" style="DISPLAY: inline; WIDTH: 132px; 
    COLOR: #dcdcdc; HEIGHT: 22px"
    onclick="return divScore_onclick(13)"
    ondblclick="return divScore_ondblclick()" 
    onmouseover="return divScore_onmouseover(13)"
    onmouseout="return divScore_onmouseout(13)">
         Chance
</div>

Points of interest

Originally, at the end of the game, there was a pop-up window. The pop-up window contained the following code to display the player's score:

JavaScript
var score;
var message="GAME OVER: <br />Your score was ";
try
{
    score = window.opener.document.getElementById("txtTotal").value;
    document.getElementById("divMessage").innerHTML=message+score;
}

However, with the tendency for browser security settings to question the user about each script, this feature becomes more trouble than it is worth.

History

  • Submitted Summer 2006.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralPretty Works... Pin
Pier...29-Jun-06 7:25
Pier...29-Jun-06 7:25 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.