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 » Games Programming » Mastermind Game in C#

Mastermind Game in C#

This is the game of Mastermind written in C#. The game is played by clicking on a set of 4 colors and then hitting the score button. Colors can repeat themselves in this game, so be wary!

Author Rank:
Total page views :  24997
Total downloads :  915
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
MastermindMG.zip
 
Powerful ASP.NET Hosting w/ NO Setup Fees. Click Here!
Become a Sponsor


Interviews



Game Description


This is the game of Mastermind written in C#. The game is played by clicking on a set of 4 colors and then hitting the score button. Colors can repeat themselves in this game, so be wary! The score is determined each time with the following rules:

A black peg to the right of your guess indicates that one of the pegs is in the right location in the row (although you do not necessarily know which position it is referring to). Four black pegs indicates you have won the game because all 4 colors are in the right position in the row. A white peg indicates that one of the pegs is correct, but its in the wrong position in the row. An empty peg (hollow circle), indicates that one of the colored pegs is completely wrong and is not part of the puzzle. Anotherwords, if after pressing the Score button, you have 4 hollow pegs, then you can eliminate all the pegs in the row as being part of the solution to the puzzle. 

Strategy

Use the previous guesses and logic to figure out which pegs are referring to which colors.

Application Design

This is a GDI+ application and utilizes the DrawEllipse and FillEllipse routines to draw the pegs on the board. It is also a good application for examining multidimensional arrays. Below is the UML design for Mastermind:



Fig 1.2 - UML Design Reverse Engineered using WithClass 2000

You'll notice that a lot of the design is centralized around the Board class. The Board class draws the color pegboard and calls the ScoreBoard class to draw the score peg column. The ColorPanel is also drawn directly onto the form and has a routine for determining which color is chosen by the user called GetColorAt. Below is the sequence of events that happens when a user chooses a color on the panel:



Fig 1.3 - Sequence of events after pressing ColorPanel using WithClass

The Mouse Coordinates on the form are used to determine the location of the color on the color panel and then the next available peghole in the row is filled.

The board is drawn using a 2 dimensional Grid array to store the color peg positions.  The position is scaled to the appropriate location on the form:

public void Draw(Graphics g)
{
// cycle through the Grid Matrix and place the
// indicated colored peg at the indicated location
for (int i = 0; i < Grid.GetLength(0); i++)
{
for (int j = 0; j < Grid.GetLength(1); j++)
{
// a Grid value of 0 indicates an empty slot
// draw an empty hole
if (Grid[i,j] == 0)
{
Rectangle r =
new Rectangle(PegHole.Left, PegHole.Top, PegHole.Width, PegHole.Height);
r.Offset(i* (PegHole.Width + SPACING), j* (PegHole.Height + SPACING));
r.Offset(MARGIN, MARGIN);
g.DrawEllipse(Pens.Black, r);
g.FillEllipse(Brushes.Black, r);
}
else
{
// there is a peg here, draw the colored peg
Rectangle r = new Rectangle(Peg.Left, Peg.Top, Peg.Width, Peg.Height);
r.Offset(i* (PegHole.Width + SPACING), j* (PegHole.Height + SPACING));
r.Offset(MARGIN, MARGIN);
Brush aBrush = Brushes.Black;
// This routine retrieves the brush matching
// the integer at the grid point
aBrush = GetBrush(Grid[i,j]);
// draw the colored peg with the determined brush
Pen aPen = new Pen(aBrush,1);
g.FillEllipse(aBrush, r);
g.DrawEllipse(Pens.Black, r);
aPen.Dispose();
}
}
}
// draw the score column
TheScore.Draw(g);
// draw the color peg choice panel
ThePanel.Draw(g);
}

Listing 1.0 - Drawing the entire board of Mastermind

The last interesting code to look at in this project is the scoring algorithm.  The score is determined by first figuring out the locations that the player matched exactly and marking them.  Then the white pegs are determined by going through each peg in the solution row and checking it against all the pegs of the player row. Again, arrays are used extensively here:

