简体   繁体   中英

How can I better achieve my implementation of a 5x5 grid puzzle of buttons that activate the surrounding buttons on the grid using a 2D Array?

The goal I am trying to achieve is to have a 5x5 grid of buttons. When you toggle a button, the buttons surrounding the buttons you toggle should toggle with it. Here is the grid:

   private static final int[][] GRID = {
        {4, 5, 6, 7, 0},
        {9, 10, 11, 12, 13},
        {14, 15, 16, 17, 18},
        {19, 20, 21, 22, 23},
        {24, 25, 26, 27, 28}
};

So if I press button 16, I need buttons 10, 11, 12, 17, 22, 21, 20, and 15 to toggle along with it. A major issue I've faced is that if I were to, say, toggle button 4, only buttons 5, 10, and 9 should activate with it, because there is a "wall" to the left and above button 4. I've been able to do this, but my implementation is awful:

   private void setButtonActivated(Player player, int button) {
        player.setButtonActivated(button);
        for (int b : getConnectedTiles(button)) {
            player.setButtonActivated(b);
        }
    }

private int[] getConnectedTiles(int button) {
    switch (button) {
        case 4:
            return new int[] { 5, 10, 9 };
        case 6:
            return new int[] { 5, 10, 11, 12, 7 };
        case 16:
            return new int[] { 10, 11, 12, 17, 22, 21, 20, 15 };
    }
    return null;
}

I would like to see if anyone could offer ideas for a better implementation of this.

You could make it less hardcoded:

  • You need the x|y position of the button pressed
  • then you can autopress the other buttons at neighbored positions: button(x-1|y-1), button(x-1|y), ...
  • but you have to add some exceptions for buttons at positions with x=0, y=0, x=4, y=4, so you dont try to press buttons, that dont exist

If more help needed, you can ask me again. I've did simular before

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM