开发者

Is there a way to change multiple items? [Hard to describe, example inside]

I'm struggling a bit in how to put this into words coherently, so I'll just use an example and hope it gets the message across.

Take the game Othello (Reversi) for example. I can program the logic behind the game, that is to say I can determine which pieces are to have their colors changed after each turn.

Let's say I've got 64 panels on a JFrame, each one representing a position on the Othello board. After a turn ends, I determine that panels 5 and 6 need to have their colors changed.

What I would like to be able to do is pass 5 and 6 via an array, let's say, and have a for-loop that runs through the array.

for(int i=0; i < array.length; i++){
   change the image at array[i]
}

And, thus, only check for and make changes at the 2, in this example, places I need changed. Saving quite a bit of time writing code.

What I currently have to do is have a for-loop and inside the for-loop I have 64 if-else statements, saying

if(p开发者_如何学Canel == 5){
    change the image at 5
}
etc.

I hope this successfully got across what I was trying to ask. If not, I'd be more than happy to clarify.


How are you storing the 64 sub-panels? If your existing code refers to panels as numbers from 0-63 (or 1 - 64) then you could store them in an single dimensional array and then your code yould be:

ImagePanel[] othelloPanels;

void changeImages(int[] indicies) {
    for (int i=0;i<indicies.length;i++) {
        othelloPanels[indicies[i]].change();
    }
}

I would have thought that storing them as two dimensonal (8 by 8) array makes more sense but perhaps that's just me.


How about this:

void changeImages(Image[] images, Set<Integer> positionsToChange) {
    for (int i=0; i < array.length; i++){
        if (positionsToChange.contains(i)) {
            // change the image at array[i]
        }
    }
}


Put your panels into map so that these panels could be easily addressed:

Map<Integer, PanelClass> panelsMap;

Where Integer key is an address of the panel in the map if you use one-dimensional addressing. When your method defines which panels to change it should return an array or Iterable of Integer, then do the following:

for(Integer coord : getPanelIdsToChange()) {
   panelsMap.get(coord).doWhatYouWant();
}


On the base of abhin4v's answer:

void changeImages(Image[] images, Set<Integer> positionsToChange) {
    for (Integer index : positionsToChange) {
        // change the image at images[index]
    }
}

you may put some additional checks in the for loop to be sure that your index is in bounds of your array, but it is not necessary, if you form Set correctly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