actionscript-3actionscriptflixel

Checking for same values using if statement in actionscript?


I'm working on a match-3 style puzzle game using Flixel, and so I'm working on checking each row and column to see if there is a match at any given time. However, I have 6 different pieces (as of right now) that are active, and each piece is identified by an integer. Given that, I can check, for each and every single piece, by doing something like this:

public function matchingCheck():void
    {
        if (piecesArray[0][1] == 1 && piecesArray[1][1] == 1 && piecesArray[2][1] == 1) {
            FlxG.log("Yay!");
        }
    }

However, this is rather unwieldy and would basically cause way too much repetition for my liking.

At the very least, I would like to be able to check if the values in these arrays are equal to one another, without having to specify which value it is. At the very best, I'd love to be able to check an entire row for three (or more) adjacent pieces, but I will settle for doing that part manually.

Thanks for your help!


EDIT: Nevermind, my edit didn't work. It was just checking if piecesArray[2][1] == 1, which makes me a sad panda.


EDIT 2: I've selected the correct answer below - it's not exactly what I used, but it definitely got me started. Thanks Apocalyptic0n3!


Solution

  • You could cut down on that code a little bit by using another function

    private function checkValid( arrayOfItemsToCheck:Array, value:* ):Boolean {
        for ( var i:Number = 0; i < arrayOfItemsToCheck.length; i++ ) {
            if ( arrayOfItemsToCheck[i] != value ) {
                return false;
            }
        }
        return true;
    }
    

    Then you just do this in your if statement:

    if ( checkValid( [ piecesArray[0][1], piecesArray[1][1], piecesArray[2][1] ], 1 ) ) {
                FlxG.log("Yay!");
    }
    

    That does assume all items need to be equal to 1, though. It's still a lot of code, but it cuts out one set of "= 1 &&" for each check.