|
|
|
|
|
|
Author Rank:
|
|
Total page views :
24459
|
|
Total downloads :
1242
|
|
|
|
|
Download
Files:
|
|
|
|
|
|
|
|
|
|
|
|
|
Similar ArticlesMost ReadTop RatedLatest
|
|
|
|
|
|
|
|
|
|

Figure 1 - Sudoku Puzzle Player and Some of the Options
I am pretty much flabbergasted at how prevalent the Sudoku craze is here. If you pick up many of the newspapers in NY city, there are Sudoku puzzles next to the crossword. Borders and Barnes and Noble have Sudoku books on their counter spaces. And just today, I was talking to a cohort at work, and found out that he does the Sudoku puzzle on the way to work on the train from Jersey. So is Sudoku a fad or a brainteaser staple? Time will only tell. In the meantime, "if you can't beat'em join'em." This .NET program will allow you to play Sudoku, print Sudoku, save Sudoku, and check Sudoku puzzles that you come across in your day to day activities (I almost went as far to add e-mal Sudoku functionality, but figured that would be taking things a bit far). The program also comes with a hint feature, that figures out the possible values for each square as you are playing the game. I don't know about you, but I just want to solve the puzzle and not go through the work of writing the possible values for all 30 some cells (although some people may argue that this is half the fun of Sudoku so you are free to turn this feature off in the Utilities menu). This app also allows you to create a Sudoku template and save it or save a Sudoku puzzle in progress. Sudoku templates are saved with a .xml extension, where work in progress is saved with a .sav extension. Both types of files are xml files. An example of a Sudoku template is shown in the figure below:

Figure 2 - Sudoku Template File saved in Xml Format
Saving a Sudoku Template
To create a brand new template, first click File -->New in the menu. Then go to Utilities-->and Check Template Mode in the menu. Finally proceed to type in a Sudoku puzzle you found in the paper. When you are finished, choose File-->Save As Template to save the fresh puzzle. If you ever want to start the puzzle over, either open the file you saved, or choose Restart from the Utilities menu.

Figure 3 - Creating a Sudoku Puzzle in Template Mode
Playing Sudoku
Now that you have your puzzle, be sure to turn off Template Mode in the Utilities Menu and begin to play. Just type in your guesses. Allowable values are 0-9 and <space>. The zero and <space> keys both allow you to clear a cell you feel may be a wrong choice. Speaking of wrong choices, the puzzle will also warn you if you put in a number that is in a duplicate Sudoku block, column, or row as shown in figure 4.

Figure 4 - Sudoku Guess with Duplicate Entry
Design
The design of the Sudoku Game Player is fairly simple with only three classes: the main form, the SudokuReader and the SudokuGrid class. The Form does all the painting, printing, and user interaction. The SudokuGrid maintains all the Grid Data, calculates hints, and checks the board. The SudokuReader reads and writes the Sudoku data to xml.

