Search code examples
c#linqcollision-detection

struggling to understand code written for me by my tutor, for arknoid/brickbreaker collision detection


I asked a third year student to help me detect collisions for the game, I've tried understanding the order but the last 20 or so lines don't make much sense to me, would anyone by willing to make it a bit more cleaner?

Specifically I need to understand what the code means from the keyword "Where". Any improvements that can be made to the code would be appreciated.

UIElement upDownBlock = MyGrid.Children.Cast<Rectangle>().Where(i => (Grid.GetRow(i) == ballRow + vely) && (Grid.GetColumn(i) == ballColumn)).FirstOrDefault();
if (upDownBlock != null)
{
    vely = -vely;
    MyGrid.Children.Remove(upDownBlock);
}
UIElement leftRightBlock = MyGrid.Children.Cast<Rectangle>().Where(i => (Grid.GetColumn(i) == ballColumn + velx) && (Grid.GetRow(i) == ballRow)).FirstOrDefault();
if (leftRightBlock != null)
{
    velx = -velx;
    MyGrid.Children.Remove(leftRightBlock);
}

any sort of help would be appreciated, game was created on a grid


Solution

  • As I said in my comment, you need to learn linq and your mentor needs to use better naming. Does this seem more understandable?

    Rectangle upDownBlock = MyGrid.Children.Cast<Rectangle>()
                              .Where(rect => (Grid.GetRow(rect) == ballRow + vely) && 
                                             (Grid.GetColumn(rect) == ballColumn))
                             .FirstOrDefault();
    if (upDownBlock != null)
    {
        vely = -vely;
        MyGrid.Children.Remove((UIElement)upDownBlock);
    }
    

    Basically the code in the Where clause is run against the various lists of rectangles, it evaluates to either true or false and the first rectangle that matches (evaluates to true) is returned.

    An improvement would be to replace the “Where” with “FirstOrDefault” in the various assignments. This does not increase performance as you might expect, lazy evaluation means that the Where clause only evaluates the items requested, and FirstOrDefault will stop asking it to evaluate items when it finds its first match. But it makes it clearer earlier that you don’t care about the whole list of rectangles, just the first one to match your criteria aka predicate.