【问题标题】:Button should change text every two presses按钮应每两次按下更改文本
【发布时间】:2014-09-03 19:08:14
【问题描述】:

我正在尝试使用 Visual Basic 创建一个井字游戏。按下按钮后,按钮应首先变为“O”,然后下一次按下应为“X”,但它似乎继续放置“O”。

    Dim turn As Boolean
    turn = True 'true = X turn, false = Y turn
    Dim b As Button

    b = DirectCast(sender, Button)
    If (turn) Then
        b.Text = "O"
    Else
        b.Text = "X"
        turn = Not turn <<< This seems to not to be working...

        b.Enabled = False
    End If

【问题讨论】:

  • 转身声明在哪里?在类或函数中?听起来它应该是一个类/表单变量,所以每次按下按钮时都不会重新创建它。

标签: vb.net


【解决方案1】:

需要在方法外声明turn变量,使其成为类的成员,而不是每次都重新创建的局部变量。

此外,您应该在每次更改后翻转状态,不仅是在放置 X 时,在禁用按钮时也是如此。

例子:

Dim turn As Boolean = True 'true = X turn, false = Y turn

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

  Dim b As Button = DirectCast(sender, Button)

  If turn Then
    b.Text = "O"
  Else
    b.Text = "X"
  End If

  turn = Not turn
  b.Enabled = False
End Sub

【讨论】:

  • 我在那里看到了 C# 的痕迹 ;)
  • 或者,如果在点击处理程序之外不需要turn,则可以在其中将其声明为Static 变量。
  • @the_lotus 由于 Guffa 似乎被占用了,我已经删除了 C# 的痕迹。你也可以这样做;)
  • 感谢您的编辑。只是在方法声明中有 C# 代码,其余的实际上来自原始代码。 :)
猜你喜欢
  • 2018-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多