Search This Blog

Thursday, September 30, 2010

AS3: Only allow a certain number of a certain type of object into an Array

Programmer Question

I want to find a way to only allow certain objects into an array that have a certain word in thier class name. Or at least find the optimal way of doing something like this. Heres the details. I have an Array that stores all the objects dropped into a cart.



function addProductToArray (e:MouseEvent):void{
currMC = (e.target as MovieClip);
myCart.itemsInCart.push(currMC);
trace(myCart.itemsInCart);}



If, for example, I drop an [object BreadGrain] and a [object PastaGrain].



trace(myCart.itemsInCart);// would trace [object BreadGrain],[object PastaGrain].



Easy, no problems there. But what do I do if I only want to allow 2 objects with "Grain" in their Classname into the array? I want to do this so that the user can only drop 2 of each type of food into the 'cart'. The types of food are Grain, Fruit, Vegetable, Meats etc and I've appended the type of food to the end of the Classname, hopefully so that I can use it to detect what type of food it is and stop it from being added over the limit as well as displaying an error. i.e "You already have 2 Grain products".



I hope that makes sense. Anyway, i've found that works well to a degree:



if (currMC is BreadGrain) {
myCart.itemsInCart.push(currMC);
} else {
// error message code here
}


BUT I have several products and I don't want to have to write a if/else or switch statement for them all. I was hoping to do this dynamically with something similar to:



//this is an example of the logic
if (currMC classNameContainsTheWord "Grain" AND myCart.itemsInCart DoesNotContainMoreThan 2 Grain Objects) {


myCart.itemsInCart.push(currMC);
} else {
// error message code here
}



I'm stumped. Even just a "Dude, you are doing this all wrong" would help. Thanks.



Find the answer here

No comments:

Post a Comment

Related Posts with Thumbnails