Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » LINQ » Think in LINQ: Yahtzee Score Calculator Using LINQ Technology

Think in LINQ: Yahtzee Score Calculator Using LINQ Technology

This article revisits the yahtzee program I wrote in 2002 and reimplements scoring using LINQ technology. It compares the old way of scoring with LINQ and shows you the advantages of using LINQ.

Author Rank:
Total page views :  8511
Total downloads :  108
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
LINQYahtzee.zip
 
Become a Sponsor


This is an update of the Yahtzee game I wrote back in 2002 which replaces the ScoreCalculator class with methods that use LINQ queries on the dice array.  In order to use LINQ, you'll need to download a preview of LINQ functionality into Visual Studio from Microsoft.  LINQ takes some getting used to, because you have to alter your thought process a little in order to write the code for filtering, grouping, sorting, and examining collections.  However, once you get the hang of it, the code you write is greatly reduced and much cleaner.

LINQ can be broken down into about 14 different operator groups.  Below are most of the commonly used ones:

Table 1 - Operators built into LINQ

Operator Definition Keyword
Filter Restricts the data in a collection with a condition Where, OfType
Select Selects specific items from a collection as well as being able to select generated and calculated items. Select, SelectMany
Partitioning Chooses portions of a collection based on the index in the sequence. Take, Skip
Sorting Puts the collection in order OrderBy, OrderByDescending, ThenBy, ThenByDescending, Reverse
Grouping Groups the items in a collection into a collection of groups GroupBy
Set Operations Does Set operations on one or more collections Distinct, Union, Intersect, Except
Conversion Converts the IEnumerable<> collection to another collection type ToArray, ToList, ToDictionary
Single Element Accesses an individual element in the collection First, ElementAt
Aggregate/Statistical functions Performs a function on the collection to obtain statistical data for the whole collection Count, Sum, Min, Max, Average, Fold
Quantifiers Returns a boolean to determine if the items in the collection meet the functions criteria Any, All, EqualAll

In the article to follow, we'll use some of these functions in our yahtzee score calculator to determine a score in a particular row on the yahtzee board.

Out with the Old, In with the New

Let's look at one of the scoring challenges.  In yahtzee, there is a column for each number on the die.  The row with a particular die number is scored by the total of the dice displaying that number.  So, for example, let's say you roll the five dice, and 4 three's appear on 4 of the 5 dice, a sample roll might be {3, 4, 3, 3, 3}.  If you put this score in the three's row, then you would get a score of  4 x 3 = 12.  How do we handle calculating the score for matching die in code?

Let's first think about what we want to accomplish in order to understand the code implementation.  We want to extract all the dice from the collection with the die number equal to nDie.  Then we want to add them up. 

Old Method:

Normally we we would loop through all values in the dice collection and use an if statement to determine if the die were equal to nDie.  If the die was equal to nDie, we would add the die to a total sum that was initialized to zero.

LINQ Method:

Run a query on the dice collection that filters all die = nDie using a Where clause.  Take the results of this query and call a Sum function to sum the matching die.

Listing 1 - Calculating matching Dice Rolls using LINQ

public int CalculateLikeRolls(int nDie, Dice[] dice)
{
// determine all the dice in the dice collection
// that have the value of nDie

var numberOfValues = from die in dice where die.RollNumber == nDie select die.RollNumber;

// Add all the values which have value nDie together
int sum = numberOfValues.Sum();

// add the sum to the total score and to the upper
// score section

m_nTotal += sum;
m_nUpperTotal += sum;

return sum;
}

 

Although this isn't a large difference in the amount of code, it is a lot cleaner and brings us to a higher level of thinking about how we milk our collection data for useful information.  Also, (as you'll see in the following yahtzee calculations), LINQ reduces our code by quite a bit.

Let's take a look at another yahtzee score:  three of a kind. With three of a kind, if you have at least 3 of the same die value out of 5 die, you can sum the die together for the score and put it in the three of a kind column.  How do we score this in code?

Old Method:

