java fx 生成猜数字游戏代码
时间: 2024-06-14 13:03:34 浏览: 151
根据提供的引用内容,没有直接与Java FX生成猜数字游戏代码相关的信息。但是,我们可以提供一些Java FX生成游戏的基本步骤和示例代码,供您参考。
Java FX生成游戏的基本步骤:
1.创建Java FX项目
2.设计游戏界面
3.实现游戏逻辑
4.测试和调试游戏
下面是一个简单的Java FX猜数字游戏示例代码,供您参考:
```java
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import java.util.Random;
public class GuessNumberGame extends Application {
private int randomNumber;
private int guessCount = 0;
@Override
public void start(Stage primaryStage) throws Exception {
// 生成随机数
Random random = new Random();
randomNumber = random.nextInt(100) + 1;
// 创建界面
Label titleLabel = new Label("猜数字游戏");
titleLabel.setStyle("-fx-font-size: 24px; -fx-font-weight: bold;");
Label promptLabel = new Label("请输入1-100之间的整数:");
TextField guessTextField = new TextField();
guessTextField.setPrefWidth(200);
Button guessButton = new Button("猜");
guessButton.setOnAction(event -> {
String guessText = guessTextField.getText();
if (guessText.isEmpty()) {
return;
}
int guessNumber = Integer.parseInt(guessText);
guessCount++;
if (guessNumber == randomNumber) {
showResult("恭喜你,猜对了!", guessCount);
} else if (guessNumber < randomNumber) {
promptLabel.setText("猜小了,请再试一次:");
} else {
promptLabel.setText("猜大了,请再试一次:");
}
});
Button resetButton = new Button("重置");
resetButton.setOnAction(event -> {
guessTextField.setText("");
guessCount = 0;
randomNumber = random.nextInt(100) + 1;
promptLabel.setText("请输入1-100之间的整数:");
});
HBox buttonBox = new HBox(10, guessButton, resetButton);
buttonBox.setAlignment(Pos.CENTER);
VBox rootBox = new VBox(20, titleLabel, promptLabel, guessTextField, buttonBox);
rootBox.setAlignment(Pos.CENTER);
rootBox.setPadding(new Insets(20));
Scene scene = new Scene(rootBox, 400, 300);
primaryStage.setTitle("猜数字游戏");
primaryStage.setScene(scene);
primaryStage.show();
}
private void showResult(String message, int guessCount) {
Stage stage = new Stage();
stage.setTitle("游戏结果");
Label messageLabel = new Label(message);
messageLabel.setStyle("-fx-font-size: 18px; -fx-font-weight: bold;");
Label countLabel = new Label("你猜了" + guessCount + "次。");
countLabel.setStyle("-fx-font-size: 16px;");
Button closeButton = new Button("关闭");
closeButton.setOnAction(event -> stage.close());
VBox rootBox = new VBox(20, messageLabel, countLabel, closeButton);
rootBox.setAlignment(Pos.CENTER);
rootBox.setPadding(new Insets(20));
Scene scene = new Scene(rootBox, 300, 200);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
```
阅读全文