在 vb.net 中保存和加载游戏

Posted

技术标签:

【中文标题】在 vb.net 中保存和加载游戏【英文标题】:Saving and loading a game in vb.net 【发布时间】:2014-10-20 23:04:17 【问题描述】:

我是否可以比以前更轻松地保存或加载游戏?

保存代码

Dim file As System.IO.StreamWriter
file = My.Computer.FileSystem.OpenTextFileWriter("c:\Pugio Cadite\CharacterInformation.txt", True)
file.WriteLine(charactername)
file.WriteLine(characterrace)
file.WriteLine(characterclass)
file.WriteLine(characterGender)
file.WriteLine(charactergold)
file.WriteLine(characterlevel)
file.Close()

而且我还没有写加载函数。

【问题讨论】:

你可以使用序列化。将所有这些存储在一个类中,然后使用内置的序列化/反序列化方法。 这取决于保存的内容,但serialization 可以工作 【参考方案1】:
Imports System.Xml.Serialization

Public Class Form1
  Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    'save the program variables
    Dim p As New ProgramVars
    p.Prop1 = "1"
    p.Prop2 = "2"
    p.Prop3 = "3"
    p.Prop4 = "4"
    Dim strFilename As String = "C:\Junk\Junk.xml"
    p.Save(strFilename)

    'load them into a different object
    Dim p2 As ProgramVars = ProgramVars.Load(strFilename)
    MsgBox(p2.Prop3)

  End Sub
End Class

<Serializable>
Public Class ProgramVars
  Property Prop1 As String
  Property Prop2 As String
  Property Prop3 As String
  Property Prop4 As String
  Sub Save(filename As String)
    Using fs As New System.IO.FileStream(filename, IO.FileMode.OpenOrCreate)
      Dim xs As New XmlSerializer(GetType(ProgramVars))
      xs.Serialize(fs, Me)
    End Using
  End Sub

  Shared Function Load(filename As String) As ProgramVars
    Using fs As New System.IO.FileStream(filename, IO.FileMode.OpenOrCreate)
      Dim xs As New XmlSerializer(GetType(ProgramVars))
      Return xs.Deserialize(fs)
    End Using
  End Function
End Class

【讨论】:

以上是关于在 vb.net 中保存和加载游戏的主要内容,如果未能解决你的问题,请参考以下文章

在 VB.net 中保存设置的最简单方法是啥

VB.NET和C++之间的区别

如何从谷歌玩游戏中选择和加载保存的游戏快照

如何在pygame中保存/加载游戏功能?

如何在 cocos2d iphone 游戏中保存高分和加载高分

将抽象数据类型保存和加载到 json 文件并从游戏中的文件中读取 Haskell