class Child:public Parent{
public:
enum Direction { Left, Right, Up, Down };
Direction direction;
void Update();
private:
int x,y;
void ChangeDirection();
void Draw();
};
我需要 Update(( 函数,它调用 ChangeDirection(( 和 Draw(( 来递增和递减我所做的当前方向上的 x y 值。我的问题是 y 或 x 不能是 (-( 值。
并且 ChangeDirection(( 应该为方向数据分配一个随机方向,并且该方向必须与当前方向不同。我能够以这种方式在相同的 ChangeDirection(( 函数中找出随机方向
Direction direction = static_cast<Direction>(rand() % 4);
cout << direction;
但有时它会打印相同的方向。现在我想要的是,方向的随机赋值应该发生在 ChangeDirection(( 成员函数中,不允许再次使用当前值,但它应该通过 void Draw(( 显示结果;成员函数递增或递减 x y 值而不让它成为 (-(值(应固定为 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();
但它正在给出(-(值。 我该如何向前迈进..
由于您分配的是随机方向,因此分配的方向有时等于前一个方向是有道理的。尝试类似操作:
Direction direction = static_cast<Direction>((currentDirection + 1 + (rand() % 3) ) % 4);
确保您获得新的方向
编辑:要回答问题的另一部分,您必须在递增或递减之前检查 x 和 y 的值,以确保它们在您当前使用的任何范围内。这是我所说的一个例子:
if(x > 0){
x--;
} else {
//do something else
}