创建一组控件

本文关键字:一组 控件 创建 | 更新日期: 2023-09-27 18:27:59

我今天在玩游戏时遇到了一个小问题。。。问题是我在1毫秒计时器上运行了这种情况:

if (jump == true && 
    jumped == 0 && 
   (Player.Location == new Point(Player.Location.X, Block1.Location.Y - Player.Height) || 
    Player.Top == this.Height - Player.Height))
{
   do something...
}

"区块1"是游戏中的一个对象(图片框),我需要10、20甚至100个以上具有相同条件的区块,那么我该如何简化它呢?这将是一个条件下的50行甚至更多行。基本上,我想知道是否有一种方法可以将所有"块"(pictureboxes)混合到一个组(命名的块)中,或者我仍然可以使用Blocks.Location.Y等访问

创建一组控件

IMO,这一次检查中有太多条件。我会将它们分解,然后以独立的方式处理每个条件,这将使事情在未来更容易调试和阅读/理解。

// Too much going on here; let's refactor.
if (jump == true 
    && jumped == 0 
    && (Player.Location == new Point(Player.Location.X, Block1.Location.Y - Player.Height) 
        || Player.Top == this.Height - Player.Height))
{
   //do something...
}

与其创建一个大的if语句,不如将条件拉到一个方法中:

// first refactor
private bool IsValidForSomeAction()
{
    if(!jump)
    {
        return false;
    }
    if(jumped != 0)
    {
        return false;
    }
    if(Player.Top == this.Height - Player.Height)
    {
        return true;
    }
    if (Player.Location == new Point(Player.Location.X, Block1.Location.Y - Player.Height))
    {
       return true;
    }
    return false;
}

在第一次refator之后,很明显没有必要为最终比较创建新的点:

// second refactor
private bool IsValidForSomeAction()
{
    if(!jump)
    {
        return false;
    }
    if(jumped != 0)
    {
        return false;
    }
    if(Player.Top == this.Height - Player.Height)
    {
        return true;
    }
    // only the Y location matters, no need to create a new Point for the comparison.
    if (Player.Location.Y == Block1.Location.Y - Player.Height)
    {
       return true;
    }
    return false;
}

现在,让我们关注真正重要的内容:if (Player.Location.Y == Block1.Location.Y - Player.Height)。这种情况可以归结为区块的Y位置和玩家高度之间的差异。

假设可能有10个、20个、50个或100多个块要比较,则创建包含所有块的集合的私有字段。

// override the onload event and find all the picture boxes:
private readonly List<PictureBox> _boxes = new List<PictureBox>();
protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);    
    _boxes.AddRange(this.Controls.OfType<PictureBox>()
}

_boxes字段可用于最终验证:

// third refactor
private bool IsValidForSomeAction()
{
    if(!jump)
    {
        return false;
    }
    if(jumped != 0)
    {
        return false;
    }
    if(Player.Top == this.Height - Player.Height)
    {
        return true;
    }
    // only the Y location matters, no need to create a new Point for the comparison.
    if(_boxes.Any(x => x.Location.Y - Player.Height == Player.Location.Y)
    {
        return true;
    }
    return false;
}