Issue
I have a list of buttons that I use as tiles for my tic tac toe game and I want to make a method to check for a tie which would basically check if the board is full and there is no winner then it is a tie.
I want to grab the text from all the buttons and concat it all into 1 string and when that string's length is 9 and there isn't a winner then it is a tie.
my current method works but I was wondering if there's anyway to be more efficient with it by either using a loop or something
code for initializing the game
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
buttons = new ArrayList<>(Arrays.asList(button1,button2,button3,button4,button5,button6,button7,button8,button9));
buttons.forEach(button ->{
setupButton(button);
button.setFocusTraversable(false);
button.setText("");
});
}
code to check for tie
line2 = button1.getText() + button2.getText() + button3.getText() + button4.getText() + button5.getText() + button6.getText() + button7.getText() + button8.getText() + button9.getText();
if ((line2.length()) == 9 && winner == null) {
ties++;
tiesText.setText(""+ties);
disableAllButtons();
newGame(null);
}
Solution
You could use a counter and increment it on button click. If the counter is 9 it's a tie.
If you want sticking to the buttontext you can use a foreach loop like :
line2 = "";
foreach (Button button : buttons){
line2 += button.getText();
}
Answered By - valentin
Answer Checked By - Candace Johnson (JavaFixing Volunteer)