龙空技术网

JAVA语言编写猜字谜小程序,解压又好玩

打篮球的程序员独城人 313

前言:

而今同学们对“java实用小程序”都比较关注,兄弟们都需要了解一些“java实用小程序”的相关知识。那么小编同时在网络上收集了一些有关“java实用小程序””的相关内容,希望朋友们能喜欢,你们一起来了解一下吧!

import javafx.application.Application;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.VBox;import javafx.stage.Stage;import java.util.Random;public class GuessTheWordGame extends Application {    private static final String[] WORDS = {"apple", "banana", "cherry", "grape", "orange", "pear"};        private Random random = new Random();    private String currentWord;    private int attempts = 3;        private Label instructionLabel;    private Label attemptsLabel;    private TextField guessTextField;    private Button submitButton;    private Label resultLabel;    private void startNewGame() {        currentWord = WORDS[random.nextInt(WORDS.length)];        attempts = 3;        instructionLabel.setText("Guess the word:");        attemptsLabel.setText("Attempts remaining: " + attempts);        guessTextField.setDisable(false);        guessTextField.clear();        submitButton.setDisable(false);        resultLabel.setText("");    }    @Override    public void start(Stage primaryStage) {        instructionLabel = new Label("Guess the word:");        attemptsLabel = new Label("Attempts remaining: " + attempts);        guessTextField = new TextField();        submitButton = new Button("Submit");        resultLabel = new Label("");                submitButton.setOnAction(e -> {            String guess = guessTextField.getText().toLowerCase();            if (guess.equals(currentWord)) {                resultLabel.setText("Congratulations! You guessed the word.");                guessTextField.setDisable(true);                submitButton.setDisable(true);            } else {                attempts--;                attemptsLabel.setText("Attempts remaining: " + attempts);                if (attempts <= 0) {                    resultLabel.setText("Sorry, you've run out of attempts. The word was: " + currentWord);                    guessTextField.setDisable(true);                    submitButton.setDisable(true);                } else {                    resultLabel.setText("Incorrect guess. Try again.");                }            }        });        VBox root = new VBox(10);        root.setAlignment(Pos.CENTER);        root.getChildren().addAll(instructionLabel, attemptsLabel, guessTextField, submitButton, resultLabel);        Scene scene = new Scene(root, 300, 200);        primaryStage.setTitle("Guess The Word Game");        primaryStage.setScene(scene);        primaryStage.show();                startNewGame();    }    public static void main(String[] args) {        launch(args);    }}

标签: #java实用小程序