简体   繁体   English

我怎样才能更好地实现使用 2D 阵列激活网格上周围按钮的 5x5 网格按钮拼图?

[英]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.我试图实现的目标是拥有一个 5x5 的按钮网格。 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.因此,如果我按下按钮 16,我需要按钮 10、11、12、17、22、21、20 和 15 与其一起切换。 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:我遇到的一个主要问题是,如果我要切换按钮 4,则只有按钮 5、10 和 9 应该用它激活,因为按钮 4 的左侧和上方有一个“墙”。我'已经能够做到这一点,但我的实现很糟糕:

   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您需要按下按钮的 x|y 位置
  • then you can autopress the other buttons at neighbored positions: button(x-1|y-1), button(x-1|y), ...然后您可以在相邻位置自动按下其他按钮: 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但是你必须为 x=0, y=0, x=4, y=4 位置的按钮添加一些例外,所以你不要尝试按下不存在的按钮

If more help needed, you can ask me again.如果需要更多帮助,你可以再问我。 I've did simular before我以前做过模拟

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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