затопление тральщика продолжает получать ошибку переполнения стека

Я пытаюсь использовать заливку, чтобы очистить открытую площадку в игре с тральщиком. Я сделал простую функцию заливки, но все время получаю код ошибки переполнения стека

 public void revealEmpty(int givenIndex){
        if(buttons.get(givenIndex).isEnabled())
            open(givenIndex);

            if(gm.surroundingbombs(givenIndex)==0){

                if(gridsize>givenIndex+gridwidth)
                    revealEmpty(givenIndex+gridwidth);

                if(gridsize>givenIndex+gridwidth+1)
                    revealEmpty(givenIndex+gridwidth+1);

                if(gridsize>givenIndex+gridwidth-1)
                    revealEmpty(givenIndex+gridwidth-1);

                if(gridsize<givenIndex-gridwidth)
                    revealEmpty(givenIndex-gridwidth);

                if(gridsize<givenIndex-gridwidth+1)
                    revealEmpty(givenIndex-gridwidth+1);
                if(gridsize<givenIndex-gridwidth-1)

                    revealEmpty(givenIndex-gridwidth-1);

                 if(gm.rightEdge(givenIndex,gridwidth)){//checks if the button pressed is on the right edge

                        revealEmpty(givenIndex+1);
                }

                 if(gm.leftEdge(givenIndex,gridwidth)){//checks if the button pressed ison the left edge

                    revealEmpty(givenIndex-1);
                }



            }   
            else{
                return;
            }



    }

это код, используемый для «открытия» ячейки в сетке

public void open(int Bindex){
        Font f = new Font("Arial", Font.BOLD, 26);//font for the buttons
        Font f2 = new Font("Arial", Font.BOLD, 15);//font for the move tracker
        if(gm.surroundingbombs(Bindex)!=0){
            buttons.get(Bindex).setBorder(BorderFactory.createBevelBorder(1, Color.LIGHT_GRAY, Color.DARK_GRAY));
            buttons.get(Bindex).setIcon(null);
            if(gm.surroundingbombs(Bindex)!=0)
            buttons.get(Bindex).setText(Integer.toString(gm.surroundingbombs(Bindex)));
            if(small)
            buttons.get(Bindex).setFont(f2);
            else
            buttons.get(Bindex).setFont(f);
            buttons.get(Bindex).setBorderPainted(true);
            buttons.get(Bindex).setEnabled(false);
            buttons.get(Bindex).setContentAreaFilled(true);
            buttons.get(Bindex).setBackground(Color.LIGHT_GRAY);
        }
        else
        buttons.get(Bindex).setBorder(BorderFactory.createBevelBorder(1, Color.LIGHT_GRAY, Color.DARK_GRAY));
        buttons.get(Bindex).setIcon(null);
        buttons.get(Bindex).setBorderPainted(true);
        buttons.get(Bindex).setEnabled(false);
        buttons.get(Bindex).setContentAreaFilled(true);
        buttons.get(Bindex).setBackground(Color.LIGHT_GRAY);


    }

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


person w_o_w    schedule 26.01.2018    source источник
comment
Проблема здесь в том, что вы выполняете рекурсивный вызов и никогда не выходите из метода. См. stackoverflow.com/q/214741/4574633   -  person Antoine Dubuis    schedule 26.01.2018
comment
Чтобы быстрее получить помощь, опубликуйте минимальный воспроизводимый пример или Краткий, автономный, правильный пример.   -  person Andrew Thompson    schedule 26.01.2018


Ответы (1)


Проблема здесь в том, что вы проверяете все окружающие JButton, независимо от того, обнаружены ли они уже. Чтобы исправить рекурсивные вызовы, попробуйте изменить if-оператор, чтобы он окружал весь код. Нравится:

    public void revealEmpty(int givenIndex){
    if(buttons.get(givenIndex).isEnabled()) { //If statement opens here
        open(givenIndex);

        if (gm.surroundingbombs(givenIndex) == 0) {

            if (gridsize > givenIndex + gridwidth)
                revealEmpty(givenIndex + gridwidth);

            if (gridsize > givenIndex + gridwidth + 1)
                revealEmpty(givenIndex + gridwidth + 1);

            if (gridsize > givenIndex + gridwidth - 1)
                revealEmpty(givenIndex + gridwidth - 1);

            if (gridsize < givenIndex - gridwidth)
                revealEmpty(givenIndex - gridwidth);

            if (gridsize < givenIndex - gridwidth + 1)
                revealEmpty(givenIndex - gridwidth + 1);
            if (gridsize < givenIndex - gridwidth - 1)

                revealEmpty(givenIndex - gridwidth - 1);

            if (gm.rightEdge(givenIndex, gridwidth)) {//checks if the button pressed is on the right edge

                revealEmpty(givenIndex + 1);
            }

            if (gm.leftEdge(givenIndex, gridwidth)) {//checks if the button pressed ison the left edge

                revealEmpty(givenIndex - 1);
            }


        } else {
            return;
        }
    } else { //And ends here
        return;
    }


}

Основываясь на предоставленной вами информации, я не уверен на 100%, решит ли это вашу проблему, поэтому, пожалуйста, проверьте ее и сообщите мне, сработало ли это.

person DerBobby    schedule 26.01.2018
comment
это останавливает работу функции, но я почти уверен, что причина того, что она не работает, заключается в том, что способ, которым я проверяю, была ли кнопка уже открыта, не работает. - person w_o_w; 26.01.2018