public int CalcScore()
{
int nExact = 0;
int nThere = 0;
int nCount = 0;
int[] places = new int[4]{-1, -1, -1, -1};
int[] places2 = new int[4]{-1, -1, -1, -1};
// match exact rows first, this is easier
for (int i = 0; i < 4; i++)
{
if (GuessingRow[i] == Grid[i, CurrentRow])
{
nExact++;
TheScore.AddBlackPeg(CurrentRow, nCount);
nCount++;
places[i] = 1;
places2[i] = 1;
}
}
// check the special case where the player may have solved the puzzle
if (nExact == 4)
{
return nExact;
}
// now check for all the white pegs, a bit trickier
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
// make sure the positions aren't the same and the pegs in the different positions
// both in the solution and the player row haven't already been determined
if ((i != j) && (places[i] != 1) && (places2[j] != 1))
{
// if the GuessedRow color matches the Grid Color at a different position
// We have a white peg
if (GuessingRow[i] == Grid[j, CurrentRow])
{
nThere++;
TheScore.AddWhitePeg(CurrentRow, nCount);
nCount++;
places[i] = 1;
places2[j] = 1;
j = 5;
// force a break, (I know, you can also use break;)
}
}
}
}
return nExact; // return the # of exact (black pegs) that matched
}

Summary

This is the first cut.  While playing the game, one thing I noticed would be a nice improvement would be to be able to specify the row hole you want to fill, rather than fill in order from left to right.  This will come out in the next version. Have fun!


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.
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.
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
MastermindMG.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments
hi!i need your help. by karen On July 22, 2007
Hi!I'm currently doing a mini project using programming C#.I need to hand in by next week.My lecturer only taught me the basic of c#.I'm stuck with my project.Can you help me by adding me to ur Msn?
Reply | Email | Delete | Modify | 
Do you have any tips? by max On February 24, 2008
Hi I am aged 11 and love C#, and am trying to do things that will help me to learn more about programeing. I would like to start making games like mastermind or checkers or chess or somthing. Do you have any tips, helping points or guides i can please use for my programing. So far I have not managed to ecumplish much (E.G. click buttons to make a button turn different colours, and clicking buttons to make other dialoge boxes appear.) I would be very greatfull if you could help me. Thanks, Max
Reply | Email | Delete | Modify | 
Re: Do you have any tips? by Mike On February 26, 2008

Hi Max,

It's great that you are already programming C# at age 11! Myself, I started programming on an Apple II at around age 15 in Basic (before there was a visual basic).  What I recommend you do to start programming games is to look at some of the code here on C# corner.  Also try to learn about Object-Oriented design before actually programming c#.  If you learn design concepts first, you can think of the big picture of programming the game, instead of the programming implementation.  Then you can apply the design concepts to the c# easier.  A few books they may help you is any books on UML (The Unified Modeling Language) and a book by Grady Booch called Object-Oriented Analysis and Design.

If you want to start getting into game programming, I think you'll find it also involves a lot of math Points, Transforms, even a little Trigonometry.  However you can get away with creating simpler games with just points and rectangles. 

I would look at doing your first game with GDI+ using C#.  This is the library for graphics in C#.  The ones used to create Halo 3 and others are probably DirectX and 3D Studio (expensive and much more difficult).  GDI+ and C# should be enough to do checkers, chess, mastermind, etc.)   Take a look at the following link that I wrote as well:

http://www.c-sharpcorner.com/UploadFile/mgold/SpaceInvaders06292005005618AM/SpaceInvaders.aspx

This is space invaders in C#.  The article shows a UML diagram which is the design I used to develop space invaders.  If you can understand this diagram, you'll understand some important object-oriented concepts such as inheritance, aggregation, association and one-to-many relationships.  Also in the diagram are classes, attributes and operations.  The C# Code maps directly to this diagram.

Anyway, hope this gives you a head start into the programming and software engineering world and helps you with your first game.

Best Regards,

-Mike

Reply | Email | Delete | Modify | 
Re: Re: Do you have any tips? by max On February 27, 2008

Thanks Mike, I will look at the space invaders, and will try see if any of it can help me. I am really enjoying C# and hope to become really good at it. My uncle learns C#, and so if i cant understand the diagram, i will just ask him, and will be off again.

 

Thanks, Max.

Reply | Email | Delete | Modify | 
link has been died by tho On October 14, 2008
it's been died. can you post again,please??????????????
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
 © 1999 - 2010  Mindcracker LLC. All Rights Reserved