使用JavaFX完成刽子手游戏

使用JavaFX完成刽子手游戏

1.1 题目说明

在这里插入图片描述

1.2 分析过程

本题让我画一个小人,首先使用new Arc()命令绘制半个椭圆当基座,然后使用new Line()绘制线条,line1和line2绘制杆,line3绘制绳子,然后用new Circle()命令画圆,circle当做小人的头,用line4、line5画小人的手、line6画身子和line7、line8画脚,准备做好后,创建一个Pane面板,然后使用getChildren()方法中的add()方法将所有小组件放到面板中。

1.3系统测试

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-1C1lg05f-1640435147141)(file:///C:\Users\25016\AppData\Local\Temp\ksohtml\wpsE6AC.tmp.jpg)]

1.4代码展示

package version2;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Arc;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Line;
import javafx.stage.Stage;



/**
 * @Auther: paradise
 * @Date: 2021/6/24 - 06 - 24 - 16:33
 */
public class Executioner extends Application {
    @Override
    public void start(Stage primaryStage) throws Exception {
        Pane pane = new Pane();
        Arc arc = new Arc(80,280,50,25,0,180);
        arc.setFill(Color.WHITE);
        arc.setStroke(Color.BLACK);

        Line line1 = new Line(80,255,80,30);
        Line line2 = new Line(80,30,260,30);
        Line line3 = new Line(260,30,260,50);

        Circle circle = new Circle(260,80,30);
        circle.setStroke(Color.BLACK);
        circle.setFill(Color.WHITE);

        Line line4 = new Line(260-30*Math.cos(Math.toRadians(30)),80+30*Math.sin(Math.toRadians(30)),260-100*Math.sin(Math.toRadians(60)),160);
        Line line5 = new Line(260+30*Math.cos(Math.toRadians(30)),80+30*Math.sin(Math.toRadians(30)),260+100*Math.sin(Math.toRadians(60)),160);
        Line line6 = new Line(260,110,260,210);
        Line line7 = new Line(260,210,260-100*Math.sin(Math.toRadians(60)),275);
        Line line8 = new Line(260,210,260+100*Math.sin(Math.toRadians(60)),275);

        pane.getChildren().addAll(arc,line1,line2, line3,circle,line4,line5,line6,line7,line8);

        Scene scene = new Scene(pane,400,300);
        primaryStage.setTitle("HangMan Game");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

}

2.1 题目说明

​ 结合以上两个功能,实现动画方式的侩子手游戏,当用户猜错 7 次,绞刑架上的人摆动。当一个单词完成后,用户使用回车键继续猜下一个单词。

初始状态如下:

在这里插入图片描述
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-enQGhtHr-1640435147142)(file:///C:\Users\25016\AppData\Local\Temp\ksohtml\wps8B93.tmp.jpg)][外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-SVUajQNS-1640435147143)(file:///C:\Users\25016\AppData\Local\Temp\ksohtml\wps995F.tmp.jpg)]

2.2 分析过程

创建一个名为missNum和guessNum,都为int类型的私有数据域,missNum为猜错的次数,guessNum为猜测的次数,同时声明一个名为missWord、wordMessage、word,类型为String的私有数据域,由于题目要求,当全部输出错误的时候,小人需要晃动,所以我在这里设置了两个Pane面板,一个名为pane的面板用于整体布局,一个用于名为laterPane的面板,当回答七次之后,在上面绘制小人,然后让这个面板转动起来。arc用于绘制基座,line1和lin2用于绘制杆,名为message和word的Label标签用于显示信息,一个名为info用于显示错误信息,一个名为textField的文本域供用户输入,这里使用setLayoutX()方法和setLayoutY()方法进行布局。

设置完界面之后,便开始进行事件处理,使用getText()方法获取用户在文本框中输入的信息,系统在这个使用已经调用了chooseWord()方法随机生成了一个单词,用户没进行一次猜测的时候,guessNum都会加1,当missedNum小于7的时候,判断用户输入的字母是否在单词中,如果在的话,使用for循环和if判断语句看单词中是否出现多次,使用一个字符串str存储输入的字符,如果不在的话,str加上*号,每一次输入完成后,都需要将str赋值给wordMessage,如果猜测的单词和系统产生的单词相同,则把画出相应的部分,当猜测的时候,猜错一个单词就会依次画出绳子、小人的头、左手、身子、右手、左脚、右脚,这里我使用了一个switch判断,当猜测错误一次的时候,向面板中添加绳子;当猜测错误为两次时,向面板中添加头;当猜测错误为三次时,向面板中添加左手;当猜测错误为四次时,向面板中添加身体;当猜测错误为五次时,向面板中添加右手;当猜测错误为六次时,向面板中添加左腿;当猜测错误为七次时,向面板中添加右腿;然后将这些组件添加到laterPane面板里,我在这里使用setRotate方法进行面板的旋转,newRotate()方法进行角度设置,然后一个double类型的数据。

由于无论猜测成功还是失败,我们都需要重新开始游戏,所以我设置了一个事件处理,但按下回车键并且猜测成功或猜错次数大于7次的时候,重置面板,初始错误次数为0,猜测次数为0,并且面板上有基座和杆。

相关函数:

paintHead():画小人的头

PaintLeftArm():画小人的左手

PaintRope():画绳子

PaintRightArm():画小人的右手

PaintBody():画小人的身子

paintLeftLeg():画小人的左腿

PaintRightLeg():画小人的右腿

2.3 系统测试

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-3ZlXfYvS-1640435147143)(file:///C:\Users\25016\AppData\Local\Temp\ksohtml\wps5FDC.tmp.jpg)]

2.4 代码展示

package version3;

import javafx.application.Application;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Arc;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Line;
import javafx.stage.Stage;
import javafx.util.Duration;

import java.util.Random;

/**
 * @Auther: paradise
 * @Date: 2021/6/24 - 06 - 24 - 16:35
 */
public class Game3 extends Application {
    private int missedNum=0;
    private int guessNum=0;
    private String missWord = "";//错误信息
    private String wordMessage = "";//单词信息
    private String word = "";//随机的单词
    private Line line4 = new Line(260-30*Math.cos(Math.toRadians(30)),80+30*Math.sin(Math.toRadians(30)),260-100*Math.sin(Math.toRadians(60)),160);
    private  Line line5 = new Line(260, 30, 260, 50);
    private Line line6 =  new Line(260+30*Math.cos(Math.toRadians(30)),80+30*Math.sin(Math.toRadians(30)),260+100*Math.sin(Math.toRadians(60)),160);
    private  Line line7 = new Line(260, 110, 260, 210);
    private Line line8 = new Line(260, 210, 260 - 100 * Math.sin(Math.toRadians(60)), 270);
    private Line line9 = new Line(260, 210, 260 + 100 * Math.sin(Math.toRadians(60)), 275);
    private Circle circle = new Circle(260, 80, 30);
    @Override
    public void start(Stage primaryStage) throws Exception{
        final Pane pane = new Pane();
        final Arc arc = new Arc(80,280,50,25,0,180);//底座
        arc.setFill(Color.WHITE);
        arc.setStroke(Color.BLACK);

        final Pane laterPane = new Pane();
        laterPane.setPrefSize(520,60);

        final Line line1 = new Line(80,255,80,30);//底座竖杆
        final Line line2 = new Line(80,30,260,30);//底座横杆
        pane.getChildren().addAll(arc,line1,line2);

        final Label message = new Label("Guess a word:");
        message.setLayoutX(220);
        message.setLayoutY(280);
        pane.getChildren().add(message);

        final Label words = new Label("******");
        words.setLayoutX(320);
        words.setLayoutY(280);
        pane.getChildren().add(words);

        final Label info = new Label("");//显示错误信息
        info.setLayoutX(220);
        info.setLayoutY(310);
        pane.getChildren().add(info);

        final TextField textField = new TextField();
        textField.setLayoutX(220);
        textField.setLayoutY(340);
        pane.getChildren().add(textField);


        textField.setOnKeyReleased(new EventHandler<KeyEvent>() {
            public void handle(KeyEvent event) {
                if (event.getCode() == KeyCode.ENTER && (wordMessage.equals(word) || missedNum >= 7)) {
                    pane.getChildren().clear();
                    missedNum = 0;
                    guessNum = 0;
                    words.setText("******");
                    info.setText("");
                    textField.setText("");
                    wordMessage = "";
                    missWord = "";

                    pane.getChildren().addAll(arc, line1, line2, message, words, info, textField);
                }

                String chr = textField.getText().trim();

                if (!chr.equals("")) {
                    if (missedNum % 7 == 0 && guessNum == 0) {
                        String[] words = {"write", "that", "program", "animal", "version", "world"};
                        word = chooseWord(words);
                    }

                    guessNum++;

                    if (missedNum < 7) {
                        if (word.indexOf(chr.charAt(0)) != -1) {
                            String str = "";
                            words.setText("");
                            for (int j = 0; j < word.length(); j++) {
                                if (chr.charAt(0) == word.charAt(j)) {
                                    str += chr.charAt(0);
                                }
                                else {
                                    if (wordMessage.length() > j) {
                                        if (wordMessage.charAt(j) != '*'){
                                            str += wordMessage.charAt(j);
                                        }
                                        else str += '*';
                                    }
                                    else str += '*';
                                }
                            }
                            words.setText(str);
                            wordMessage = str;
                            if (wordMessage.equals(word)) {
                                //猜词成功
                                info.setText("Guess successfully.To continue the game,press Enter.");
                                pane.getChildren().clear();
                                laterPane.getChildren().addAll(line4,line5,circle);
                                pane.getChildren().addAll(line1,line2,arc,laterPane,message,words,info,textField);
                            }
                        } else {
                            missWord += chr.charAt(chr.length()-1);
                            switch (missedNum) {
                                case 0:
                                    pane.getChildren().add(paintRope());
                                    break;
                                case 1:
                                    pane.getChildren().add(paintHead());
                                    break;
                                case 2:
                                    pane.getChildren().add(paintLeftArm());
                                    break;
                                case 3:
                                    pane.getChildren().add(paintBody());
                                    break;
                                case 4:
                                    pane.getChildren().add(paintRightArm());
                                    break;
                                case 5:
                                    pane.getChildren().add(paintLeftLeg());
                                    break;
                                case 6:
                                    pane.getChildren().add(paintRightLeg());

                                    pane.getChildren().clear();
                                    laterPane.getChildren().addAll(line4,line5,line6,line7,line8,line9,circle);
                                    pane.getChildren().addAll(line1,line2,arc,laterPane,message,words,info,textField);
                                    EventHandler<ActionEvent> eventHandler = e -> {
                                        laterPane.setRotate(newRotate());//旋转角度setRotate(角度)
                                    };
                                    Timeline rotateFan = new Timeline(new KeyFrame(Duration.millis(100), eventHandler));
                                    rotateFan.setCycleCount(Timeline.INDEFINITE);
                                    rotateFan.play();//开始动画

                                    break;
                            }
                            missedNum++;
                            info.setText("Missed Letters:" + missWord);
                        }
                    } else {
                        info.setText("Guess failed!To continue the game,press Enter");
                    }

                }
                textField.setText("");
            }
        });

        Scene scene = new Scene(pane, 800, 600, Color.WHITE);
        primaryStage.setTitle("Hangman Game");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    //选择数组中一个元素的方法
    public static String chooseWord(String[] s){
        Random random = new Random();
        int num = random.nextInt(s.length);
        String word = s[num];
        return word;
    }

    private Circle paintHead() {
        //头
        circle.setStroke(Color.BLACK);
        circle.setFill(Color.WHITE);
        return circle;
    }

    private Line paintLeftArm() {
        return line4;//左胳膊
    }

    private Line paintRope() {
        return line5 ;//底座吊绳
    }

    private Line paintRightArm() {
        return line6;//右胳膊
    }

    private Line paintBody() {
        return line7;//躯干
    }

    private Line paintLeftLeg() {
        return line8;//左腿
    }

    private Line paintRightLeg() {
        return line9;//右腿
    }

    public static void main(String[] args) {
        launch(args);
    }

    boolean direction=true;
    int rotate=10;
    int speed=5;
    int counts=0;

    public double newRotate()
    {
        if(rotate/80 == 1||rotate/80 == -1) {
            direction = !direction;
        }
        if (direction)
        {
            counts++;
            return rotate = (rotate + speed) % 360;
        }
        else
        {
            return rotate = (rotate - speed) % 360;
        }
    }
}
speed=5;
    int counts=0;

    public double newRotate()
    {
        if(rotate/80 == 1||rotate/80 == -1) {
            direction = !direction;
        }
        if (direction)
        {
            counts++;
            return rotate = (rotate + speed) % 360;
        }
        else
        {
            return rotate = (rotate - speed) % 360;
        }
    }
}
  • 5
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是基于 JavaFX 实现动画方式的 Hangman 游戏的示例代码: ```java import javafx.animation.RotateTransition; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; 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.input.KeyCode; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.layout.StackPane; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; import javafx.scene.shape.Line; import javafx.scene.text.Font; import javafx.stage.Stage; import javafx.util.Duration; public class HangmanGame extends Application { private static final int MAX_INCORRECT_GUESSES = 7; private static final String[] WORDS = {"HELLO", "WORLD", "JAVA", "FX"}; private static final Font WORD_FONT = new Font(30); private static final Font GUESS_FONT = new Font(18); private static final int WORD_SPACING = 20; private static final int GUESS_SPACING = 10; private static final int PANE_WIDTH = 500; private static final int PANE_HEIGHT = 500; private String word; private char[] wordChars; private char[] guessChars; private int incorrectGuesses; private Label wordLabel; private Label guessLabel; private TextField guessField; private Button guessButton; private Pane hangmanPane; @Override public void start(Stage primaryStage) { BorderPane root = new BorderPane(); root.setTop(createWordPane()); root.setCenter(createGuessPane()); root.setBottom(createInputPane()); Scene scene = new Scene(root, PANE_WIDTH, PANE_HEIGHT); primaryStage.setScene(scene); primaryStage.setTitle("Hangman Game"); primaryStage.show(); startNewGame(); } private Pane createWordPane() { wordLabel = new Label(); wordLabel.setFont(WORD_FONT); StackPane pane = new StackPane(); pane.getChildren().add(wordLabel); return pane; } private Pane createGuessPane() { guessLabel = new Label(); guessLabel.setFont(GUESS_FONT); StackPane pane = new StackPane(); pane.getChildren().add(guessLabel); return pane; } private HBox createInputPane() { guessField = new TextField(); guessField.setPrefWidth(100); guessField.setOnKeyPressed(event -> { if (event.getCode() == KeyCode.ENTER) { handleGuess(); } }); guessButton = new Button("Guess"); guessButton.setOnAction(event -> handleGuess()); HBox pane = new HBox(GUESS_SPACING, guessField, guessButton); pane.setAlignment(Pos.CENTER); return pane; } private Pane createHangmanPane() { hangmanPane = new Pane(); Circle head = new Circle(50, Color.TRANSPARENT); head.setStroke(Color.BLACK); head.setStrokeWidth(5); head.setCenterX(250); head.setCenterY(100); Line body = new Line(250, 150, 250, 300); body.setStroke(Color.BLACK); body.setStrokeWidth(5); Line leftArm = new Line(250, 200, 200, 250); leftArm.setStroke(Color.BLACK); leftArm.setStrokeWidth(5); Line rightArm = new Line(250, 200, 300, 250); rightArm.setStroke(Color.BLACK); rightArm.setStrokeWidth(5); Line leftLeg = new Line(250, 300, 200, 350); leftLeg.setStroke(Color.BLACK); leftLeg.setStrokeWidth(5); Line rightLeg = new Line(250, 300, 300, 350); rightLeg.setStroke(Color.BLACK); rightLeg.setStrokeWidth(5); hangmanPane.getChildren().addAll(head, body, leftArm, rightArm, leftLeg, rightLeg); hangmanPane.setTranslateX(PANE_WIDTH / 2 - 250); hangmanPane.setTranslateY(PANE_HEIGHT / 2 - 200); return hangmanPane; } private void startNewGame() { word = WORDS[(int) (Math.random() * WORDS.length)]; wordChars = word.toCharArray(); guessChars = new char[wordChars.length]; incorrectGuesses = 0; wordLabel.setText(String.join(" ", String.valueOf(guessChars))); guessLabel.setText(""); if (hangmanPane != null) { hangmanPane.getChildren().clear(); } guessField.setDisable(false); guessButton.setDisable(false); guessField.requestFocus(); } private void handleGuess() { String guessText = guessField.getText().toUpperCase(); if (guessText.length() == 1 && Character.isLetter(guessText.charAt(0))) { char guess = guessText.charAt(0); boolean found = false; for (int i = 0; i < wordChars.length; i++) { if (wordChars[i] == guess) { guessChars[i] = guess; found = true; } } if (!found) { incorrectGuesses++; if (incorrectGuesses >= MAX_INCORRECT_GUESSES) { guessField.setDisable(true); guessButton.setDisable(true); guessLabel.setText("You lose! The word was: " + word); createHangmanPane(); RotateTransition rotate = new RotateTransition(Duration.seconds(1), hangmanPane); rotate.setByAngle(30); rotate.setCycleCount(6); rotate.setAutoReverse(true); rotate.setOnFinished(event -> startNewGame()); rotate.play(); } } else if (String.valueOf(guessChars).equals(word)) { guessField.setDisable(true); guessButton.setDisable(true); guessLabel.setText("You win! The word was: " + word); startNewGame(); } wordLabel.setText(String.join(" ", String.valueOf(guessChars))); guessLabel.setText("Incorrect guesses: " + incorrectGuesses); guessField.setText(""); guessField.requestFocus(); } } public static void main(String[] args) { launch(args); } } ``` 在该游戏中,创建了一个包含单词区、猜测区和输入区的 BorderPane。单词区和猜测区使用 Label 来显示单词和猜测结果,输入区使用 TextField 和 Button 来接收用户猜测。当用户猜错时,将在 hangmanPane 上绘制一个绞刑架,同时将 hangmanPane 在窗口中旋转。当用户猜中或猜错次数达到最大值时,将调用 startNewGame() 方法开始新游戏。 该游戏使用JavaFX 动画库中的 RotateTransition 类来实现旋转绞刑架的效果。通过设置旋转角度、持续时间、重复次数等参数,可以非常方便地实现旋转动画效果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值