如何获取2D对象数组的索引?

时间:2021-04-04 21:32:54

I have a 2D button array (buttons) that will generate a 5 by 5 grid of buttons. I want to get the index of a single button (say, (2,2) in the center) when clicked, and find the index values of buttons surrounding the original button within a 3 x 3 radius by creating integer variables such as topcentre (which would be the index of buttons(x, y - 1) or 1,2, where x and y are the values of the clicked button.) I can then add text, etc. to those surrounding buttons.

我有一个2D按钮阵列(按钮),将生成一个5乘5的按钮网格。我想在单击时获得单个按钮的索引(例如,在中心的(2,2)),并通过创建整数变量(如topcentre)找到3 x 3半径内原始按钮周围的按钮的索引值(这将是按钮(x,y - 1)或1,2的索引,其中x和y是单击按钮的值。)然后我可以向周围的按钮添加文本等。

Here's a visualization:

这是一个可视化:

0,0|0,1|0,2|0,3|0,4

1,0|1,1|1,2|1,3|1,4

2,0|2,1|2,2|2,3|2,4

3,0|3,1|3,2|3,3|3,4

4,0|4,1|4,2|4,3|4,4

How can I do this?

我怎样才能做到这一点?

1 个解决方案

#1


3  

In the backend you could just use a single array.

在后端,您可以使用单个阵列。

0,0|0,1|0,2|0,3|0,4|1,0|1,1|1,2|1,3|1,4|2,0|2,1|2,2|2,3|2,4|3,0|3,1|3,2|3,3|3,4|4,0|4,1|4,2|4,3|4,4

Even if on the UI it's display as 2D.

即使在UI上它也显示为2D。

2,2 would be index 12 ({x} * {width} + {y} = 2 * 5 + 2 = 12). To get the other index, you can substract or add.

2,2将是索引12({x} * {width} + {y} = 2 * 5 + 2 = 12)。要获取其他索引,您可以减去或添加。

Top Left = {index} - {width} - 1
Top = {index} - {width}
Top Right = {index} - {width} + 1
...

左上角= {index} - {width} - 1 Top = {index} - {width}右上角= {index} - {width} + 1 ...

#1


3  

In the backend you could just use a single array.

在后端,您可以使用单个阵列。

0,0|0,1|0,2|0,3|0,4|1,0|1,1|1,2|1,3|1,4|2,0|2,1|2,2|2,3|2,4|3,0|3,1|3,2|3,3|3,4|4,0|4,1|4,2|4,3|4,4

Even if on the UI it's display as 2D.

即使在UI上它也显示为2D。

2,2 would be index 12 ({x} * {width} + {y} = 2 * 5 + 2 = 12). To get the other index, you can substract or add.

2,2将是索引12({x} * {width} + {y} = 2 * 5 + 2 = 12)。要获取其他索引,您可以减去或添加。

Top Left = {index} - {width} - 1
Top = {index} - {width}
Top Right = {index} - {width} + 1
...

左上角= {index} - {width} - 1 Top = {index} - {width}右上角= {index} - {width} + 1 ...