Figure 5 - UML diagram of Sudoku Player reverse engineered using WithClass
Code
There are a lot of aspects of the code that are worth mentioning, but for the purpose of this article, we will talk about how to use Xml to read and write the grid data. The Xml library in .NET is extremely rich. There are many ways you can read and write Xml using .NET from including DataSets, Searlizable Objects, or the System.Xml library. In this article we chose to use the System.Xml libray in order to customize our xml format to one shown in Figure 2. Reading the Xml is performed using the XmlDocument. The XmlDocument has a method called Load that allows you to load any well formed document into the XmlDocument object and then work with the Xml as a hierarchal collection of XmlNode objects. We can also use XPath (the Xml Query Language) to read the particular nodes we are interested in, instead of traversing the whole XmlDocument tree.
Listing 1 - Reading the Sudoku puzzle into an XmlDocument to get the grid data
XmlDocument _xDoc = new XmlDocument(); public SudokuGrid Read(string filename) { try { // load the Xml document from an xml file. // as long as the Xml in the file is well formed, // this will work. _xDoc.Load(filename);
// Construct the grid data from the xml file SudokuGrid grid = new SudokuGrid(_xDoc);
return grid; } catch (Exception ex) { Console.WriteLine("Couldn't Load the Grid in {0}-->{1}", filename, ex.ToString()); }
return null;
} |
The Constructor of the SudokuGrid calls on XPath to pull out the collection of Row nodes inside the XmlDocument. These Row nodes are each traversed and the data within is parsed and stuck inside the grid. Each number in a row is separated by commas, so this data can be split up into an array using the string Split method.
Listing 2 - Parsing out the Xml Data using a combination of XPath and string.Split
public SudokuGrid(XmlDocument xdoc) { // read in sudoku hint nodes using XPath _nodes = xdoc.SelectNodes("//Hints/Rows/*");
// parse out the numbers in the row ParseHintNodes();
// read in sudoku player guess nodes using XPath _nodes = xdoc.SelectNodes("//Guesses/Rows/*");
// parse out the numbers in the row ParseGuessNodes();
}
public void ParseHintNodes() { int row = 0;
// precondition - there must be nodes to parse if (_nodes == null) return;
// traverse each xml node and pull out the text. // split the text using the Split method in the string class
foreach (XmlNode n in _nodes) {
// split the comma delimited string of numbers in the row string[] rowValues = n.InnerText.Split(new char[]{','}); int col = 0; foreach (string num in rowValues) { // blank cells are assigned 0 if (num == "-") { _grid[row, col] = 0; } else { // populate the grid with the row value _grid[row, col] = Convert.ToInt32(num);
// track the cells that are hint cells. // we will treat them differently when we paint them _knownElements[row,col] = Convert.ToInt32(num); }
col++; } row++; }
} |
Writing out the Sudoku Grid
Writing the grid is a little more complicated because it involves constructing each node of Xml documenting and appending children to each node. Once the node structure is built, you can simply use the Save method of the XmlDocument object in conjunction with an XmlWriter to write out the Xml file. Below is the code used to save the Xml Template shown in Figure 2.
Listing 3 - Saving the contents of the grid to an Xml Template file t using XmlDocument and XmlWriter
public void SaveTemplate(string filename, SudokuGrid grid) { // create a new xml document _xDoc = new XmlDocument();
// fill the xml document from the existing grid data FillTemplate(_xDoc, grid);
// save the xml document to disk with the filename passed in SaveToDisk(filename); }
// FillTemplate fills the xml structure from the grid data
public void FillTemplate(XmlDocument doc, SudokuGrid grid) { // create the top level nodes for Sudoku/Hints/Rows XmlNode rows = doc.CreateNode(XmlNodeType.Element, "Rows", ""); XmlNode sudoku = doc.CreateNode(XmlNodeType.Element, "Sudoku", ""); XmlNode hints = doc.CreateNode(XmlNodeType.Element, "Hints", "");
doc.AppendChild(sudoku); sudoku.AppendChild(hints); hints.AppendChild(rows);
// add each of the 9 rows from the grid as a XmlNode element called Row for (int row = 0; row < 9; row++) { // crete a new Row Node XmlNode node = doc.CreateNode(XmlNodeType.Element,"Row", "");
// append the Row node as a child of the Rows node rows.AppendChild(node);
for (int col = 0; col<9; col++) { if (grid[row, col] == 0) { // empty cell, concatenate a dash node.InnerText += "-" + ","; } else { // concatenate a comma delimited list of row elements node.InnerText += grid[row, col] + ","; } }
// remove the last comma from the row if (node.InnerText.Length > 0) { node.InnerText = node.InnerText.Remove(node.InnerText.Length -1 , 1); }
}
}
private void SaveToDisk(string filename) { // create an xml writer for writing to disk XmlTextWriter xmlWriter = new XmlTextWriter(filename, null);
// specify the format of the xml writer xmlWriter.IndentChar = '\t'; xmlWriter.Indentation = 1; xmlWriter.Formatting = Formatting.Indented;
// save the contents of the XmlDocument structure to disk _xDoc.Save(xmlWriter);
// close the stream of the file xmlWriter.Close(); }
|
Conclusion
Sudoku may keep you busy on route to work, but coding xml file manipulation can keep you busier. Using XmlDocument along with XPath, reading the contents of Xml files becomes a bit easier, especially if you are targeting specific information. The XmlDocument class also helps you easily write an xml structure out to a file. With the huge amount of support .NET gives you, you can come out xml'ing like roses.
Site References
Sudoku - Generating and Solving using the Pocket PC, Alex Groysman
Using Genetic Algorithms to come up with Sudoku Puzzles, Mike Gold
Sudoku Site, Pappocom
Sudoku and SudokuList Online, Michael Mepham
|
|
|
Login
to add your contents and source code to this article
|
|
|
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
|
|
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.
|
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
|
|
|
|
|
|
|
|
|
Download
Files:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|