VB-使用上一个表单的结果时,将分数增加或将生命值减少1



这是在Windows窗体应用程序中完成的

当它使用上一个表单的分数时,我如何使这个代码增加分数或减少生命1。

第一个表单有分数,并且作为一个集值存在,它可以删除或添加到该集值上,但是第二个表单使用的是第一个表单的标签,该标签具有第一组代码的结果,我需要它删除1的生命或增加1的分数,但我不确定在第二个窗体上使用什么代码来实现这一点。我想我只需要增加数字,但我不知道怎么增加。

这是来自第一个表单的代码:

Dim score As Integer = 0
Dim lives As Integer = 3
If RadioButton3.Checked Then
score = score + 1
Label3.Text = "Score: " & score
Me.Hide()
Question2.Show()
ElseIf RadioButton1.Checked Then
lives = lives - 1
Label2.Text = "Lives: " & lives
Me.Hide()
Question2.Show()
ElseIf RadioButton2.Checked Then
lives = lives - 1
Label2.Text = "Lives:" & lives
Me.Hide()
Question2.Show()
ElseIf RadioButton4.Checked Then
lives = lives - 1
Label2.Text = "Lives:" & lives
Me.Hide()
Question2.Show()
End If
Question2.Label3.Text = Label3.Text
Question2.Label2.Text = Label2.Text

第二个我有问题:

Dim score As Integer
Dim lives As Integer
If RadioButton2.Checked Then
score = score + 1
Label3.Text = "Score: " & score
Me.Hide()
Question3.Show()
ElseIf RadioButton1.Checked Then
lives = lives - 1
Label2.Text = "Lives: " & lives
Me.Hide()
Question3.Show()
ElseIf RadioButton3.Checked Then
lives = lives - 1
Label2.Text = "Lives:" & lives
Me.Hide()
Question3.Show()
ElseIf RadioButton4.Checked Then
lives = lives - 1
Label2.Text = "Lives:" & lives
Me.Hide()
Question3.Show()
End If
Question3.Label3.Text = Label3.Text
Question3.Label2.Text = Label2.Text

我猜问题在于您将数值存储在控件的.Text属性的标签中,这些属性的类型为String。代码

Label3.Text = "Score: " & score

令人不安的是;运算符连接两个字符串,而"Score:"实际上是一个字符串,但Score是一个Integer。将选项Option Strict On放在代码填充的顶部会提醒您,这不是正确的做事方式。正确的方法是

Label3.Text = "Score: " & score.ToString()

但这并不能解决你的问题。

因此,问题在于,从一个表单到另一个表单都可以访问的公共变量是标签中的.Text属性,它包含字符串值"Score:3"(或任何分数),因此很难提取分数。你可以做一个字符串操作来提取它,因为你知道你把"Score:"放在数字分数前面,你可以用"代替它,然后转换成整数:

Dim scoreIn3 As Integer = Integer.Parse(Question2.Label3.Text.Replace("Score: ", ""))

这一行可以在问题3中使用,以从问题2中提取分数。你可以看到,提取分数的方法很复杂,但这是你设计的产品。这可能是一个小项目,不需要太多的设计考虑,但对于任何严肃的项目,您都应该考虑使用类和对象来存储数据,以及仅用于显示和输入的表单。希望这能有所帮助。

我还建议您可以使用以下内容:

Public Shared score As Integer
Public Shared lives As Integer

它需要放置在sub之外,但在form类内部这样,它们就可以被通过以下任何形式的方法申请:

Form_Name.score = number
Form_Name.lives = number

同样,当你这样做的时候,你只需要在一个表格上声明它可以在所有中使用

一个小技巧,可以将代码缩短一点,而不是使用像lives = lives + 1lives = lives - 1这样的东西,你可以使用lives -= 1lives += 1来获得同样的效果——稍微短一点的书写方式。它也适用于其他方程,如乘法和除法,只需改变=后面的符号,如lives *= 5lives /= 5,仅用于乘以或除以5 的示例

最新更新