JavaFX 答案未显示

问题描述 投票:0回答:1

我正在使用 javaFX 编写 Hangman 游戏,不知怎的,代码假设我所有的猜测都是错误的,并且即使它是正确的,也总是被认为是一个错误。所以用户最终总是会失败。我认为这与我使用的 while 循环有关,以确保处理任何字母的所有冗余(例如在“banana”中,如果用户输入“a”,则当前进度应显示为“-a-a-a”)而不是“-a----”)但我不知道:这是我的控制器类以及单词,如果您需要任何其他类,请告诉我!


import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.layout.Pane;
import javafx.scene.text.Text;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.List;

public class Controller {

    //inject an element defined in fxml to controller!
    @FXML
    //pane is a form container
    private Pane man;
    @FXML
    private Pane base1;
    @FXML
    private Pane base2;
    @FXML
    private Pane base3;
    @FXML
    private Pane pole;
    @FXML
    private Pane rod;
    @FXML
    private Pane rope1;
    @FXML
    private Pane rope2;
    @FXML
    private Text text;
    @FXML
    private Pane buttons;
    @FXML
    private Text winStatus;
    @FXML
    private Text realWord;

    private int mistakes;
    private int correct;
    
    private String[] table;
    private String word;
    private String category;
    private List<String> myLetters;
    private List<String> answer;

    public Controller(){
    }

    public void initialize() {
        base1.setVisible(false);
        base2.setVisible(false);
        base3.setVisible(false);
        pole.setVisible(false);
        rod.setVisible(false);
        rope1.setVisible(false);
        rope2.setVisible(false);
        man.setVisible(false);
        buttons.setDisable(false);
        
        mistakes=0;
        correct=0;
        
        table = Words.getRandomWord(2);
        word=table[1];
        category=table[0];
        
        myLetters = Arrays.asList(word.split(""));
        answer = Arrays.asList(new String[myLetters.size()*2]);
        
        for(int i=0; i<myLetters.size()*2; i++){
            if(i%2==0){
                answer.set(i, "_");
            }else{
                answer.set(i, " ");
            }
        }
        String res = String.join("", answer);
        text.setText(res);
        
        //hide winstatus and realword in case of a new game! 
        winStatus.setText("");
        realWord.setText("");
    }

    //when do i call for u ?when the event i declared happened!
    public void onClick(ActionEvent event){
        //getText return string not char
        String letter = ((Button)event.getSource()).getText();
        ((Button) event.getSource()).setDisable(true);
        
        if(myLetters.contains(letter)){
            correct++;
            int letterIndex = myLetters.indexOf(letter);
            while (letterIndex != -1) {
                myLetters.set(letterIndex, "*");
                answer.set(letterIndex*2, letter);
                letterIndex = myLetters.indexOf(letter);
                String res = String.join("", answer);
                text.setText(res);
            }
            
            if(correct==word.length()){
                winStatus.setText("You Win!");
                buttons.setDisable(true);
            }
        }
        else{
            mistakes++;
            if(mistakes ==1)       base1.setVisible(true);
            else if (mistakes ==2) base2.setVisible(true);
            else if (mistakes ==3) base3.setVisible(true);
            else if (mistakes ==4) pole.setVisible(true);
            else if (mistakes ==5) rod.setVisible(true);
            else if (mistakes ==6) rope1.setVisible(true);
            else if (mistakes ==7) rope2.setVisible(true);
            else if (mistakes ==8){
                rope2.setVisible(false); //7bal lmachan9a around the neck 
                man.setVisible(true);//sad face+body
                winStatus.setText("You Lose!");
                realWord.setText("The actual word was " + word);
                buttons.setDisable(true);
            }
        }
    }

    public void newGame(){
        //i don't get what does the loops does
        //why enable here and enable in initialize?
        for(int i=0; i<26; i++){
            buttons.getChildren().get(i).setDisable(false);
        }
        initialize();
    }


}
package sample;

import java.util.Random;

