-1
class Child:public Parent{
public:
    enum Direction { Left, Right, Up, Down };
    Direction direction;
    void Update();            
private:
    int x,y;
    void ChangeDirection();
    void Draw();

};

我需要调用ChangeDirection()Draw()的Update()函数来根据我所做的当前方向递增和递减xy值。我的问题是yx不能是(-)值。

并且ChangeDirection()应该为方向数据分配一个随机方向,并且该方向必须与当前方向不同。 我能够以这种方式在同一个ChangeDirection ()函数中计算出随机方向

Direction direction = static_cast<Direction>(rand() % 4);
cout << direction;

但有时它会再次打印相同的方向。现在我想要的是,方向的随机分配应该发生在ChangeDirection()成员函数中,不允许再次使用当前值,但它应该通过void Draw(); 显示结果;成员函数,它增加或减少xy值而不让它成为 (-) 值(应钳制为 0)。这就是我为此所做的。

if ( direction == 0 ){
    cout << "Right";
    x++;
}
else if (direction == 1 ){
    cout << "Down";
    y++;
}
else if (direction == 2 ){
    cout << "Up";
    y--;
}
else if (direction == 3 ){
    cout << "Left";
    x--;
}
Draw();

但它给出了(-)值。我该如何前进..

4

1 回答 1

1

由于您正在分配随机方向,因此有时分配的方向等于前一个方向是有意义的。尝试类似:

Direction direction = static_cast<Direction>((currentDirection + 1 + (rand() % 3) ) % 4);

确保你得到一个新的方向

编辑:要回答您问题的另一部分,您必须在递增或递减之前检查 x 和 y 的值,以确保它们在您当前使用的范围内。这是我正在谈论的一个例子:

 if(x > 0){
   x--;
 } else {
 //do something else
 }
于 2014-09-23T11:55:53.367 回答