如何在Visual Basic中将4x4数组和单个整数保存到文件中?
我在视觉基础上制作2048。我有一个名为“Grid”的4x4数组和一个名为score的整数变量。我希望能够保存我的游戏并继续我离开的地方。如何将数组的内容保存到文件中,然后将其与分数一起重新加载?
答案 0 :(得分:2)
以下是如何使用网格创建txt文件并加载它的示例。
你需要根据需要定制它,特别是从LoadTxtFile
返回,这是一个文本字符串数组。
保存强>
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
<强>加载强>
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
有关详细信息,请参阅此处的示例:
How to create a .txt
Reading a .txt file