Moynul
Moynul

Reputation: 635

if statement is not working despite trace commands being true

this is really irritating and I've tried everything but can't fix this bug.

    private function gameLoop(e:Event):void 
    {

        movement();
        trace(randomItem);
        if (randomItem == "pomme")
        {
            updateScore();
        }



        if (timerText.text == "0") 
        {
            stage.removeChild(player);
            stage.removeEventListener(Event.ENTER_FRAME, gameLoop);
            stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyDown);
            stage.removeEventListener(KeyboardEvent.KEY_UP, keyUp);
            this.gotoAndStop(3)
            endFrame();

        }
    }

This code traces the randomItem. I tested it and the trace output said the randomItem was "pomme".

This means the score should have update (trace command:"score has updated");

But it hasn't, this method has worked for the other games i am working on but what's the big idea here?

    private var colourArray:Array = new Array("pomme ","banane ","laitue ","concombre ","miel");

The top code is an array and the randomItem compares it to the array.

    private var colourArray:Array = new Array("pomme ","banane ","laitue ","concombre ","miel");
    private var len:int = colourArray.length - 1;
    private var rand:int;
    private var randomItem:String;  

        rand = Math.floor(Math.random() * len);
        randomItem = colourArray[rand];
        trace(randomItem);
        baloonText.text = "Teddy wants to eat " + randomItem;

Upvotes: 0

Views: 92

Answers (2)

DFreeman
DFreeman

Reputation: 542

Entries in your colourArray include a space at the end.
If you are populating randomItem from this array then "pomme " != "pomme" and the difference wouldn't be immediately obvious from a trace.

Upvotes: 6

Andrey Popov
Andrey Popov

Reputation: 7510

The item is either not "pomme" or it's calling the updateScore without your notice :)

Best practice is to put trace statements inside the if clause as well as inside the updateScore function. From this point of view, your code looks well.

Edit: Just to mention, that your random function doesn't work properly, because Math.random() Returns a pseudo-random number n, where 0 <= n < 1 (from ref).

So your array length now is 5, your len property goes down to 4, Math.Random() * len returns maximum of 3.99 (0.999 * 4), and when you floor it down it means that the maximum you can get is 3. But you have 4 elements.. :)

Upvotes: 1

Related Questions