I am making a complex tic tac toe program that has a variable grid size and player amount. But one of my friends commented that it is a little slow respond after they make a move in a 64 by 64 space. I looked into it and I have found the issue, my program checks every button in the grid to see if it was clicked, then it checks every player to see who made the move. Once it has found both out, it moves on with life :D. But that can take some time when working with a larger grid. so I made an attempt at fixing it by putting in some “breaks;”, but they didn’t help to find it faster, only to stop looking faster.
public void actionPerformed(ActionEvent gridButtonClicked) {
for (int i = 0; i < gridButton.length; i++) {
if (gridButtonClicked.getSource() == gridButton[i]) {
for(int a = 0;a < amountOfPlayers;a++){
if(turn == a) {
gridButtonOwner[i] = a + 1;
gridButton[i].setBackground(playerColors[a]);
gridButton[i].setEnabled(false);
System.out.println("Grid " + i + ": " + gridButtonOwner[i]);
break;
}
}
break;
}
}
}
What I want to know is that if I can get the array number of the button clicked. Like if gridButtonClicked = gridButton[1], it would return the number 1, or if it equaled gridButton[2] it would return 2, etc.
- gridButtonOwner is a int array,
- gridButton is a jbutton array.
I must say i don’t understand the need for the loops. In the first for-loop you’re getting the grid-button – but you know what this is because it’s the event source… You can just store a map of
GridButtononto Integer to get the place in your array. Why loop to find it? In the second loop you’re looping untila == turn… Which means you already know whatais because it== turn. You should be able to remove the loops completely: