只要玩家仅单击不匹配的图标对,游戏即可顺畅地运行。但是,请考虑玩家单击匹配对时应发生的情况。游戏不是通过打开计时器(使用 Start() 方法)来使图标消失,而应当进行重置,这样游戏就不再使用 firstClicked 和 secondClicked 引用变量跟踪任何标签,而且无需重置两个已单击过的标签的颜色。
保持对可见
将下面的 if 语句添加到 label_Click() 事件处理程序方法的尾部附近,紧靠启动计时器的语句的上方。将代码添加到程序时,请仔细查看一下代码。考虑代码如何运行。
' If the player gets this far, the timer isn't ' running and firstClicked isn't Nothing, ' so this must be the second icon the player clicked ' Set its color to black secondClicked = clickedLabel secondClicked.ForeColor = Color.Black ' If the player clicked two matching icons, keep them ' black and reset firstClicked and secondClicked ' so the player can click another icon If (firstClicked.Text = secondClicked.Text) Then firstClicked = Nothing secondClicked = Nothing Return End If ' If the player gets this far, the player ' clicked two different icons, so start the ' timer (which will wait three quarters of ' a second, and then hide the icons) Timer1.Start() End If End Sub
// If the player gets this far, the timer isn't // running and firstClicked isn't null, // so this must be the second icon the player clicked // Set its color to black secondClicked = clickedLabel; secondClicked.ForeColor = Color.Black; // If the player clicked two matching icons, keep them // black and reset firstClicked and secondClicked // so the player can click another icon if (firstClicked.Text == secondClicked.Text) { firstClicked = null; secondClicked = null; return; } // If the player gets this far, the player // clicked two different icons, so start the // timer (which will wait three quarters of // a second, and then hide the icons) timer1.Start(); } }
您刚添加的 if 语句的第一行检查玩家单击的第一个标签中的图标是否与第二个标签中的图标相同。如果图标相同,则程序执行 C# 中大括号之间的三个语句或 Visual Basic 中 if 语句内的三个语句。前两个语句重置 firstClicked 和 secondClicked 引用变量,使它们不跟踪任何标签。(您可以从计时器的 Tick 事件处理程序识别这两个语句。)第三个语句是返回语句,它通知程序跳过方法中的其余语句,不执行它们。
如果使用 Visual C# 编程,您可能已注意到某些代码使用单个等号 (=),而其他语句使用双等号 (==)。请考虑为什么在某些位置使用 =,但在其他位置使用 ==。
以下是一个显示该区别的很好的示例。请仔细查看 if 语句括号之间的代码。
firstClicked.Text = secondClicked.Text
firstClicked.Text == secondClicked.Text
再仔细查看 if 语句后的代码块中的第一个语句。
firstClicked = Nothing
firstClicked = null;
这两个语句中的第一句检查两个图标是否相同。因为要比较两个值,所以 Visual C# 程序使用 == 相等运算符。第二个语句实际上更改值(称为“赋值”),将 firstClicked 引用变量设置为等于 null 以重置它。这就是使用 = 赋值运算符的原因。Visual C# 使用 = 设置值,使用 == 比较值。而,Visual Basic 将 = 既用于赋值,也用于比较。
保存并运行程序,然后开始在窗体中单击。如果单击的是不匹配的对,则将触发计时器的 Tick 事件,两个图标都会消失。如果单击的是匹配的对,则将执行新的 if 语句,而返回语句会使方法跳过启动计时器的代码,因此图标保持可见,如下图所示。
具有可见图标对的匹配游戏
继续或查看
若要转到下一个教程步骤,请参见步骤 8:添加方法以验证玩家是否获胜。
若要返回上一个教程步骤,请参见步骤 6:添加计时器。