Somehow we need to determine which items in the collection are alike.  One way to do this is to build a Hashtable containing a histogram of all 6 (1-6) die possibilities as keys.  We increment each hash key each time a die matches that key.  If one of the keys is equal to or greater than 3, then we loop through all the dice and sum them.

LINQ Method:

Group all the dice by like numbers and count them in a generated DieCount collection.  Determine if there is Any group containing at least 3 dice.  If so, Sum the dice.  You can start to see how the solution to the problem more closely matches your thinking in the implementation of the solution.

Listing 2 - Calculating Three of A Kind using LINQ

public int CalculateThreeOfAKind (Dice[] myDice)
{

// group the die by dice number and keep a count of each group
var groupCounts = from die in myDice
group die.RollNumber by die.RollNumber into g
select new {Category = g.Key, DieCount = g.Count()};
 

// determine if there is at least 3 dice in any group
bool count3 = groupCounts.Any(dieGroup => dieGroup.DieCount >= 3);
 

// if not, then there is no score
if (count3 == false)
 return 0;
 

// yes, we have three of a kind, sum all the dice
int nTotal = SumAllDice(myDice);
m_nTotal += nTotal;
m_nLowerTotal += nTotal;
return nTotal;
}
 

Finally, let's look at how to score a large straight.  A large straight is a set of 5 consecutive die values (either a roll of {1, 2, 3, 4, 5}  or a roll of {2,3,4,5,6})

Old Method:

One way to determine if you have a large straight is to sort all the die in an ArrayList, then loop through each die and determine if the die in front of the previous die is at least 1 ahead of the previous die.  Another way would be to sort all the die in order, then loop through each of the two possible large straight arrays and test each die against the corresponding element at the same index to see if they are the same. 

LINQ Method:

See if one of the two possible straights {1, 2, 3, 4, 5}  and {2,3,4,5,6} Intersect with all 5 dice in the roll.

Listing 3 - Calculating a Large Straight using LINQ

public int CalculateLargeStraight (Dice[] myDice)
{

// now test against 2 possibilities

//  get the dice as a result of integers

var result = from die in myDice orderby die.RollNumber select die.RollNumber;

// possible large straights
int[] largeStraight1 = new int[5]{1,2,3,4,5};
int[] largeStraight2 = new int[5]{2,3,4,5,6};
 

// test to see if the roll intersects all 5 dice in either of the two possibilities
bool commonValues1 = ((IEnumerable<int>)result).Intersect(largeStraight1).Count() == 5;
bool commonValues2 = ((IEnumerable<int>)result).Intersect(largeStraight2).Count() == 5;

// if either possibility is true, add a score of 40
if (commonValues1 || commonValues2)
{
int nTotal = 40;
m_nTotal += nTotal;
m_nLowerTotal += nTotal;
return nTotal;
}

return 0;
}

Conclusion:

LINQ is a powerful technology for manipulating collections that will require you to change your thinking of how you are probably currently manipulating them in C#.  Not only can LINQ help you query and manipulate collections in memory, but LINQ technology can be extended to work with databases (DLINQ)  and XML (XLINQ).  Ultimately,  LINQ reduces code size and helps your code implementation match a higher level thinking of working with the data.  In the meantime,  if you are in search for the missing LINQ, you may have found it here in C# and .NET 3.0.


Login to add your contents and source code to this article
 About the author
 
Mike Gold
Michael Gold is President of Microgold Software Inc., makers of the WithClass UML Tool. His company is a Microsoft VBA Partner and Borland Partner. Mike is a Microsoft MVP and founding member of C# Corner. He has a BSEE and MEng EE from Cornell University and has consulted for Chase Manhattan Bank, JP Morgan, Merrill Lynch, and Charles Schwab. Currently he is a senior developer at Finisar Corp. He has been involved in several .NET book projects, and is currently working on a book for using .NET with embedded systems. He can be reached at mike@c-sharpcorner.com
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
LINQYahtzee.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments
I need help seriously! by Dana On May 28, 2009
I need some help making a yahtzee game on Vb 6.0 I'm desperate and not too good with this program yet, can you or someone give me the code that's short and to the point? I need it for a final, it's worth 300 points... Please I need someones help that knows what they're doing...
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.