如何在 Visual Basic 中将 4x4 数组和单个整数保存到文件中?
我正在 Visual Basic 中制作 2048。我有一个名为“Grid”的 4x4 数组和一个名为 score 的整数变量。我希望能够保存我的游戏并从我停止的地方继续。我如何将数组的内容保存到一个文件中,然后将它连同分数一起加载回来?
下面是一个示例,说明如何创建带有网格的 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
Run Code Online (Sandbox Code Playgroud)
加载
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
Run Code Online (Sandbox Code Playgroud)
有关更多信息,您可以在此处查看示例:
How to create a .txt
Reading a .txt file
| 归档时间: |
|
| 查看次数: |
9024 次 |
| 最近记录: |