我有一個按鈕串列,用作我的井字游戲的圖塊,我想制定一種方法來檢查平局,該方法基本上可以檢查棋盤是否已滿并且沒有贏家,那么它就是平局。
我想從所有按鈕中獲取文本并將其全部連接到 1 個字串中,當該字串的長度為 9 并且沒有獲勝者時,則為平局。
我目前的方法有效,但我想知道是否有任何方法可以通過使用回圈或其他方式來提高效率
游戲初始化代碼
@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("");
});
}
檢查領帶的代碼
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);
}
uj5u.com熱心網友回復:
您可以使用計數器并在單擊按鈕時增加它。如果計數器為 9,則為平局。
如果你想堅持按鈕文本,你可以使用像這樣的 foreach 回圈:
line2 = "";
foreach (Button button : buttons){
line2 = button.getText();
}
uj5u.com熱心網友回復:
您可以在串聯字串系結上創建一個偵聽器,然后使用它來監視所有按鈕的串聯文本。
例如:
StringExpression state = Bindings.concat(
board.getChildren().stream()
.map(node -> ((Button) node).textProperty())
.toArray()
);
state.addListener((observable, oldState, newState) ->
handleStateChange(newState)
);
這可能比必要的要復雜一些。對于基本解決方案,只需對按鈕點擊做出反應并在回圈中更新狀態(如
背景關系中的示例
- 使用 James 的建議,檢查線路以檢測平局。
- 使用 Java 17 功能。
應用代碼
import javafx.application.*;
import javafx.beans.binding.*;
import javafx.geometry.Insets;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.layout.TilePane;
import javafx.stage.*;
public class NoughtsAndCrosses extends Application {
private static final int NUM_SQUARES = 9;
private static final String X = "X";
private static final String O = "O";
private static final String TIE = "-";
private static final String NONE = " ";
private String nextPlayer = X;
private Scene scene;
private static final int[][] LINES = {
{1,2,3}, {4,5,6}, {7,8,9}, // horizontal
{1,4,7}, {2,5,8}, {3,6,9}, // vertical
{1,5,9}, {3,5,7} // diagonal
};
public void start(Stage stage) {
scene = new Scene(newGame());
stage.setScene(scene);
stage.setTitle("Noughts and Crosses");
stage.show();
}
private Parent newGame() {
TilePane board = createBoard();
if (scene != null) {
scene.setRoot(board);
}
return board;
}
private TilePane createBoard() {
TilePane board = new TilePane(10, 10);
board.setStyle("-fx-base: antiquewhite; -fx-font-size: 30; -fx-font-weight: bold;");
board.setPadding(new Insets(10));
board.setPrefColumns(3);
board.setMinSize(Control.USE_PREF_SIZE, Control.USE_PREF_SIZE);
board.setMaxSize(Control.USE_PREF_SIZE, Control.USE_PREF_SIZE);
for (int i = 0; i < NUM_SQUARES; i ) {
board.getChildren().add(createSquare());
}
StringExpression state = Bindings.concat(
board.getChildren().stream()
.map(node -> ((Button) node).textProperty())
.toArray()
);
state.addListener((observable, oldState, newState) ->
handleStateChange(newState)
);
return board;
}
private Button createSquare() {
final Button square = new Button(NONE);
square.setMinSize(Control.USE_PREF_SIZE, Control.USE_PREF_SIZE);
square.setPrefSize(65, 65);
square.setMaxSize(Control.USE_PREF_SIZE, Control.USE_PREF_SIZE);
square.setOnAction(e -> takeTurn(square));
return square;
}
private void takeTurn(Button square) {
square.setText(nextPlayer);
nextPlayer = X.equals(nextPlayer) ? O : X;
}
private void handleStateChange(String state) {
int nTies = 0;
for (int[] line : LINES) {
String result = checkResult(line, state);
switch (result) {
case X -> { endGame(X); return; }
case O -> { endGame(O); return; }
case TIE -> nTies ;
}
}
if (nTies == LINES.length) {
endGame(TIE);
}
}
private String checkResult(int[] line, String state) {
int numX = 0, numO = 0;
for (int j : line) {
String cellState = state.substring(j - 1, j);
switch (cellState) {
case X -> numX ;
case O -> numO ;
}
}
if (numX == 3) {
return X;
}
if (numO == 3) {
return O;
}
if (numX > 0 && numO > 0) {
return TIE;
}
return NONE;
}
private void endGame(String result) {
String msg = switch (result) {
case X -> X " won";
case O -> O " won";
case TIE -> "Tie";
default -> "unexpected result";
};
Alert resultDialog = new Alert(
Alert.AlertType.CONFIRMATION,
"""
Play again?
%s will start first.
""".formatted(X.equals(nextPlayer) ? O : X)
);
resultDialog.setHeaderText(msg);
resultDialog.setTitle("Game Over");
resultDialog.initOwner(
scene.getWindow()
);
// we do this in a run later as we want the board state to update for
// the last interaction before displaying the result dialog.
Platform.runLater(() ->
resultDialog.showAndWait()
.filter(response -> response == ButtonType.OK)
.ifPresentOrElse(
response -> newGame(),
Platform::exit
)
);
}
public static void main(String[] args) {
launch(args);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/381879.html
