-2

How do I save a 4x4 array and a single integer to a file in visual basic?

I am making 2048 in visual basic. I have a 4x4 array called "Grid" and an integer variable called score. I wish to be able to save my game and continue where I left off. How would I save the contents of the array to a file and then load it back in, along with the score?

Community
  • 1
  • 1
Edmund Osborne
  • 9
  • 1
  • 1
  • 1

1 Answers1

5

Here's an example of how to create a txt file with a grid and load it.

You need to tailor this to your need, especially the return from LoadTxtFile which is an Array of text strings.

Save

Sub SaveInTxtFile(Optional grid As Variant)

If IsMissing(grid) Then
    grid = Array(Array("test00", "test01"), Array("test10", "test11"), Array("test20", "test21"))
End If

'create object for file system
Dim fsobj As Object
Set fsobj = CreateObject("Scripting.FileSystemObject")

'your path and name of text file to save
strPath = "C:\yourPath\"
strFileName = "gridSave.txt"

'create text file object
Dim txtFile As Object
Set txtFile = fsobj.CreateTextFile(strPath & strFileName)

    'populate file with grid
    For n = 0 To UBound(grid)
        txtFile.WriteLine grid(n)(0) & "," & grid(n)(1)
    Next
    txtFile.Close

'set objects to nothing
Set fsobj = Nothing
Set txtFile = Nothing

End Sub

Load

Function LoadTxtFile() As Variant

'variant to hold strings
Dim gridStr As Variant
ReDim gridStr(0)
Dim i As Integer
i = 0

    'open text file
    Open "C:\yourPath\gridSave.txt" For Input As #1
    'while not End Of File
    Do While Not EOF(1)
        'input current line of text to gridStr
        Line Input #1, gridStr(i)
        'increase gridStr to hold more variables/strings of text
        i = i + 1
        ReDim Preserve gridStr(i)
    Loop
    Close #1

'function return grid
LoadTxtFile = gridStr

End Function

For more information you can see examples here:
How to create a .txt
Reading a .txt file

And documentation here:
File System Object
Reading and Writing Text Files

Miguel_Ryu
  • 1,390
  • 3
  • 18
  • 26