java - 如何更好地实现我的 5x5 按钮网格拼图,使用 2D 数组激活网格上的周围按钮?
问题描述
我想要实现的目标是拥有一个 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 的位置的按钮添加一些例外,因此您不要尝试按下不存在的按钮
如果需要更多帮助,您可以再次询问我。我以前做过类似的
推荐阅读
- bash - 匹配两个文件中的列并修改结果文件
- azure-devops - Azure DevOps 管道中 $(System.AccessToken) 中令牌的范围是什么
- angular - Angular Refresh Error - 当我刷新 Angular 时服务器遇到内部错误
- javascript - anychart.bounds 做什么以及它如何在特定位置配置图表
- c++ - 如何在通过应用程序进行单步调试时检查堆分配?
- javascript - 谷歌标签管理器/增强型电子商务 - 网页浏览标签数据层推送不起作用
- python - 如何在 Python 中使用正则表达式从逗号分隔的数字字符串中找到匹配数字的下一个数字?
- c# - 如何使用 PayPal .NET SDK 获取付款人列表?
- python - 为什么 readline() 没有从我的 .txt 中获取所有单词
- angular - 如何将 queryParams 动态添加到 Angular 7 中动态创建的链接?