为数据成员分配一个新的随机方向,该方向不同于 c++ 中的当前方向
Assign a new random direction to data member that is different from the current in c++
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
}
相关文章:
- 在C++中,我如何接受不同于同一行的用户输入
- 来自逆 vp 矩阵和相机位置的光线方向不正确
- int lastIndex[NO_OF_CHARS]={-1} 如何;不同于 vector<int> lastIndex(NO_OF_CHARS, -1);?
- 不同于按值传递和常量引用传递的程序集
- 在 C++ 的自定义运算符中删除与删除[](不同于常见的删除与删除[]问题)
- sizeof(enum) 可以不同于 sizeof(std::underlying_type<Enum>::
- 使用 "()" 调用构造函数不同于"{}"
- 循环的C 范围不同于常规循环
- 功能模板与Variadic模板过载:Intel C 编译器版本18产生的结果不同于其他编译器.英特尔是错误的
- 以不同于其声明形式的形式定义类
- 在不同于依赖DLL的文件夹中输出已编译目标的正确方法是什么
- 编译器如何以不同于常规函数的方式处理 lambda?
- 是否允许标准库实施具有不同于C 标准的类定义
- 没有可调用的匹配函数(构造函数),候选函数不同于对给定类型的引用
- OpenCV立体视觉3D坐标到2D相机平面投影不同于将2D点三角化到3D
- 搜索字符串中的第一个字符不同于"X"
- c++:指针值不同于指向变量的地址
- 对象的大小不同于没有指针的类的大小
- xml序列化不同于以字符串形式发送的原因
- 为数据成员分配一个新的随机方向,该方向不同于 c++ 中的当前方向