public class Words{
    
       
    public static String[] getRandomWord(int languageChoice) {
        
        String[] fruits = {"strawberry", "banana", "orange", "apple", "cherry", "peach", "kiwi", "lemon", "grape", "mango"};
        String[] countries = {"tunisia", "spain", "japan", "qatar", "greece", "palestine", "italy", "canada", "germany", "china"};
        String[] animals = {"shark", "wolf", "cat", "cow", "snake", "horse", "dog", "lion", "rabbit", "zebra"};
        String[] languages = {"arabic", "korean", "english", "russian", "turkish", "hindi", "spanish", "french", "german", "chinese"};
        String[] occupations = {"doctor", "engineer", "teacher", "baker", "clown", "pilot", "lawyer", "chef", "nurse", "police"};

        String[] fruit = {"fraise", "bananes", "orange", "pomme", "cerise", "pêche", "kiwi", "citron", "raisin", "mangue"};
        String[] pays = {"tunisie", "espagne", "japon", "qatar", "grèce", "palestine", "italie", "canada", "allemagne", "chine"};
        String[] animaux = {"requin", "loup", "chat", "vache", "serpent", "cheval", "chien", "lion", "lapin", "zèbre"};
        String[] langues = {"arabe", "coréen", "anglais", "russe", "turc", "hindi", "espagnol", "français", "allemand", "chinois"};
        String[] professions = {"médecin", "ingénieur", "enseignant", "boulanger", "clown", "pilote", "avocat", "chef", "infirmier", "police"};
        
        String category=null;
        String word=null;      
        int categoryIndex = new Random().nextInt(5)+1; 

        if (languageChoice == 2) {
            switch (categoryIndex) {
                case 1:
                    category = "fruits";
                    word = fruits[new Random().nextInt(fruits.length)];
                    break;
                case 2:
                    category = "countries";
                    word = countries[new Random().nextInt(countries.length)];
                    break;
                case 3:
                    category = "animals";
                    word = animals[new Random().nextInt(animals.length)];
                    break;
                case 4:
                    category = "languages";
                    word = languages[new Random().nextInt(languages.length)];
                    break;
                case 5:
                    category = "occupations";
                    word = occupations[new Random().nextInt(occupations.length)];
                    break;
            }
        } 
        else {
            switch (categoryIndex) {
                case 1:
                    category = "fruits";
                    word = fruit[new Random().nextInt(fruit.length)];
                    break;
                case 2:
                    category = "pays";
                    word = pays[new Random().nextInt(pays.length)];
                    break;
                case 3:
                    category = "animaux";
                    word = animaux[new Random().nextInt(animaux.length)];
                    break;
                case 4:
                    category = "langues";
                    word = langues[new Random().nextInt(langues.length)];
                    break;
                case 5:
                    category = "professions";
                    word = professions[new Random().nextInt(professions.length)];
                    break;
            }
        }

        return new String[]{category, word};
    }
} ```
java user-interface javafx
1个回答
0
投票

这不是一个 GUI 应用程序,但希望它可以演示我认为程序员在编程时应该使用的一些想法。很多想法都与将事情分解成更小的任务有关。这有助于发现错误,IMO。

  1. 创建静态辅助方法来帮助对类进行操作。示例:Word 类需要知道单词中每个字符的索引。此示例使用

    getIndexOfCharacters
    查找当前单词中每个字符的索引,并在
    Map
    中返回该信息。还有其他静态
    Word
    方法可以帮助获取与
    Word
    类相关的信息。如果需要的话,我还会将人工智能作为一个单独的类和通用辅助实用程序。对于这个例子我没有做任何事情。

  2. 尝试找到最适合该工作的数据结构。在此示例中,我使用

    Map
    List
    Set
    是出于与他们将要执行的工作相关的不同原因。

  3. 因为它涉及到很多游戏,所以从状态的角度来思考事情。我这里做得不太好,但是棋盘可以看作是猜测前后的状态。

我希望其中一些想法有所帮助。祝你编码顺利!

主要

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;

/**
 *
 * @author sedj601
 */
public class Mavenproject24 {   
    public static void main(String[] args) {        
        String someString = Word.getRandomWord();
        StringBuilder board = new StringBuilder(Word.createInitialBoard(someString));        
        //System.out.println("Board: " + board.toString());
        
        Map<Character, List<Integer>> characterIndexes = Word.getIndexOfCharacters(someString);
        //printMap(characterIndexes);
        
        Set<Character> rightGuesses = createWinSet(someString);//keeps up with correct guesses.
        List<Character> wrongGuesses = new ArrayList(); //Keep up with the number of incorrect guesses.
        
        
        Scanner input = new Scanner(System.in);
        List<Character> choices = createAiPlayerChoices();
        
        for(int i = 0; i < choices.size(); i++)
        {
            char aiGuess = choices.get(i);
            
            if(characterIndexes.containsKey(aiGuess))
            {
                //Update the board
                characterIndexes.get(aiGuess).forEach((index) -> {
                    board.setCharAt(Word.convertToBoardIndex(index), aiGuess);
                });
                //Remove char from correctGuesses map; 
                rightGuesses.remove(aiGuess);
                
            }
            else
            {
                //Add Character to wrong guess list.
                wrongGuesses.add(aiGuess);
            }            
            
            System.out.println("AI Guess " + i + " - " + aiGuess + ": " + board.toString());
            checkForWinOrLose(wrongGuesses, rightGuesses);
            input.nextLine();//Press enter to take another guess            
        }
    }
    
    static public List<Character> createAiPlayerChoices()
    {
        List<Character> choices = new ArrayList();
        
        String alphabet = "abcdefghijklmnopqrstuvwxyz";
        for(int i = 0; i < alphabet.length(); i++)
        {
            choices.add(alphabet.charAt(i));
        }
        Collections.shuffle(choices);
        
        return choices;
    }
    
    static public void checkForWinOrLose(List<Character> wrongGuesses, Set<Character> rightGuesses)
    {
        int numOfAppendages = 20;
        if(wrongGuesses.size() >= numOfAppendages)
        {
            System.out.println("Game Over: You lose!");
            System.exit(0);
        }
        else if(rightGuesses.isEmpty())
        {
            System.out.println("Game Over: You Win!");
            System.exit(0);
        }
        else
        {
            System.out.println("Keep going! No win or lose!");
        }      
    }       
           
    static public Set<Character> createWinSet(String word)
    {
        Set<Character> winSet = new HashSet();
        for(int i = 0; i < word.length(); i++)
        {
            winSet.add(word.charAt(i));
        }
        
        return winSet;
    }
    
    //    static public void printMap(Map<Character, List<Integer>> inputMap)
//    {
//        for (Map.Entry<Character, List<Integer>> entry : inputMap.entrySet()) {
//            System.out.print(entry.getKey());
//            entry.getValue().forEach((t) -> {
//                System.out.print("\t" + t);
//            });
//            System.out.println("");
//        }
//    }
}

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author blj0011
 */
public class Word
{
    public static String getRandomWord()
    {
        return "banana";
    }
    
    static public String createInitialBoard(String word)
    {
        String board = "";
        for(int i = 0; i < 2 * word.length() - 1; i++)
        {
            if(i % 2 == 1)
            {
                board += "-";
            }
            else
            {
                board += "_";
            }
            
        }
        
        return board;
    }    
    
    static public int convertToBoardIndex(int stringIndex)
    {
        return 2 * stringIndex;
    }  
    
    static public Map<Character, List<Integer>> getIndexOfCharacters(String word)
    {
        Map<Character, List<Integer>> indexes = new HashMap();
        
        for(int i = 0; i < word.length(); i++)
        {
            if(!indexes.containsKey(word.charAt(i)))
            {
                List<Integer> newList = new ArrayList();
                newList.add(i);
                indexes.put(word.charAt(i), newList);
            }
            else
            {
                indexes.get(word.charAt(i)).add(i);
            }
        }
        
        return indexes;
    }
}

注意:如果你想增加AI损失的变化,请将numOfAppendages设置为一个较低的数字。另外,这段代码可能有问题。

© www.soinside.com 2019 - 2024. All rights reserved.