我的问题得到了回答,我的问题得到了解决。我已经更新了这个线程与我的最终解决方案
我正在做这个学校作业(测验程序),我们最初只需要做一个纯粹的基于文本的控制台游戏,但我想挑战自己,试着用JavaFX创建它,我们刚刚开始学习。
这是一个基于回合的问答游戏,玩家将被呈现一个问题,要求玩家通过两个按钮(对或错按钮)回答对/错
游戏流程:
我正在运行一个for循环,只要我的ArrayList中还有问题,这个循环就会继续。
理想的流程如下所示:
0)输入姓名并按:开始游戏按钮1)向玩家1提出问题。2) 通过True按钮或False按钮接收输入。3) 将输入与从数组中提取的正确答案进行比较。4) 如果正确,用户得到1分-如果错误,继续玩家2。5) 换成玩家2,重新开始,直到ArrayList中没有更多问题。
我已经让我的循环“正常运行”,从某种意义上说,它改变了玩家,并一直持续到ArrayList中不再有问题为止。
问题我希望for循环通过true/false按钮等待用户输入。但是,for循环在不等待输入的情况下运行整个程序。
问题:是否可以“暂停”for循环并让它等待来自两个按钮之一的输入?你有没有建议我用其他html" target="_blank">方法来处理这个问题?
如果你愿意直接解决这个问题,我会非常高兴。无论是通过这个论坛还是通过给我发一个链接来进一步阅读都是可以的。我似乎无法通过谷歌搜索或搜索这个论坛找到解决方案。
代码用System.out.println()填充,让我看看程序运行了多远。请把目光移开。
而且任何关于如何改进代码的建议都将不胜感激。Java编程才8周,希望学习如何做得更聪明。
主代码
package sample;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
primaryStage.setTitle("Expert Quiz Game");
primaryStage.setScene(new Scene(root, 800, 600));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
控制器代码
package sample;
import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.text.Text;
import java.util.Random;
public class Controller {
@FXML
TextField player1;
@FXML
TextField player2;
@FXML
Text score1;
@FXML
Text score2;
@FXML
Text questionText;
@FXML
Text questionsLeft;
@FXML
Text gameStatus;
@FXML
Button startGame;
@FXML
Button buttonTrue;
@FXML
Button buttonFalse;
//@FXML
//Button nextRound;
@FXML
private void handleStartGame(ActionEvent event) {
// ******* DECLARE VARIABLES ********
String playerOneName = player1.getText(); //Saves the name for later use
String playerTwoName = player2.getText(); //Saves the name for later use
int playerOneScore = 0;
int playerTwoScore = 0;
Random randomQuestionNumber1 = new Random();
//Random randomQuestionNumber2 = new Random();
System.out.println(playerOneName + " TEST"); //To TEST if the name is saved
System.out.println(playerTwoName + " TEST"); //To TEST if the name is saved
// ******* DECLARE QUESTION ARRAY ********
ArrayList<String> questionsArray = new ArrayList<String>();
questionsArray.add("Question 1");
questionsArray.add("Question 2");
questionsArray.add("Question 3");
questionsArray.add("Question 4");
questionsArray.add("Question 5");
questionsArray.add("Question 6");
// ******* DECLARE ANSWER ARRAY ********
ArrayList<String> answerArray = new ArrayList<String>();
answerArray.add("True");
answerArray.add("True");
answerArray.add("False");
answerArray.add("True");
answerArray.add("False");
answerArray.add("True");
//int randomQuestionA = randomQuestionNumber1.nextInt(questionsArray.size()); //+0
//int randomQuestionB = randomQuestionNumber2.nextInt(questionsArray.size()); //+0
//Button clickedButton = (Button) event.getTarget();
//String buttonLabel = clickedButton.getText();
int player = 1;
for (int i = 0; i < questionsArray.size(); i++) {
if (player == 1) {
int randomQuestionA = randomQuestionNumber1.nextInt(questionsArray.size());
// ****** RETRIEVE AND PRESENT FIRST QUESTION ******
System.out.println("1. Player: " + playerOneName); // WRITE TO CONSOLE THE CURRENT PLAYER * CAN BE REMOVED
questionText.setText("Question: " + questionsArray.get(randomQuestionA)); // PRINTS QUESTION TO THE UI
System.out.println("2. "+questionsArray.get(randomQuestionA)); // WRITES TO CONSOLE THE QUESTION * CAN BE REMOVED
// ****** GET ANSWER FOR THE QUESTION ******
String answerFromArray = answerArray.get(randomQuestionA); // TAKES THE ANSWER FROM THE ARRAY AND SAVES AS A NEW STRING
System.out.println("3." + answerArray.get(randomQuestionA)); // WRITES THE ANSWER FROM THE ARRAY TO CONSOLE * CAN BE REMOVED
// ****** TEST IF ANSWER IS TRUE ******
String buttonTrueText = buttonTrue.getText(); // SAVES THE BUTTON TEXT AS A STRING FOR LATER COMPARISON
String buttonFalseText = buttonFalse.getText(); // SAVES THE BUTTON TEXT AS A STRING FOR LATER COMPARISON
// ****** IF TRUE, THEN COUNT ONE UP IN SCORE ******
buttonTrue.setOnAction(e -> {
System.out.println("4. Now running"); // WRITES TO CONSOLE * CAN BE REMOVED
String buttonAnswer = " "; // INITIALIZES THE VARIABLE WITH AN EMPTY STRING
handleButtonAnswer(event);
/**if (buttonText.equals("True")) { // REGISTERS THE BUTTON PRESSED AND SAVES IT IN A VARIABLE
buttonAnswer = "True";
} else if (buttonText.equals("False")) { // REGISTERS THE BUTTON PRESSED AND SAVES IT IN A VARIABLE
buttonAnswer = "False";
}**/
if (buttonAnswer == "True" || buttonAnswer == "False") {
System.out.println("5. Test");
}
System.out.println("6. "+buttonAnswer);
if (answerFromArray.equals(buttonAnswer)) {
System.out.println("7. Answer was correct - Need to count one up in score");//
}
score1.setText("Points: " + playerOneScore+1);
System.out.println("8. "+playerOneScore+1);
questionsArray.remove(randomQuestionA); // REMOVES QUESTION FROM ARRAYLIST
answerArray.remove(randomQuestionA); // REMOVES ANSWER FROM ARRAYLIST
int remainingQuestions = questionsArray.size();
questionsLeft.setText(remainingQuestions + " questions left");
});
// ****** REMOVE THAT QUESTION + ANSWER FROM THE ARRAY ******
// ****** CHANGE PLAYER AND START AGAIN ******
player = 2;
System.out.println("Changing to player " +player);
} else if (player == 2) {
//clickedButton.setText("O");
int randomQuestionA = randomQuestionNumber1.nextInt(questionsArray.size());
// ****** RETRIEVE AND PRESENT FIRST QUESTION ******
System.out.println("1. Player: " + playerOneName); // WRITE TO CONSOLE THE CURRENT PLAYER * CAN BE REMOVED
questionText.setText("Question: " + questionsArray.get(randomQuestionA)); // PRINTS QUESTION TO THE UI
System.out.println("2. "+questionsArray.get(randomQuestionA)); // WRITES TO CONSOLE THE QUESTION * CAN BE REMOVED
// ****** GET ANSWER FOR THE QUESTION ******
String answerFromArray = answerArray.get(randomQuestionA); // TAKES THE ANSWER FROM THE ARRAY AND SAVES AS A NEW STRING
System.out.println("3." + answerArray.get(randomQuestionA)); // WRITES THE ANSWER FROM THE ARRAY TO CONSOLE * CAN BE REMOVED
// ****** TEST IF ANSWER IS TRUE ******
String buttonTrueText = buttonTrue.getText(); // SAVES THE BUTTON TEXT AS A STRING FOR LATER COMPARISON
String buttonFalseText = buttonFalse.getText(); // SAVES THE BUTTON TEXT AS A STRING FOR LATER COMPARISON
// ****** IF TRUE, THEN COUNT ONE UP IN SCORE ******
buttonTrue.setOnAction(e -> {
System.out.println("4. Now running"); // WRITES TO CONSOLE * CAN BE REMOVED
String buttonAnswer = " "; // INITIALIZES THE VARIABLE WITH AN EMPTY STRING
handleButtonAnswer(event);
/**if (buttonText.equals("True")) { // REGISTERS THE BUTTON PRESSED AND SAVES IT IN A VARIABLE
buttonAnswer = "True";
} else if (buttonText.equals("False")) { // REGISTERS THE BUTTON PRESSED AND SAVES IT IN A VARIABLE
buttonAnswer = "False";
}**/
if (buttonAnswer == "True" || buttonAnswer == "False") {
System.out.println("5. Test");
}
System.out.println("6. "+buttonAnswer);
if (answerFromArray.equals(buttonAnswer)) {
System.out.println("7. Answer was correct - Need to count one up in score");//
}
score1.setText("Points: " + playerOneScore+1);
System.out.println("8. "+playerOneScore+1);
questionsArray.remove(randomQuestionA); // REMOVES QUESTION FROM ARRAYLIST
answerArray.remove(randomQuestionA); // REMOVES ANSWER FROM ARRAYLIST
int remainingQuestions = questionsArray.size();
questionsLeft.setText(remainingQuestions + " questions left");
});
// ****** REMOVE THAT QUESTION + ANSWER FROM THE ARRAY ******
// ****** CHANGE PLAYER AND START AGAIN ******
player = 1;
System.out.println("Changing to player " +player);
}
}
}
@FXML
private String handleButtonAnswer(ActionEvent event) {
String buttonAnswer = "";
// (1)
Button b = (Button) event.getSource();
// (2)
String t = b.getText();
System.out.println("4. the text on the button was: "+t);
if (t.equals("True")){
buttonAnswer = "True"; // demo
}else if (t.equals("False")){
buttonAnswer = "False";
}
return buttonAnswer;
}
}
fxml代码
设计还没有完成-需要它的工作,然后再造型它正确
<?xml version="1.0" encoding="UTF-8"?><?import javafx.scene.text.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="600.0" prefWidth="794.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Controller">
<children>
<Label layoutX="225.0" layoutY="47.0" prefHeight="66.0" prefWidth="334.0" text="Java ExpertQuiz" textAlignment="CENTER">
<font>
<Font name="Cambria Bold" size="45.0" />
</font>
</Label>
<TextField fx:id="player1" layoutX="79.0" layoutY="154.0" prefHeight="39.0" prefWidth="201.0" promptText="Enter name for player1" />
<TextField fx:id="player2" layoutX="503.0" layoutY="154.0" prefHeight="39.0" prefWidth="222.0" promptText="Enter name for player2" />
<Text fx:id="score1" layoutX="79.0" layoutY="232.0" strokeType="OUTSIDE" strokeWidth="0.0" text="Ponits" />
<Text fx:id="score2" layoutX="503.0" layoutY="232.0" strokeType="OUTSIDE" strokeWidth="0.0" text="Points" />
<Text fx:id="questionText" layoutX="38.0" layoutY="315.0" strokeType="OUTSIDE" strokeWidth="0.0" text="Question" textAlignment="CENTER" wrappingWidth="717.1240234375">
<font>
<Font size="38.0" />
</font>
</Text>
<Button fx:id="startGame" layoutX="318.0" layoutY="154.0" mnemonicParsing="false" onAction="#handleStartGame" text="Start game" />
<Text fx:id="questionsLeft" layoutX="301.0" layoutY="505.0" strokeType="OUTSIDE" strokeWidth="0.0" text="Questions left: " textAlignment="CENTER" wrappingWidth="191.9072265625" />
<Text fx:id="gameStatus" layoutX="320.0" layoutY="547.0" strokeType="OUTSIDE" strokeWidth="0.0" text="The winner is:" />
<Button fx:id="buttonTrue" layoutX="150.0" layoutY="390.0" mnemonicParsing="false" onAction="#handleButtonAnswer" text="True" />
<Button fx:id="buttonFalse" layoutX="582.0" layoutY="390.0" mnemonicParsing="false" onAction="#handleButtonAnswer" text="False" />
</children>
</AnchorPane>
一切正常-这是我的最终解决方案
package sample;
import java.net.URL;
import java.util.*;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.text.Text;
public class Controller {
@FXML
TextField player1;
@FXML
TextField player2;
@FXML
Text score1;
@FXML
Text score2;
@FXML
Text statusText;
@FXML
Text questionsLeft;
@FXML
Text currentPlayer;
@FXML
Button startGame;
@FXML
Button buttonTrue;
@FXML
Button buttonFalse;
@FXML
Button nextRound;
private ArrayList<String> questionsArray = new ArrayList<String>();
private ArrayList<String> answerArray = new ArrayList<String>();
private int player = 0;
private int remainingQuestions = 0;
private int playerOneScore;
private int playerTwoScore;
private String playerOneName = "";
private String playerTwoName = "";
private String answerFromArray = "";
private String answerButtonText = "";
private Random randomQuestionNumber = new Random();
private int randomQuestion = 0;
@FXML
private void handleStartGame(ActionEvent event) {
// ******* DECLARE VARIABLES ********
playerOneName = player1.getText(); //Saves the name for later use
playerTwoName = player2.getText(); //Saves the name for later use
score1.setText(playerOneName+ " has: 0 points;");
score2.setText(playerTwoName+ " has: 0 points;");
playerOneScore = 0;
playerTwoScore = 0;
System.out.println(playerOneName + " TEST"); //To TEST if the name is saved
System.out.println(playerTwoName + " TEST"); //To TEST if the name is saved
// ******* DECLARE QUESTION ARRAY ********
questionsArray.add("Question 1");
questionsArray.add("Question 2");
questionsArray.add("Question 3");
questionsArray.add("Question 4");
questionsArray.add("Question 5");
questionsArray.add("Question 6");
// ******* DECLARE ANSWER ARRAY ********
answerArray.add("True");
answerArray.add("True");
answerArray.add("False");
answerArray.add("True");
answerArray.add("False");
answerArray.add("True");
// ******* THIS IS THE PLAYER STARTING THE ROUND ******
player = 1;
// ****** RETRIEVE AND PRESENT FIRST QUESTION - THIS WILL ONLY BE USED TO START THE PROGRAM ******
randomQuestion = randomQuestionNumber.nextInt(questionsArray.size()); // GENERATES A RANDOM NUMBER TO PICK A RANDOM QUESTION FROM ARRAYLIST
statusText.setText("Question: " + questionsArray.get(randomQuestion)); // PRINTS THE RANDOM QUESTION TO THE UI
currentPlayer.setText("Current Player: "+playerOneName);
buttonFalse.setDisable(false);
buttonTrue.setDisable(false);
startGame.setDisable(true);
}
@FXML
private void handleButtonAnswer(ActionEvent event) {
Button answerButtonClicked = (Button) event.getSource();
answerButtonText = answerButtonClicked.getText();
answerFromArray = answerArray.get(randomQuestion); // PICKS THE ANSWER MATCHING THE QUESTION GENERATED BY THE RANDOM NUMBER
if (answerFromArray.equals(answerButtonText)) {
statusText.setText("Answer was correct! You've been awarded 1 point");
if(player == 1){
playerOneScore = playerOneScore+1;
score1.setText(playerOneName+ " has: "+playerOneScore+" points;");
}else if(player == 2){
playerTwoScore = playerTwoScore+1;
score2.setText(playerTwoName+ " has: "+playerTwoScore+" points;");
}
}else{
statusText.setText("Answer was incorrect! No point was given.");
}
nextRound.setDisable(false);
buttonFalse.setDisable(true);
buttonTrue.setDisable(true);
}
@FXML
private void handleButtonNext(ActionEvent event) {
if(player == 1){
player = 2;
currentPlayer.setText("Current Player: "+playerTwoName);
}else if(player == 2){
player = 1;
currentPlayer.setText("Current Player: "+playerOneName);
}
questionsArray.remove(randomQuestion); // REMOVES QUESTION FROM ARRAYLIST
answerArray.remove(randomQuestion); // REMOVES ANSWER FROM ARRAYLIST
remainingQuestions = questionsArray.size();
questionsLeft.setText(remainingQuestions + " questions left");
if(questionsArray.size()!=0){
randomQuestion = randomQuestionNumber.nextInt(questionsArray.size());
statusText.setText("Question: " + questionsArray.get(randomQuestion)); // PRINTS QUESTION TO THE UI
}else{
if(playerOneScore>playerTwoScore){
questionsLeft.setText("Game is over. The winner is: "+playerOneName);
}else if(playerTwoScore>playerOneScore){
questionsLeft.setText("Game is over. The winner is: "+playerTwoName);
}else{
questionsLeft.setText("The game ended in a DRAW. ");
}
startGame.setDisable(false);
buttonFalse.setDisable(true);
buttonTrue.setDisable(true);
}
nextRound.setDisable(true);
buttonFalse.setDisable(false);
buttonTrue.setDisable(false);
}
}
fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.text.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="600.0" prefWidth="800.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Controller">
<children>
<Label layoutX="233.0" layoutY="46.0" prefHeight="66.0" prefWidth="334.0" text="Java ExpertQuiz" textAlignment="CENTER">
<font>
<Font name="Cambria Bold" size="45.0" />
</font>
</Label>
<TextField fx:id="player1" layoutX="79.0" layoutY="154.0" opacity="0.5" prefHeight="39.0" prefWidth="201.0" promptText="Enter name for player 1" />
<TextField fx:id="player2" layoutX="503.0" layoutY="154.0" opacity="0.5" prefHeight="39.0" prefWidth="222.0" promptText="Enter name for player 2" />
<Text fx:id="score1" layoutX="114.0" layoutY="224.0" strokeType="OUTSIDE" strokeWidth="0.0" text="Player 1 has: 0 points" />
<Text fx:id="score2" layoutX="558.0" layoutY="224.0" strokeType="OUTSIDE" strokeWidth="0.0" text="Player 2 has: 0 points" />
<Text fx:id="statusText" layoutX="41.0" layoutY="315.0" strokeType="OUTSIDE" strokeWidth="0.0" text="Question" textAlignment="CENTER" wrappingWidth="717.1240234375">
<font>
<Font size="38.0" />
</font>
</Text>
<Button fx:id="startGame" layoutX="363.0" layoutY="161.0" mnemonicParsing="false" onAction="#handleStartGame" text="Start game" />
<Text fx:id="questionsLeft" layoutX="304.0" layoutY="473.0" strokeType="OUTSIDE" strokeWidth="0.0" text="Questions left: " textAlignment="CENTER" wrappingWidth="191.9072265625">
<font>
<Font size="18.0" />
</font></Text>
<Button fx:id="buttonTrue" disable="true" layoutX="150.0" layoutY="378.0" mnemonicParsing="false" onAction="#handleButtonAnswer" text="True" />
<Button fx:id="buttonFalse" disable="true" layoutX="592.0" layoutY="378.0" mnemonicParsing="false" onAction="#handleButtonAnswer" text="False" />
<Button fx:id="nextRound" disable="true" layoutX="354.0" layoutY="378.0" mnemonicParsing="false" onAction="#handleButtonNext" text="Next Question" />
<Text fx:id="currentPlayer" layoutX="355.0" layoutY="260.0" strokeType="OUTSIDE" strokeWidth="0.0" text="Current player:">
<font>
<Font size="14.0" />
</font>
</Text>
</children>
您可以将循环设为一个单独的函数,然后在放置按钮时调用它,而不是将其视为暂停循环。在这种情况下,它不再是一个循环,它只需要将循环的索引存储为函数外部的变量,或者您可以使用索引作为参数调用函数。我认为你的整个handlestart游戏
可以进一步拆分。一个好的经验法则是,一个函数应该执行一个特定的任务,这将使程序更容易继续工作。如果您对此有任何疑问,请随时发表评论!
问题内容: 我正在使用bluebird,方法 getAll 和 update return promises。我如何说“等到两个承诺返回,然后更新currentProduct值”?我对JS很陌生… 问题答案: 如果可以使用/,这将很简单。 或者,如果您只能使用简单的承诺,则可以遍历所有产品,并将每个承诺置于最后一个循环中。这样,仅当前一个问题解决时,它才会前进到下一个问题(即使它将首先迭代整个循环
问题内容: 我正在开发满足个人需要的控制台脚本。我需要能够暂停很长一段时间,但是,根据我的研究,Node.js无法按需停止。一段时间后,读取用户的信息变得越来越困难……我已经看到了一些代码,但是我相信他们必须在其中包含其他代码才能使其正常工作,例如: 但是,我需要这段代码之后的所有内容才能在一段时间后执行。 例如, 我也看过类似的东西 但是Node.js无法识别这一点。 我如何才能实现这种长时间的
问题内容: 我正在为个人需求开发类似脚本的控制台。我需要能够暂停很长一段时间,但是,根据我的研究,node.js无法按需停止。一段时间后,读取用户的信息变得越来越困难……我已经看到了一些代码,但是我相信他们必须在其中包含其他代码才能使他们工作,例如: 但是,我需要这段代码之后的所有内容才能在一段时间后执行。 例如, 我也看过类似的东西 但是node.js无法识别这一点。 我如何才能实现这种长时间的
我正在为个人需要开发一个控制台脚本。我需要能够暂停更长的时间,但根据我的研究,Node.js无法按要求停止。用户的信息读一段时间后就越来越难了...我已经看到了一些代码,但我相信它们必须有其他代码在里面才能工作,例如: 但是,我需要这行代码之后的所有内容在这段时间之后执行。 例如, 我也见过 但Node.js并不认识到这一点。 我如何实现这种延长的暂停?
问题内容: 我会明白为什么 需要新的线程;它适用于: 为什么我不能使用同一线程?一世: 将光标设置为WAIT(进入GUI队列) 做我的长任务…(它进入GUI队列,但我希望光标更改,即在队列中,它在此之前执行) 将光标重置为默认值(任务完成后) 那么,我的长任务不会进入MAIN队列吗?因为,如果它进入主队列,我希望它在我的WAIT游标首先插入队列之后执行。为什么会这样呢? 问题答案: 没有线程,您的
启动无限循环后,我无法关闭JFrame。 我想停止无限循环使用停止按钮。 我用开始按钮开始一个无限循环。我想用“停止”按钮关闭那个回路。 > if(stop.getModel(). isP的()){中断;}不工作 actionListener用于识别按钮单击并在循环也不起作用时使用中断语句终止 点击停止按钮,无限循环必须终止。在使用start Button启动无限循环后,我无法使用JFrame中的