一种获得布尔值来表示1和-1的优雅方法

本文关键字:方法 表示 一种 布尔值 | 更新日期: 2023-09-27 18:00:40

这是我的一段代码,它将游戏场从左向右移动,每次击中侧面时向下移动一个。

    private void moveMonsterPlayField()
    {
        if (monsterPlayField.DirectionRight)
        {
            monsterPlayField.X++;
            if (monsterPlayField.X + monsterPlayField.Width >= this.width)
            {
                monsterPlayField.DirectionRight = false;
                monsterPlayField.Y++;
            }
        }
        else 
        {
            monsterPlayField.X--;
            if (monsterPlayField.X == 0)
            {
                monsterPlayField.DirectionRight = true;
                monsterPlayField.Y++;
            }
        }

    }

但它有点冗长。

相反,我想做一些类似的事情:

    private void moveMonsterPlayField()
    {
       monsterPlayField.X += monsterPlayField.DirectionRight * 1 //where DirectionRight resolves to 1 or -1
       if (monsterPlayField.X + monsterPlayField.Width >= this.width || monsterPlayField.X == 0)
       {
           monsterPlayField.DirectionRight = !monsterPlayField.DirectionRight;
           monsterPlayField.Y++;
       }

    }

这可能吗?

一种获得布尔值来表示1和-1的优雅方法

您可以使用这样的东西:

monsterPlayField.X += monsterPlayField.DirectionRight ? 1 : -1;

事实上,这只是一个if语句,具有truefalse结果。

其他选项:

  • 您可以将另一个属性添加到计算该属性的类中
  • 创建一个类,并将转换运算符重写为boolint,尽管我个人不会这么做

您可能会考虑的另一种选择是使用两个整数属性来表示怪物的当前速度,指定X和Y分量:

int VelocityX;
int VelocityY;

目前,您可以将值限制为-1、0和1(但将来可以指定更高的速度)。

然后你调整怪物(X,Y)位置的代码是:

monsterPlayField.X += monsterPlayField.VelocityX;
monsterPlayField.Y += monsterPlayField.VelocityY;

更改X和Y值后,您仍然需要对它们进行范围检查。

另一个选项是使用枚举并为枚举成员赋值。

enum Direction
{
    Right = 1,
    Left = -1
}

然后,您可以将枚举强制转换为代码中的int值。

private void moveMonsterPlayField()
{
   monsterPlayField.X += (int)monsterPlayField.Direction; // Direction is now of type Direction instead of bool
   if (monsterPlayField.X + monsterPlayField.Width >= this.width || monsterPlayField.X == 0)
   {
       monsterPlayField.Direction = (Direction)((int)monsterPlayField.Direction * -1); 
   }
}