0

我总是能够在这里搜索我需要的东西,而且我通常很容易找到它,但这似乎是一个例外。

我正在用 Visual Basic 2010 Express 编写一个程序,这是一个相当简单的基于文本的冒险游戏。

我有一个故事,根据您选择的按钮/选项有多种可能的路径。每个故事路径的文本都保存在其自己的嵌入式资源 .txt 文件中。我可以直接将文本文件的内容写入 VB,这样可以解决我的问题,但这不是我想要这样做的方式,因为那样最终看起来会非常混乱。

我的问题是我需要在我的故事中使用变量名,这是一个嵌入文本文件内容的示例,

"When "+playername+" woke up, "+genderheshe+" didn't recognise "+genderhisher+" surroundings."

我已使用以下代码将文件读入我的文本框中

Private Sub frmAdventure_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim thestorytext As String
    Dim imageStream As Stream
    Dim textStreamReader As StreamReader
    Dim assembly As [Assembly]
    assembly = [assembly].GetExecutingAssembly()
    imageStream = assembly.GetManifestResourceStream("Catastrophe.CatastropheStoryStart.png")
    textStreamReader = New StreamReader(assembly.GetManifestResourceStream("Catastrophe.CatastropheStoryStart.txt"))
    thestorytext = textStreamReader.ReadLine()
    txtAdventure.Text = thestorytext
End Sub

这在一定程度上有效,但在文本文件中完全显示它,保留引号和 +s 和变量名,而不是删除引号和 +s 并将变量名替换为存储在变量中的内容。

谁能告诉我我需要更改或添加什么才能完成这项工作?

谢谢,如果这已经在某个地方得到了回答,而我只是没有认识到它是解决方案,或者不知道要搜索什么来找到它或其他东西,我深表歉意。

4

1 回答 1

1

由于您的应用程序已编译,因此您不能只将一些 VB 代码放在文本文件中并在读取时执行它。

可以做的以及通常做的是将某些标签留在文本文件中,然后找到它们并用实际值替换它们。

例如:

When %playername% woke up, %genderheshe% didn`t recognise %genderhisher% surroundings.

然后在您的代码中,您会找到所有标签:

Dim matches = Regex.Matches(thestorytext, "%(\w+?)%")
For Each match in matches
    ' the tag name is now in: match.Groups(1).Value
    ' replace the tag with the value and replace it back into the original string
Next

当然,大问题仍然存在——即如何填写实际值。不幸的是,没有干净的方法可以做到这一点,尤其是使用任何局部变量。

您可以手动维护一个Dictionary标记名称及其值,也可以使用反射在运行时直接获取值。虽然应该谨慎使用它(速度、安全性......),但它对您的情况非常有用。

假设您将所有变量定义为与Me读取和处理此文本的代码相同的类 () 中的属性,代码将如下所示:

Dim matches = Regex.Matches(thestorytext, "%(\w+?)%")
For Each match in matches
    Dim tag = match.Groups(1).Value
    Dim value = Me.GetType().GetField(tag).GetValue(Me)
    thestorytext = thestorytext.Replace(match.Value, value) ' Lazy code
Next

txtAdventure.Text = thestorytext

如果您不使用属性,而只使用字段,请将行更改为:

Dim value = Me.GetType().GetField(tag).GetValue(Me)

请注意,这个例子很粗略,如果标签拼写错误或不存在,代码会很高兴地崩溃(你应该做一些错误检查),但它应该能让你开始。

于 2013-05-02T12:01:59.283 回答