Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
201 views
in Technique[技术] by (71.8m points)

actionscript 3 - Flash hangs when I execute this particular loop

Please do forgive me if this question is very stupid, but I couldn't figure out what to do, which is why I ask it. Here, I declared a small white square as a movieclip symbol(Dot) and I wish to generate it after a specific gap on the entire screen. So, when I execute this (test it) code on Flash CS6, it hangs. After that I will be forced to end the program without doing anything further.

import flash.ui.*;
stop();
Mouse.hide();
var ctX:int = 0,ctY:int = 0,done:Boolean = false;
var base:Object = MovieClip(root);
this.addEventListener(Event.ENTER_FRAME, eFrame);
function eFrame(event:Event):void
{
    while (done == false)
    {
        var dots:Dot = new Dot  ;
        dots.x +=  (50 * ctX);
        dots.y +=  (50 * ctY);
        ctX++;
        if (ctX == 11)
        {
            ctX = 0;
            ctY++;
        }
        else if (ctX == 11 && ctY == 10)
        {
            done = true;
            break;
        }
        stage.addChild(dots);
    }
}

Thank you in advance. I have attached a screenshot of the situation.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The loop will never finish because the condition for done=true is ctX==11, but ctX==11 causes ctX=0 in the first condition:

if (ctX == 11) // when ctX is 11
{
    ctX = 0; // ctX is reset to 0
    ctY++;
}
else if (ctX == 11 && ctY == 10) // so you will never have ctX=11 here
{
    done = true;
    break; // (Tip: you don't need `done` since `break` exits the loop)
}

You could fix this by swapping the conditions, but I think this use of a while loop is unnecessarily complex and fragile. Why not just use two for loops:

for (var ctX:int = 0; ctX < 11; ctX++) {
    for (var ctY:int = 0; ctY < 11; ctY++) {
        var dots:Dot = new Dot();
        dots.x = (50 * ctX);
        dots.y = (50 * ctY);
        stage.addChild(dots);
    }
}

This is much clearer and less fragile because the loops are fixed length.

You could even do it with one for loop and a little math, but you lose some clarity:

for (var i:int = 0; i < 11 * 11; i++) {
    var dots:Dot = new Dot();
    dots.x = (50 * (i % 11));
    dots.y = (50 * int(i / 11));
    stage.addChild(dots);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...