Sudoku Game in C# - CodeProject.pdf

May 10, 2018 | Author: Ayeni Moses Moscow | Category: Matrix (Mathematics), Computer Programming, Computing, Technology, Software Development


Comments



Description

Articles » General Programming » Game Development » GamesSudoku Game in C# Gokuldas, 25 Dec 2005    4.40 (21 votes) The sudoku game in C#. Download demo project - 28.7 Kb Introduction I came across the Sudoku game a few months back. I commute by train daily to my office; this puzzle, in everyday newspaper, was one of my favorite ways to pass time in the train. I thought why not develop this game in C#? This article is on the implementation of this game in C#. The game provides three complexity levels: simple, medium and complex. The should be between 1 and 9 and should appear only once. Implementation The main class implementing this game is Sudoku and is implemented in Sudoku. I hope you will enjoy playing this game. The rules are as follows: 1. 2. switch(level) { .cs file.noOfSets. The 9X9 matrix is made of nine 3X3 matrices. This way I could generate 1000s of combinations. The other part implements the view. which displays the answer for a few seconds and then brings back the problem. in each row and column. As I am using two dimensional array to keep the problem and answer sets. which is the most common form of this game. So.user can view the answer for a few seconds to get a clue. sets and reversing numbers. Then. The ColumnChanging event of the DataTable is quite useful and I have used this event to handle data validations such as "valid number". The number. I will only explain the important methods. I tried to fill other sets. Now that we know the rules. int minPos. the number in each of these subsets should also be between 1 and 9 and should appear only once. You can use this if the problem is complex and for getting some clues. I have provided a button control to show the answer. I decided to take one unique solution as the base and then derive other unique solutions by swapping rows. The basic design idea is to first generate the solution and then unmask certain spots based on the complexity level. Rules of Sudoku The game has simple rules. columns. Using the code Sudoku class is the main class implementing the game. Another important part of the game is to provide data validations. GenerateGame() method of the Sudoku class uses this technique. Initially. Hence.cs file.maxPos. I spent some time to create a solution by populating sets which were independent using random numbers between 1 and 9. The event arguments of this event enable us to set the appropriate error message for the affected column. You can see the full implementation by downloading the source code using the links given above. public void GenerateGame(GameLevel level) { // InitialiseSet // This first creates answer set by using Game combinations InitialiseSet(). I have used DataSet which is easier to bind to the grid. The game presented in this article arranges numbers in 9X9 matrix. The next section describes the code. GenerateGame(GameLevel level) method generates the new game. The code for this is given below: // Method: GenerateGame // Purpose: Generates game based on complexity level. This was a bit complex and was taking time. let us see the implementation.NET Framework installed on your PC or laptop to run this program. // Now unmask positions and create problem set. You require . I have used DataGrid which is a very useful control to represent data in tabular form. "answer position not changed" and "number is not a duplicate". I have exposed two properties ProblemSet and AnswerSet which return the data in two dimensional array as a DataSet. The view is implemented using a DataGrid and the main form for implementing the view is in SudokuMainForm. default: UnMask(3. int number =Int32. Then. private void CurrentSet_ColumnChanging(object sender.SIMPLE: minPos=4. maxPos=5. System. UnMask(minPos.RowNumber.Data.Row. Data validations are handled using the columnchanging event of the DataTable.maxPos. int rowPos = dataGrid1.COMPLEX: minPos=3. } else . break. This method then generates the Dataset from the array and returns to the caller. This retrieval of all sets of data in a single DataSet simplifies the load and save functionality: // Property:GameSet // Return Problem Set as DataSet public DataSet ProblemSet { get{ return FormDataSet().7). noOfSets = 6.ProposedValue as string. the important property is the GameSet that returns the DataSet which is used to bind to the DataGrid. noOfSets=8. GameLevel is of type enum and it defines the complexity levels. string currentNumber = e.maxPos. The DataSet returns three sets of data: ProblemSet. noOfSets= 7. break.noOfSets). UnMask(minPos. Here. break. The following code snippet shows the event handler code: // Handler method for data validations. break. a copy of ProblemSet and AnswerSet.SetColumnError(e. UnMask(minPos. case GameLevel.Text="".} case GameLevel. based on the complexity level.CurrentCell. if((number < 1)||(number >9)) { string errorMessage= "Number should be between 1 and 9". maxPos=5. The InitialiseSet() method generates the unique solution.noOfSets).noOfSets). e. case GameLevel.} } The above property invokes the private method.DataColumnChangeEventArgs e) { try { lblStatus. the Unmask() method will keep some answer spots and create the ProblemSet by clearing other positions. In the above code.6. FormDataSet().maxPos.Column.errorMessage). maxPos=6.Parse(currentNumber).MEDIUM: minPos=3. { int col =e. Load and Save facility for the game. Border for mini 3X3 matrix Since a DataGrid is used for the view. } } } } catch(Exception ex) { e.Row.Column.CurrentCell.col.ProposedValue. The label control is used to show the status of validations and an appropriate message is shown if the solution is complete.CheckForDuplicate(rowPos.Column].Column.CheckForAnswerChange(rowPos.number)){ e. To provide border for each mini-set we need to override the paint method of DataGrid. The error message can be set by setting the e. The user entered value for the cell is available in the event argument property e.col.Row.Row[e. bool answerComplete= IsSolutionComplete(). 3.Row. e. Spinner text control when you edit a particular cell to enter a number between 1 and 9. The following code snippet shows the code in overloaded method: .RowNumber property. either the grid style of each cell can be customized or the border of the Datagrid can be changed. I have used the timer control to show the answer for a few seconds and then to redisplay the problem.Text= "Great!!! You have done it".Text="You can't change the answer". New enhancements Based on the suggestions from readers I have amended the program with the following enhancements: 1. }else if(_newGame.SetcolumnError property. to distinguish it clearly from other mini-sets. bool answerChanged = _newGame.ProposedValue = e.Ordinal. 4. if(answerChanged) { lblStatus.SetColumnError(e. if(answerComplete) { lblStatus.Column.ClearErrors(). "Enter valid Number between 1 & 9"). This property is converted to a number and then all data validations are performed by calling CheckForAnswerChangd() and CheckForDuplicate() methods of the Sudoku class.Row.SetColumnError(e. }else { e."Number is Duplicate"). } } The above code first reads the current row position of the cell using the datagrid1. This will enable the user to continue the game at a later time. Answer spots are now read-only.number). The handler also checks whether the solution is complete by invoking IsSolutionComplete() method. Border for each mini 3X3 matrix. 2. // On edit. currentPoint. instantText.TrimEnd()!="") { // Get Column position . The code snippet for the edit method is given below. rowNum. One is DataGridTextBoxColumn and the other is DataGridBoolColumn.DrawRectangle(myPen.Drawing. bool cellIsVisible) { //Call base method which is important else //edit will not function properly base. bounds. This is done to reuse the basic properties and methods implemented by this class and to enhance some of its methods required for this custom column. Microsoft . Also. Size size = new Size(PREFERRED_COLUMN_WIDTH*3.X = i*PREFERRED_ROW_HEIGHT*3. System. } } } DataGridSpinnerColumn Features 2 and 3 mentioned above are provided by implementing a custom DataGrid column.0). e./// DataGrid Paint overriden to paint border private void DataGrid1_Paint(object sender.Edit(source.Graphics. refer to the MSDN documentation.Red. I have used vertical scrollbar control which will act as spinner control. bool readOnly. string instantText.Y = j*PREFERRED_ROW_HEIGHT*3. I have implemented a DataGridSpinnerColumn class for DataGridSpinnerColumn and it is derived from DataGridTextBoxColumn. for(int i=0.Windows.PaintEventArgs e) { // Override this handler to do custom painting. which is an abstract class. and display combobox protected override void Edit(System.3).CurrencyManager source. Pen myPen = new Pen(Color. System. add scroll event handler. Rectangle rect = new Rectangle(currentPoint. int rowNum.Rectangle bounds.size). cellIsVisible).rect). For more information on DataGridColumnStyles. Point currentPoint = new Point(0. readOnly. A custom DataGrid column needs to be derived from DataGridColumnStyle.Forms.TextBox.i++) { for(int j=0.i<3. the answer spots should be read only. The main requirement is that when we edit the cell it should display the custom spinner column so that the user can use scroll buttons to change the cell value and when the focus goes to the other cell then the value should be displayed in the cell. This is because showing the spinner control is done by overriding the edit method which in turn checks whether the cell under edit is the answer spot. PREFERRED_ROW_HEIGHT*3).NET Framework provides two types of custom columns which are derived from this class.Forms. // Check if cell is not empty if(this.Windows.j++) { currentPoint. Because of this feature the custom column is not general purpose and cannot be used as is in other applications.Text.j<3. If the cell does not contain the answer spot then only the spinner control is displayed. rect. Load and save I have re-factored the sudoku class to provide this facility. if(!_answerPostion) { // Make parent of scrollbar same as parent.TextBox.Show(). } _answerPostion =false. The properties ProblemSet and AnswerSet are now replaced by the GameSet property. // Make the scrollbar visible and place on top textbox control this.vsBar.Parent = this.vsBar.ReadOnly=true. Rectangle rect = this.MappingName. int pos = this.vsBar.TextBox.vsBar.Parent. // As textbox control also there let us bring this to front. // Check whether it is answer spot.GetCurrentCellBounds(). this.Value.Substring(pos+3). } if (!readOnly && cellIsVisible) { // Save current row in the DataGrid and currency manager // associated with the data source for the DataGrid this.} else { int dataValue = Int32. this. this.Parse(this.White. //Place this control to right.ToString().vsBar.SpinnerWidth.ForeColor=Color. this.cm = source. _answerPostion=_game. if(pos > -1) { string colIndex = this.BringToFront(). Please refer to the source code for full implementation of this class.Size = new Size(this. this._currentRow = rowNum.vsBar.SpinnerWidth.vsBar.CheckIfAnswerPosition(rowNum. this. this.DataGridTableStyle. colPos.TextBox. //Set text color properties different as we are editing cell.Black. } else { } } } this.Location = new Point(rect.TextBox. .ReadOnly=true. this.DataGrid.Text). int colPos = Int32.dataValue).TextBox.this.Top).Show().TextBox.LastIndexOf("col").BackColor = Color.White. // this.Parse(colIndex).ForeColor =Color.TextBox.BackColor=Color.TextBox.Text= this.Right-this.TextBox.Blue.MappingName.Height). this. this. this.TextBox. .com. then please contact me at gokuldasc@yahoo. I am currently working as Senior Consultant for Infor. A list of licenses authors might use can be found here Share About the Author Gokuldas Software Developer (Senior) United Kingdom I am Solution Architect with 20+ years of IT experience in the field of real time. You can download the full source code using the link provided at the top. You may also be interested in.This will enable us to get all sets of data in a single DataSet.client/server and web based applications and Business Intelligence .NET. l hope you will enjoy this article and the new enhancements to this game. Sudoku Solver and Generator . This code is easy and hence not described here.embedded.. Good Luck !!! 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 you have any suggestions or difficulties. I have used ReadXml() and WritXml() methods of the DataSet class for implementing the load and save functionalities. Conclusion You have seen that how easy it is to implement this game in C# using the power of Microsoft . Also I have exposed the InitialiseGameSet() method to initialize all the data members of sudoku class once the DataSet is loaded from the XML file. If in doubt please contact the author via the discussion board below. com/Articles/12473/Sudoku-Game-in-C to post and view comments on this article. 1999-2016 .codeproject. Permalink | Advertise | Privacy | Terms of Use | Mobile Web02 | 2. or click here to get a print view with messages.1 | Last Updated 25 Dec 2005 Select Language ▼ Article Copyright 2005 by Gokuldas Everything else Copyright © CodeProject.160418.018 seconds Realtime Webcam Sudoku Solver Your Guide to Modern Dev/Test Complete Sudoku Game in C#/WPF/Silverlight How-To Intel® IoT Technology Code Samples: Robot arm in C++ Comments and Discussions 17 messages have been posted for this article Visit http://www.Sudoku Algorithm: Generates a Valid Sudoku in 0.8.
Copyright © 2024 DOKUMEN.SITE Inc.