c++中的while循环

C++ do while loop

本文关键字:循环 while 中的 c++      更新时间:2023-10-16

我有一个包含10个项目的向量(为了简单起见,所有这些都是相同的类,称为'a')。我想做的是检查'A'不是A)隐藏墙壁或b)隐藏另一个'A'。我有一个这样的碰撞函数。

这个想法很简单,让这个循环类通过并移动"A"到下一个位置,如果药水引起碰撞,那么它需要在屏幕上给自己一个新的随机位置。因为屏幕很小,所以元素很有可能会被放到另一个屏幕上(或放在墙上等)。代码的逻辑在我的头脑中工作得很好——但是调试代码时,对象就会卡在循环中,并停留在相同的位置。"A"应该在屏幕上移动,但它却静止不动!

当我注释掉Do while循环,并移动'MoveObject()'函数时,代码工作完美,'A'在屏幕上移动。只是当我尝试添加额外的功能时,它不起作用。

    void Board::Loop(void){

        //Display the postion of that Element. 
        for (unsigned int i = 0; i <= 10; ++i){

            do {
                if (checkCollisions(i)==true){
                moveObject(i); 
                }
                else{
                    objects[i]->ResetPostion();
                }
            }
            while (checkCollisions(i) == false);
            objects[i]->SetPosition(objects[i]->getXDir(),objects[i]->getYDir());
        }
}

下面的类是碰撞检测。稍后我会展开。

    bool Board::checkCollisions(int index){
    char boundry = map[objects[index]->getXDir()][objects[index]->getYDir()];
    //There has been no collisions - therefore don't change anything 
    if(boundry == SYMBOL_EMPTY){
        return false;
    }
    else{
        return true;
    }
}

任何帮助都将非常感激。我请你喝虚拟啤酒:-)

感谢编辑:

resetposition ->这将给元素A在屏幕上的一个随机位置moveObject ->这将查看对象的方向,并适当地调整x线和Y线。

我猜你需要:

do { ...
... } while (checkCollisions(i)); 

Also, if you have 10 elements, then i = 0; i < 10; i++

And btw. don't write if (something == true), simply if (something) or if (!something)

for (unsigned int i = 0; i <= 10; ++i){

是错误的因为这是一个11项的循环,使用

for (unsigned int i = 0; i < 10; ++i){

你没有定义"不工作"是什么意思,所以这就是我现在能提供的所有帮助。

在基本的语言结构和逻辑流上似乎有很多混淆。编写一些非常简单的测试应用程序来练习不同的语言特性可能会对你有很大帮助。(如果你有一个分步调试器,也会有)

do/while()是一个相当高级的功能,有些人在整个职业生涯中从未使用过,参见:do…While vs While

我建议在使用for之前,先用whileif/else打下坚实的基础。当您刚刚完成whilefor循环并意识到如果稍微改变一下执行顺序,就可以节省大量重复的初始化代码时,您应该第一次查看do。(就我个人而言,我甚至不再使用do了,我只是使用while(true)/break的迭代器,因为它让我在一个循环中预邮政编码)

我认为这简化了你想要完成的任务:

void Board::Loop(void) {
    //Display the postion of that Element. 
    for (unsigned int i = 0; i < 10; ++i) {
        while(IsGoingToCollide(i))  //check is first, do while doesn't make sense
            objects[i]->ResetPosition();
        moveObject(i);   //same as ->SetPosition(XDir, YDir)?
                         //either explain difference or remove one or the other
    }
}

这个函数名对我来说似乎模棱两可:

bool Board::checkCollisions(int index) {

我建议改成:

// returns true if moving to next position (based on inertia) will 
// cause overlap with any other object's or structure's current location
bool Board::IsGoingToCollide(int index) {

相反,checkCollisions()也可以表示:

// returns true if there is no overlap between this object's
// current location and any other object's or structure's current location
bool Board::DidntCollide(int index) {

最后注意:仔细检查->ResetPosition()是否将放在边界内