多次为相同的表达式设置相同的值

时间:2018-08-20 23:54:09

标签: vb.net

我正在制作一个简单的游戏式程序。它运行良好,是我编写的更复杂的程序之一,也是我多年来尝试的第一个程序。

我正在尝试构建一个常数表达式,该常数表达式将根据其使用位置而变化。问题是我不记得/我不确定我需要使用什么。 我目前实质上是对该程序进行硬编码以避免错误,相关代码目前位于:

Dim FangOwned

Private Sub PnlFangKnife_Click(sender As Object, e As EventArgs) Handles PnlFangKnife.Click

    GoldNeeded = 12

    If GP = GoldNeeded And FangOwned = False Then
        GP -= GoldNeeded
        LblGoldInt.Text = GP
        LblFangInt.Text = "Owned"
        FangOwned = True
        PnlFangKnife.BorderStyle = BorderStyle.Fixed3D

    Else


    End If

End Sub

等等等等

问题在于,玩家目前有四种武器可供购买。所以我必须为每种武器声明一个新的整数;

Dim FangOwned

Dim CrudeOwned

Dim ElvenOwned

Dim MagicOwned

并且基本上为每个声明写出相同的编码,并且在相关按钮内有重叠等。用法变得非常复杂...我可以做到,但我更希望使用一种更简单的方法来实现基本相同的效果。

请记住,我实际上几年都没有编码,有人可以在这里帮助我吗? 我可以使用哪种类型的声明来简化此问题?

理想情况下,我希望我可以写些东西:

Dim TheIdealDeclaration

PrivateSub Button1_Click

    If TheIdealDeclaration = False then

        TheIdealDeclaration = True

    End If

End Sub

PrivateSub Button2_Click

    If TheIdealDeclaration = False Then

        TheIdealDeclaration = True

     End If

End Sub

(并且没有这两个冲突)

1 个答案:

答案 0 :(得分:0)

说实话,除非您想使游戏变得更复杂,否则您应该保持原样。就目前的代码而言,只有避免重复代码,这才会使事情变得不必要地复杂,因为您需要添加代码来确定要更改属性的LabelPanel的。

如果您想添加更多武器和更多属性,例如其造成的伤害或是否有可能遭受额外伤害等,那么我会认真考虑创建一个Weapon类,并考虑重新设计您的界面。

一种可能的方法是类似..

Private Sub BuyWeapon(ByRef weapon As Boolean, ByRef goldOwned As Integer, cost As Integer, lbl As Label, pnl As Panel)
    If goldOwned >= cost And weapon = False Then
        goldOwned -= cost
        LblGoldInt.Text = goldOwned.ToString
        lbl.Text = "Owned"
        weapon = True
        pnl.BorderStyle = BorderStyle.Fixed3D
    Else


    End If
End Sub

您有一个名为BuyWeapon的子项,该子项可以获取有关哪种武器,您拥有多少金币,成本多少以及要更改的控制权的参数。

然后,您的代码将如下所示。

Dim FangOwned As Boolean

Dim CrudeOwned As Boolean

Dim ElvenOwned As Boolean

Dim MagicOwned As Boolean

Dim GP As Integer

Private Sub BuyWeapon(ByRef weapon As Boolean, ByRef goldOwned As Integer, cost As Integer, lbl As Label, pnl As Panel)
    If goldOwned >= cost And weapon = False Then
        goldOwned -= cost
        LblGoldInt.Text = goldOwned.ToString
        lbl.Text = "Owned"
        weapon = True
        pnl.BorderStyle = BorderStyle.Fixed3D
    Else


    End If
End Sub

Private Sub BtnBuyFangKnife_Click(sender As Object, e As EventArgs) Handles BtnBuyFangKnife.Click
    BuyWeapon(FangOwned, GP, 12, LblFangInt, PnlFangKnife)
End Sub

Private Sub BtnBuyCrudeKnife_Click(sender As Object, e As EventArgs) Handles BtnBuyCrudeKnife.Click
    BuyWeapon(CrudeOwned, GP, 20, LblCrudeInt, PnlCrudeKnife)
End Sub