Search code examples
c#game-enginewindows-forms-designer

How can i check if all my checkers are in the same place?


I need to make a backgammon game. The game is 90% done. I have to make the endgame (when you take out your checkers from the "home" i don't know how it's called in english). I have all the whitecheckers in ArrayPieseAlbe and i'm using a foreach to check if the location match.

public bool SuntToatePieseAlbeCasa()
        {
            foreach (PiesaAlba p in ArrayPieseAlbe)
            {
                return p.Location.X > 503; //503 is the right location 
            }
            return false;

PiesaAlba is the class where the white checkers are. ArrayPieseAlbe contains all the white checkers. For some strange reason this doesn't work as it's supposed to work. It's working when 7 or more checkers are in the "home" but it need for all 15 to be there to work properly. Any advices? Sorry for my bad English


Solution

  • You need to return to true if all of the pieces are "home". Currently, you're returning true if any (i.e. at least one) of the pieces are home.

    To fix this, you're logic should be:

    1. Iterate through each piece and check that it is home
    2. If not, immediately return false
    3. If all pieces have been checked, return true

    This would look something like:

    public bool SuntToatePieseAlbeCasa()
    {
        foreach (PiesaAlba p in ArrayPieseAlbe)
        {
            if (p.Location.X <= 503) //503 is the right location 
            {
                return false;
            }
        } 
        return true;
    }
    

    You could alternatively use the All() method in System.Linq:

    public bool SuntToatePieseAlbeCasa()
    {
        return ArrayPieseAlbe.All(p => p.Location.X > 503);
    }
    

    Looking at the source of All(), it does essentially the same thing as above but uses a predicate to do the check inside of the loop:

    public static bool All<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) {
        if (source == null) throw Error.ArgumentNull("source");
        if (predicate == null) throw Error.ArgumentNull("predicate");
        foreach (TSource element in source) {
            if (!predicate(element)) return false;
        }
        return true;
    }