Create a Sudoku Puzzle Generator using VB.NET - Saving and Loading Puzzles
(Page 4 of 6 )
Sometimes you might not be able to solve a puzzle at one sitting. That’s where the application’s save and load features come in handy. The Save()(see Listing 3) and Load()methods assist in this endeavor.
Listing 3 Save a puzzle to disk
Public Sub Save(ByVal szSaveFilePath As String)
'This method accepts the full path and name of a file to save the contents
'of the 9x9 2-dimensional byte arrays holding the puzzle's current state and
'solution. In addition, the selected complexity is saved in the 1st element (0,0)
'of the puzzle's current state array. Note that a vanilla binaryformatter is used
'to serialize the array contents to a file.
'
Dim oFS As FileStream
Dim oFormatter As IFormatter
Dim szBaseFileName As String
Dim szBaseFilePath As String
Dim szBaseFileExt As String
Try
szBaseFileName = Path.GetFileNameWithoutExtension(szSaveFilePath)
szBaseFileExt = Path.GetExtension(szSaveFilePath)
szBaseFilePath = Path.GetDirectoryName(szSaveFilePath)
If Not szBaseFilePath.EndsWith("") Then szBaseFilePath &= ""
oFormatter = New Formatters.Binary.BinaryFormatter
'Save original SudokuBoard
oFS = New FileStream(szBaseFilePath & szBaseFileName & szBaseFileExt, _
FileMode.OpenOrCreate, FileAccess.Write)
oFormatter.Serialize(oFS, mbyary_OrgSudokuBoard)
oFS.Close()
'Save current SudokuBoard
oFS = New FileStream(szBaseFilePath & szBaseFileName & _
szBaseFileExt.Substring(0, 3) & "1", FileMode.OpenOrCreate, FileAccess.Write)
oFormatter.Serialize(oFS, mbyary_SudokuBoard)
Catch ex As Exception
If File.Exists(szBaseFilePath & szBaseFileName & ".*") Then
File.Delete(szBaseFilePath & szBaseFileName & ".*")
End If
Finally
If Not (oFS Is Nothing) Then oFS.Close()
oFS = Nothing
oFormatter = Nothing
End Try
End Sub
Both methods incorporate BinaryFormatters and FileStreams to de/serialize both puzzle arrays from and to disk. BinaryFormatters provide a way to take an object and break it up into a linear sequence of bytes, thereby making it easy to store and retrieve. The contents of the arrays are saved to and consequently loaded from two separate files. The UI supplies the name of the files to save/load by calling upon the easy-to-use SaveFileDialog and OpenFileDialog dialog boxes. As mentioned previously, the puzzle’s complexity is always saved within the mbyary_SudokuBoard array. During a load request, the UI code retrieves this value from the appropriate array element and uses it to properly set the loaded puzzle’s complexity in the File > New menu.
Next: Solving Puzzles >>
More Visual Basic.NET Articles
More By Pete Rodriguez