缩短长 if 语句 [英] Shorting long if statement

查看:33
本文介绍了缩短长 if 语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我花了几个小时制作井字游戏,主要使用 if else 语句,我只是复制和粘贴了一些代码......

I have spent hours making a tic tac toe game just using mainly if else statements, some of the code I just copy and pasted...

我如何只创建代码的一个实例,然后稍后再引用它?- 当我需要该代码时,而不是每次都复制和粘贴大量代码行.在这段代码中,我得到一个 1 到 10 之间的随机数,这个数字将存储在 RI 中……然后当轮到 Ai 时,计算机将在按钮中随机输入一个 X,然后使用此代码它会检查确定计算机是否获胜.我希望这是有道理的 =)

How would I just create one instance of the code, then refer to it later on? - when I need that code, instead of just copy and pasting massive lines of code each time. In this block of code, I am getting a random number between 1 to 10 this number will be stored in RI... then when it's Ai's turn the computer will randomly input an X in the button, then using this code it will check to determine if the computer has won. I hope that make sense =)

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 次的一些代码,它只是让我的代码看起来很丑陋,很难阅读.

for example this code, is some of the code, that I have copied atleast 10 times, and it just makes me code look ugly and really hard to read.

推荐答案

例如这段代码,是我复制了至少 10 次的一些代码

for example this code, is some of the code, that I have copied atleast 10 times

任何时候你复制了代码,你都应该尝试把它移到一个方法中.然后您可以直接调用该方法.在你的例子中,一个方法可以很容易地接受三个按钮来影响,并直接处理它们.

Any time you have copied code, you should try to move it into a method. You can then just call the method directly. In your case, a method could easily accept the three buttons to affect, and work on them directly.

这篇关于缩短长 if 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