我花了几个小时制作井字游戏,主要是使用 if else 语句,我刚刚复制和粘贴的一些代码......
我如何只创建一个代码实例,然后再参考它?- 当我需要该代码时,而不是每次都复制和粘贴大量代码行。在这段代码中,我得到一个介于 1 到 10 之间的随机数,该数字将存储在 RI 中……然后轮到 Ai 时,计算机将在按钮中随机输入一个 X,然后使用此代码检查确定计算机是否获胜。我希望这是有道理的=)
do
{
storeRI = rc.Next(0, 10); //storing random number into storeRI so it can be used later on in life.
if (storeRI == 1 && btn1.Text == "")
{
btn1.Text = "X";
Turn = 1;
if (btn1.Text == "X" & btn2.Text == "X" & btn3.Text == "X")
{
btn1.BackColor = Color.Green;
btn2.BackColor = Color.Green;
btn3.BackColor = Color.Green;
XScore += 1;
lblPScoreX.Text = XScore.ToString();
foreach (Button btn in buttonList)
btn.Enabled = false;
}
else if (btn1.Text == "X" & btn4.Text == "X" & btn7.Text == "X")
{
btn1.BackColor = Color.Green;
btn4.BackColor = Color.Green;
btn7.BackColor = Color.Green;
XScore += 1;
lblPScoreX.Text = XScore.ToString();
foreach (Button btn in buttonList)
btn.Enabled = false;
}
}
}
例如,这段代码是一些我至少复制了 10 次的代码,它只是让我的代码看起来很难看,而且很难阅读。