Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need for loop to check 2 conditions before continuing

I'm currently developing a "Sokoban" game at a very basic level. I'm trying to make this for loop but cannot seem to complete it. My aim is to carry out an example of the movement code below, I feel my syntax is wrong in regards to adding another condition where it says "(diamondlist.Count) & (Playerlist.Count). The error I am getting is "Operator '&' cannot be applied to operands of type 'bool' and 'int'. I have tried to add double "&&" and this does not solve it eitheir, any help is appreciated - thanks :D

    protected override void Update(GameTime gameTime)
    {
        for (int i = 0; i < (diamondlist.Count) & (Playerlist.Count); i++)
        {
            if ((Playerlist[i].Position == diamondlist[i].Position) && kb_old.IsKeyDown(Keys.W))
            {
                if (currentMap.isWalkable(new Point(diamondlist[i].m_position.X, diamondlist[i].m_position.Y - 1)))
                    diamondlist[i].m_position.Y--;
            }
like image 742
Craig Thomson Avatar asked Dec 01 '22 21:12

Craig Thomson


2 Answers

What about simplifying your test condition ?

int maxValue = System.Math.Min(diamondlist.Count,Playerlist.Count);
for (int i = 0; i < maxValue; i++)
like image 26
Steve Avatar answered Dec 04 '22 03:12

Steve


There are a few problems.

  1. The expression i < (diamondlist.Count) & (Playerlist.Count) is evaluated as:

    (i < diamondlist.Count) & Playerlist.Count
    

    The first part of the expression (i < diamondlist.Count) is a bool, but the second part (Playerlist.Count) is an int. It's complaining because the & doesn't accept two different types like that.

  2. You are then trying to apply & which (for integers) is a bitwise AND operator. This would work if both types were the same, but it can lead to spend unnecessary CPU cycles and is not typically used in Boolean expressions. You probably want to use && -- the logical or conditional and operator.

Try this instead:

for (int i = 0; i < diamondlist.Count && i < Playerlist.Count; i++)
{
    ...
}
like image 185
p.s.w.g Avatar answered Dec 04 '22 03:12

p.s.w.g