带有gui的Java子手游戏,数字递增/递减问题 [英] Java hangman game with gui, problems with incrementing/decrementing numbers

查看:129
本文介绍了带有gui的Java子手游戏,数字递增/递减问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码部分无效,因为每个字的获胜/失败计数一直增加1以上,有时我会得到字符串长度为null的指针异常。而且,尽管玩家应该获得7次尝试(int no),但有时他获得更多,有时更少。字符串取自文本文件 Hangeng.txt。整个游戏都在键盘侦听器内部,而键盘侦听器在按钮侦听器内部。欢迎大家提供有关一般应如何安排游戏布局以避免错误的任何提示,因为我只是开始使用挥杆和gui东西。

The following part of the code doesn't work, as the won/lost count keeps incrementing by more than 1 for each word, and sometimes I get a nullpointerexception with the string length. Moreover, although the player is supposed to get 7 tries(int no), sometimes he gets more, sometimes less. The Strings are taken from a text file "Hangeng.txt". The whole game is inside a keyboard keytyped listener that is inside a button listener. Any tips on how the layout of the game should generally be arranged so as to avoid errors are welcome, as I am only beginning to work with swing and gui stuff.

        public class test{
static int won = 0;
static int lost = 0;
static String key = "";
static String word = null;
static int no = 0;
static StringBuffer toguess;

      public static void main(String[] args) throws IOException{

 JFrame frame = new JFrame();
  frame.setLayout(new GridLayout(3,1));
      JPanel panel1 = new JPanel();
     JPanel panel2 = new JPanel();
      JPanel panel3 = new JPanel();
         JButton button = new JButton();
           JLabel label = new JLabel();
           JLabel label2 = new JLabel();
            panel1.add(label);
              panel2.add(button);
                  panel3.add(label2);
                    frame.setSize(800,600);
                   frame.add(panel1);
                          frame.add(panel2);
                      frame.add(panel3);
                     frame.setVisible(true);

 //the button that starts the game or gets a new word
 button.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            frame.requestFocus();

                no = 0;

                label2.setText("won " + won + ", lost " + lost);
                button.setText("Next");


                                    //get random word from file
                BufferedReader reader = null;
                try {
                    reader = new BufferedReader(new FileReader(
                            "hangeng.txt"));
                } catch (FileNotFoundException e1) {
                    e1.printStackTrace();
                }
                int lineno = (int) (Math.random() * 100);
                for (int i = 0; i < lineno; i++) {
                    try {
                        reader.readLine();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }

                try {
                    word = reader.readLine().replace(" ", "");
                } catch (IOException e1) {
                    e1.printStackTrace();
                }




                String missing = "";
                for (int u = 0; u < (word.length() - 2); u++) {
                    missing = missing + "*";
                }
                final String guess = word.charAt(0) + missing
                        + word.charAt((word.length() - 1));
                toguess = new StringBuffer(guess);
                label.setText(toguess.toString());
                final ArrayList<String> tried = new ArrayList<String>();



            //keylistener that listens to key clicks by the user

         frame.addKeyListener(new KeyListener() {
                    public void keyPressed(KeyEvent arg0) {
                    }

                    public void keyReleased(KeyEvent arg0) {
                    }

                    public void keyTyped(KeyEvent arg0) {
                        key = "" + arg0.getKeyChar();
                        String guessing = null;
                        boolean k = false;

                        if ((no < 6)) {
                            guessing = key;
                            System.out.println(guessing);
                            if (!(tried.contains(guessing))) {
                                tried.add(guessing);
                                for (int length = 1; length < (guess
                                        .length() - 1); length++) {
                                    if (guessing.equals(String.valueOf(word.charAt(length)))) {
                                        toguess.replace(length,
                                                (length + 1),
                                                String.valueOf(word.charAt(length)));
                                        k = true;
                                    }
                                }
                                if (k == true) {
                                    label.setText(toguess.toString());
                                } else {
                                    no = no + 1;
                                }
                                k = false;
                            }
                            label.setText(toguess.toString());
                            if (toguess.toString().equals(word)) {
                                label.setText("Correct! The word was "  + word);
                                no = 6;
                                won = won + 1;
                            }
                        }
                        else if ((no == 6)
                                && (!(toguess.toString().equals(word)))) {
                            label.setText("Sorry, but the word was " + word);

                            lost = lost + 1;
                        }
                    }
                });
            }

    }); 

          }
   }


推荐答案

+1所有评论。...

+1 to all comments....

添加到他们的行列:


  • 请勿使用 KeyListener 使用 KeyAdapter ,但是在使用Swing而不是AWT时,您应该将 KeyBinding 用于Swing,请参见例如

  • Do not use KeyListener use a KeyAdapter however as you are using Swing and not AWT you should use KeyBindings for Swing see here for example.

不要忘记在 Event Dispatch Thread <<上创建和操作Swing组件。 / code>通过 SwingUtiltities.invokeLater(..)块,请参见此处了解更多信息。

Dont forget to create and manipulate Swing components on Event Dispatch Thread via SwingUtiltities.invokeLater(..) block see here for more.

检查类命名方案,它们应该以大写字母开头,即 test 应该是 Test ,之后的每个新单词都应大写。

Check class naming schemes they shuld start with capital letter, i.e test should be Test and every new word after that should be capitalized.

请勿在 JFrame 上调用 setSize ,而是使用适当的 LayoutManager 和/或覆盖 JPanel getPreferredSize()并返回适合其内容的大小并调用<$添加所有组件后,在 JFrame 实例上使用c $ c> pack()

Do not call setSize on JFrame rather use appropriate LayoutManager and/or override getPreferredSize() of JPanel and return a size which fits its content and call pack() on JFrame instance after adding all components.

SSCCE 应该可以从复制中进行编译,并且不能粘贴,这是....即需要更改的变量到最后,我没有Hangeng.txt的样本,因此无法测试

Also SSCCE should be compilable from copy and paste this is not.... i.e variables needed to be changed to final and I dont have a sample of Hangeng.txt so cant test

最后使用@Override注释以确保您覆盖正确的方法,即

Lastly use the @Override annotation to ensure you are overriding the correct methods, i.e

@Override
public void actionPerformed(ActionEvent e) {

}


这篇关于带有gui的Java子手游戏,数字递增/递减问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