簡體   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?

我試圖實現的目標是擁有一個 5x5 的按鈕網格。 當您切換按鈕時,您切換的按鈕周圍的按鈕應隨之切換。 這是網格:

   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}
};

因此,如果我按下按鈕 16,我需要按鈕 10、11、12、17、22、21、20 和 15 與其一起切換。 我遇到的一個主要問題是,如果我要切換按鈕 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;
}

我想看看是否有人可以提供更好地實現這一點的想法。

你可以減少硬編碼:

  • 您需要按下按鈕的 x|y 位置
  • 然后您可以在相鄰位置自動按下其他按鈕: button(x-1|y-1), button(x-1|y), ...
  • 但是你必須為 x=0, y=0, x=4, y=4 位置的按鈕添加一些例外,所以你不要嘗試按下不存在的按鈕

如果需要更多幫助,你可以再問我。 我以前做過模擬

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM