Навигация по массиву игровых объектов без отображения повторяющихся объектов

Я работаю над игрой, в моей игре пользователь приобретает оружие (кексы) на уровнях. У меня есть кнопка, которую игрок нажимает, чтобы перейти к следующему кексу (полученное оружие хранится в массиве).

Вот моя проблема: если игрок получает 2 желтых кекса, 1 красный кекс и 2 синих кекса, как мне перемещаться по массиву, не показывая один и тот же кекс дважды? Моя кнопка выглядит так, как будто она не меняет оружие, когда в коде это происходит, она переходит к следующему элементу в массиве, но это то же самое оружие [желтый кекс, желтый кекс, красный кекс, синий кекс, синий кекс].

public function CupcakeChangeButton(e: MouseEvent) {
    cakeButtonCounter++;

    //Make sure the cakeButtonCounter never exceeds the amount of 
    //elements in array

    if (cakeButtonCounter >= CupcakesArray.length - 1) {
        cakeButtonCounter = 0;
    }

    //NOTE: may need function called "cupcake count", this function should
    //be called at the beginning of THIS function and in the constructor function
    //Should count the amount of cupcakes and maybe set wasSeen Elements to No

    /*
            The switch statment makes its decisions based on the type of cupcake
            is the current elment. The current element is represented by 
            "cakeButtonCounter" (CupcakesArray[cakeButtonCounter])

            The if statements decides if the cupcake has been seen already.
            If it hasnt been seen, it sets the button's text box to show how many of 
            those kind of cupcakes are left.

            After the amount of cupcakes of that type is shown in the text box, 
            the "unshift" method is used to place "yes" in the first element, of it's
            own Array type, WITHIN THE WAS SEEN ARRAY.......confusing!!!!!!

            Example:
            wasSeen.PinkCupcake.unshift("yes") = wasSeen.PinkCupcake[0] == "yes" 

            This is done so that we can keep track of what cupcakes has been seen
            already

            When the game is initialized the was seen elements are set to "no". So when 
            it's set to "yes", after being seen, The initial value,"no", is placed in the 
            next element. It's no longer needed, so we use the "splice" method to delete it 
            and HOPEFULLY, remove it from memory

            The "else" block of code takes place if the cupcake has already been seen.
            It increments the cakeButtonCounter so that the button will display the next
            cupcake in the array, that has NOT been seen

            After all decisions are made,(which cupcakes are next and which cupakes have 
            been seen) 
            Update the button's face by displaying the next cupcake that hasnt been seen
           (button goes to and stop and next element)

            NOTE: The ACTUAL case will be the dynamic var cupcake type (the NAME not the actual 
                  cupcake)
            */

    switch (CupcakesArray[cakeButtonCounter]) {
        case "PinkCupcake":
            if (wasSeen.PinkCupcake[0] == "no") {
                CupcakeNavigationBox.countBox.text = "x" + PinkCupcakeCount;
                wasSeen.PinkCupcake[0] == "yes";
                trace("element change? " + wasSeen.PinkCupcake[0]);
            } else {
                cakeButtonCounter++;
                trace("if yes...its starting that way " + wasSeen.PinkCupcake[0]);
            }
            break;

        case "YellowCupcake":
            if (wasSeen.YellowCupcake[0] == "no") {
                CupcakeNavigationBox.countBox.text = "x" + YellowCupcakeCount;
                wasSeen.YellowCupcake[0] == "yes";
            } else {
                cakeButtonCounter++;
            }
            break;

        case "GreenCupcake":
            if (wasSeen.GreenCupcake[0] == "no") {
                CupcakeNavigationBox.countBox.text = "x" + GreenCupcakeCount;
                wasSeen.GreenCupcake[0] == "yes";
            } else {
                cakeButtonCounter++;
            }
            break;

        case "PurpleCupcake":
            if (wasSeen.PurpleCupcake[0] == "no") {
                CupcakeNavigationBox.countBox.text = "x" + PurpleCupcakeCount;
                wasSeen.PurpleCupcake[0] == "yes";
            } else {
                cakeButtonCounter++;
            }
            break;
    }

    CupcakeNavigationBox.buttonFace.gotoAndStop(CupcakesArray[cakeButtonCounter]);
    changeCupcake();
}

person rtpenick    schedule 12.02.2014    source источник
comment
Спасибо @Klaster_1 за то, что почистил это для меня.   -  person rtpenick    schedule 13.02.2014


Ответы (1)


Вместо этого вам следует хранить доступные типы оружия в массиве, из которого вы выбираете тип оружия. Кроме того, этот массив должен содержать ints, потому что, очевидно, ваши кексы тратятся на огонь/действие, поэтому в вашем распоряжении будет массив для хранения боеприпасов. Если вам нужен разблокированный массив, обязательно сделайте другой массив. (Однако убедитесь, что есть оружие по умолчанию, иначе функция выбора торта может войти в бесконечный цикл)

var cupcakesAmmo:Array=[0,0,0,0,0,0,0]; // as many as you have types of cupcakes
var cupcakesTypes:Array=[RedCupcake,YellowCupcake,PinkCupcake,GreenCupcake,BlueCupcake,PurpleCupcake,BlackCupcake];
// let's say we have seven cupcakes
var currentCupcake:int; // the selected weapon
function cupcakeChangeButton(e: MouseEvent) {
    // first check if we actually have anything to change to
    var weHave:int=0; // how many different cupcakes we have
    var i:int;
    for (i=0;i<cupcakesAmmo.length;i++) if (cupcakesAmmo[i]>0) weHave++;
    if (weHave<2) return; // hehe, we either have no cupcakes or just one type of em
    // otherwise let's change
    do { // we have to do this at least once
        currentCupcake++;
        if (currentCupcake==cupcakesAmmo.length) currentCupcake=0; // change type
    } while (cupcakesAmmo[currentCupcake]==0); // change until we find the type with nonzero ammo
    // okay, type selected, let's get proper display
    CupcakeNavigationBox.countBox.text = "x" + cupcakesAmmo[currentCupcake];
    // see, no switch is needed! Just get the data off your array :)
    // TODO change the displayed cupcake too (I don't see where you do this)
}
person Vesper    schedule 12.02.2014
comment
ОМГ ВЫ ЗАМЕЧАТЕЛЬНЫЕ!!!! Вы сделали этот образ оооочень легким и простым. Большое спасибо за вашу помощь. Это для моего самого первого мобильного приложения, и я все еще относительно новичок в программировании, поэтому я все еще учусь некоторым вещам на ходу. Еще раз спасибо за вашу помощь. Если у меня возникнут вопросы в будущем, ничего, если я напишу вам здесь? - person rtpenick; 13.02.2014
comment
Если у вас возникнут дополнительные вопросы, не стесняйтесь задавать их на StackOverflow, здесь есть люди лучше меня. Если возникнет вопрос, задайте его здесь и, скорее всего, получите развернутый ответ. - person Vesper; 13.02.2014
comment
Я столкнулся с другой проблемой actionscript и хотел бы узнать, можете ли вы дать некоторое представление. Я разместил вопрос и не получил никакой полезной информации. Мои кнопки замедляют частоту кадров в игре. Я установил для свойств мыши значение false для отображаемых объектов, не помогает вообще. Когда я не нажимаю кнопку, он работает идеально гладко. Падение частоты кадров вызывает ужасное отставание - person rtpenick; 20.10.2014