Help with a Hangman program

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • araujo2nd
    New Member
    • Oct 2007
    • 24

    #16
    kewl i just did that, i stored 200 words in a text file, its called dictionary.txt

    Comment

    • r035198x
      MVP
      • Sep 2006
      • 13225

      #17
      Originally posted by araujo2nd
      kewl i just did that, i stored 200 words in a text file, its called dictionary.txt
      Great. Now you need to know how to read words from that text file.

      This article will show you how. Make sure you also read the comments posted in that thread. After you're done reading that you should try the code and read words from your textfile. Also try to get a random word to display to the screen.
      Hint: For the random word display part you may find the java.util.Rando m class helpful.

      Comment

      • araujo2nd
        New Member
        • Oct 2007
        • 24

        #18
        ok, i just managed to read and print all the words, im not familiar with the java.util.Rando m class so do not know how to display a random word instead of all of them

        Comment

        • r035198x
          MVP
          • Sep 2006
          • 13225

          #19
          Originally posted by araujo2nd
          ok, i just managed to read and print all the words, im not familiar with the java.util.Rando m class so do not know how to display a random word instead of all of them
          You should have opened the API docs page for it.

          From here there are two ways of going about it.
          Read all the words into an ArrayList<Strin g> one word at a time. Then generate a number (using the Random class) between 0 and the number of words in the ArrayList (minus one). If the generated number is n, then displaying the nth string in the list is equivalent to displaying a random string.

          P.S Always refuse to write any code if you do not have the API specs with you.

          P.P.S We are still just playing around with some stuff here. The next step involves the algorithm which you are going to write.

          Comment

          • araujo2nd
            New Member
            • Oct 2007
            • 24

            #20
            Okay. Will attempt it first thing tomorrow morning. How exactly should i set out the algorithm. I dont normally use algorithms as i dont really understand how to make them:(.. But once i get the random word to work ill let u know. I hope i can get that by tomorrow morning.

            Comment

            • dav3
              New Member
              • Nov 2006
              • 94

              #21
              Originally posted by araujo2nd
              Okay. Will attempt it first thing tomorrow morning. How exactly should i set out the algorithm. I dont normally use algorithms as i dont really understand how to make them:(.. But once i get the random word to work ill let u know. I hope i can get that by tomorrow morning.

              An algorithm is basically just a step by step list of whats going to happen in your program.

              its also helpful to make a list of all the things your going to need.
              You need to read a file
              get user input
              display user input as output
              etc
              etc

              I have found recently that when i have a daunting project on my hands if you break it down and say "ok, today I am going to do this and if i have time start this, or polish this" the project seems to flow more smoothly. Sitting down and just starting to hack out code leads to problems. Even though coding it right away might seem like the quickest way to finish the project, its not.

              This is a great site to come to for help, you just need to show your doing the work yourself and all the developers, admins, mods and experts are more then willing to guide us:)

              Comment

              • araujo2nd
                New Member
                • Oct 2007
                • 24

                #22
                i have decided to go with the applet above, most of it was done by me in any case, i have to continue with it because its so close to done, and i rele do not have time to start from nothing, it has to be done by monday with the documentation which will take me hours:(

                so all help with my applet would be much appreciated, i would like to change the applet into a java application, i only use NETBEANS and DRJava

                Comment

                • r035198x
                  MVP
                  • Sep 2006
                  • 13225

                  #23
                  Originally posted by araujo2nd
                  i have decided to go with the applet above, most of it was done by me in any case, i have to continue with it because its so close to done, and i rele do not have time to start from nothing, it has to be done by monday with the documentation which will take me hours:(

                  so all help with my applet would be much appreciated, i would like to change the applet into a java application, i only use NETBEANS and DRJava
                  I thought you said it was written by a good friend of yours.
                  Anyway good luck with it.

                  Edit: Please do not double post. It's against the site rules. Just keep one problem in one thread.

                  Comment

                  • araujo2nd
                    New Member
                    • Oct 2007
                    • 24

                    #24
                    So i take it that u dont want to help me? My friend did not code it, he helped me do the coding. But now that he left i have no help which is why i came here. Anyway thanks

                    Comment

                    • r035198x
                      MVP
                      • Sep 2006
                      • 13225

                      #25
                      Originally posted by araujo2nd
                      So i take it that u dont want to help me? My friend did not code it, he helped me do the coding. But now that he left i have no help which is why i came here. Anyway thanks
                      Of course I want to help, but only if you want to do it the correct way.

                      Comment

                      • araujo2nd
                        New Member
                        • Oct 2007
                        • 24

                        #26
                        Sir pls can u just help me from where i am, there is still a lot to do, i rele do not have time and have exams soon:(, i just rele want to get this off my chest, i managed to get it to finally run the applet (needed a main method), but now pls could u just help me in getting a high scores table which stores user name and number of tries, and also the reset button does not work and i have tried everything to fix it...i also have no idea how to get the hangman to appear in the gui

                        Comment

                        • r035198x
                          MVP
                          • Sep 2006
                          • 13225

                          #27
                          Originally posted by araujo2nd
                          Sir pls can u just help me from where i am, there is still a lot to do, i rele do not have time and have exams soon:(, i just rele want to get this off my chest, i managed to get it to finally run the applet (needed a main method), but now pls could u just help me in getting a high scores table which stores user name and number of tries, and also the reset button does not work and i have tried everything to fix it...i also have no idea how to get the hangman to appear in the gui
                          That's because you never designed for any of those things before you started.
                          So what's your current code now? Use code tags if you're going to post it. (It's the # icon on the reply controls menu when you're posting the code)

                          Comment

                          • araujo2nd
                            New Member
                            • Oct 2007
                            • 24

                            #28
                            My java code is:



                            [CODE=java] public class Hangman
                            {
                            /**
                            * construct a Hangman game
                            */

                            public Hangman()
                            {
                            myMisses = 0;
                            myWordIndex = 0;
                            myLettersUsed = new boolean[Character.MAX_V ALUE];
                            }

                            /**
                            * clear all variables to beginning-of-game state
                            * word shown user will be all blanks, all letters
                            * are eligible for "guessabili ty"
                            */

                            private void clear()
                            {
                            int k;

                            // all letters can be guessed, none are used

                            for(k=0; k < Character.MAX_V ALUE; k++) {
                            myLettersUsed[k] = false;
                            }

                            // word shown to user is all blanks

                            mySecretWord = new char[myWords[myWordIndex].length()];
                            for(k=0; k < mySecretWord.le ngth; k++) {
                            mySecretWord[k] = BLANK;
                            }
                            }

                            /**
                            * process a user's guess, update state to reflect
                            * the guess. This might change # misses and the
                            * word displayed to the user
                            *
                            * @param ch is the character guessed by the user
                            */
                            private void guess(char ch)
                            {
                            int k;
                            boolean charFound = false;

                            ch = Character.toLow erCase(ch); // case doesn't matter

                            for(k=0; k < mySecretWord.le ngth; k++) {
                            if (! myLettersUsed[ch] &&
                            myWords[myWordIndex].charAt(k) == ch) {
                            mySecretWord[k] = ch;
                            charFound = true;
                            }
                            }
                            if (! myLettersUsed[ch] && ! charFound) {
                            myMisses++;
                            }
                            myLettersUsed[ch] = true;
                            }

                            /**
                            * display (partially guessed) word to user
                            */
                            private void showWord()
                            {
                            int k;
                            for(k=0; k < mySecretWord.le ngth; k++) {
                            System.out.prin t(mySecretWord[k]+" ");
                            }
                            System.out.prin tln("\n# misses left = "+ (MISSES-myMisses));
                            }

                            /**
                            * @return true if word has been guessed, else returne false
                            */

                            private boolean wordGuessed()
                            {
                            int k;
                            for(k=0; k < mySecretWord.le ngth; k++) {
                            if (mySecretWord[k] == BLANK) {
                            return false;
                            }
                            }
                            return true;
                            }

                            /**
                            * plays a game of hangman. Repeated calls of this
                            * function will play different games (different words)
                            * up to some internal limit based on the number of different
                            * words. After all words have been used they'll be repeated
                            */

                            public void play()
                            {
                            clear();
                            while (true) {
                            showWord();
                            System.out.prin t("guess> ");
                            String s = ConsoleInput.re adString();
                            if (s.length() > 0) { // typed something?
                            guess(s.charAt( 0));
                            }
                            if (myMisses >= MISSES) {
                            System.out.prin tln("you lose!!!");
                            break;
                            }
                            else if (wordGuessed()) {
                            System.out.prin tln("you win!!!");
                            break;
                            }
                            }
                            myWordIndex = (myWordIndex + 1) % myWords.length;
                            }

                            private String myWords[] = {
                            "apple",
                            "toothbrush ",
                            "cucumber",
                            "strengthen s",
                            "portfolio"
                            };

                            private char[] mySecretWord; // what's shown to the user
                            private int myMisses; // # misses so far
                            private int myWordIndex; // which word is being guessed
                            private boolean[] myLettersUsed; // tracks letters guessed/used

                            private final static char BLANK = '_';
                            private final static int MISSES = 8;

                            public static final void main(String args[])
                            {
                            Hangman hang = new Hangman();
                            hang.play();
                            }
                            }
                            [/CODE]
                            That doesnt work:(

                            and the applet code now is:



                            [CODE=java] package hangman;

                            import java.awt.*;
                            import javax.swing.*;
                            import java.util.*;
                            import java.lang.*;
                            import java.applet.*;
                            import java.awt.event. *;


                            public class Main extends Applet implements ActionListener, ItemListener
                            {

                            public static void main(String[] args) {
                            JFrame f = new JFrame("applet" );
                            f.setSize(800, 600);
                            Main m = new Main();
                            m.Main();
                            f.add(m);
                            f.setVisible(tr ue);
                            }

                            Button button[];
                            TextField word,letter;
                            TextField guess;
                            Label label1,label2,l abel3;
                            String alphabuttons[];
                            Panel panel1,panel2,p anel3,pana,panb ,panc;
                            Font font;
                            CheckboxGroup group;
                            Checkbox beg,inte,adv;
                            String begin[];
                            String inter[];
                            String advan[];
                            int lives,select;
                            String answer = " ";
                            String missy;
                            String buffy = "--------";
                            StringBuffer store2= new StringBuffer(bu ffy);
                            int counta = lives;
                            public void Main()
                            {
                            this.setLayout( new BorderLayout()) ;
                            // sets up the array to produce the alphabet buttons on the grid
                            alphabuttons = new String[]{"A","B","C","D ","E","F","G"," H","I","J","K", "L","M","N","O" ,"P","Q","R","S ","T","U","V"," W","X","Y","Z"} ;

                            // sets up the arrays with the words to be guessed in all three stages
                            begin = new String[]{"CAT","POWER", "UNDER"};
                            inter = new String[]{"SECTION","VIS ITOR","INTENDED "};
                            advan = new String[]{"BEAUTIFUL","C HEERFUL","ENTHU SIASM"};

                            // create and arrange panel 1 which will house the text fields and the labels

                            panel1 = new Panel(); // panel 1 will hold the two labels and text fields at the top of the applet
                            add("North",pan el1);

                            panel1.setLayou t(new BorderLayout()) ;
                            label1 = new Label("GUESS THE WORD"); // create the label
                            font = new Font("TimesRoma n",Font.ITALIC, 16);
                            label1.setFont( font); // set the font to the label

                            pana = new Panel();
                            panel1.add("Nor th",pana);
                            pana.add(label1 ); // add the label to the panel
                            label1.setAlign ment(label1.CEN TER); // set the label to the centre

                            panb = new Panel();
                            panel1.add("Cen ter",panb);
                            word = new TextField(24); // creates the text field for the word set to 24 chars
                            word.addActionL istener(this);
                            word.setEditabl e(true); // allows text to be edited
                            panb.add(word," CENTER"); // adds the text field to the panel
                            label3 = new Label("Win/Lose");
                            label3.setFont( font);
                            panb.add(label3 );
                            label1.setAlign ment(label1.RIG HT);
                            letter = new TextField(10);
                            letter.addActio nListener(this) ;
                            panb.add(letter ,"RIGHT");

                            panc = new Panel();
                            panel1.add("Sou th",panc);

                            label2 = new Label("How Many Goes Left"); // create the label and intiliase
                            label2.setFont( font); // sets the font previously defined for label 1
                            panc.add(label2 );
                            label2.setAlign ment(label2.LEF T); // Sets the label left

                            guess = new TextField(3); // initialises the guess text field to 3 chars
                            guess.addAction Listener(this);
                            panc.add(guess) ;

                            // create and arrange panel 2 which will house the alphabet grid

                            panel2 = new Panel();
                            add("Center",pa nel2);

                            // set gridLayout for panel2(int rows , int col, int hgap, int vgap
                            panel2.setLayou t(new GridLayout(4,7, 3,3));

                            button = new Button[28];

                            for (int i=0;i<26;i+=1)
                            {
                            // set the buttons of the alphabet up using the array
                            button[i] = new Button(alphabut tons[i]);
                            panel2.add(butt on[i]);
                            button[i].addActionListe ner(this);
                            }

                            button[26] = new Button("Answer" ); // creates the answer button
                            button[26].setForeground( Color.green);
                            button[26].addActionListe ner(this);

                            button[27] = new Button("Reset") ; // creates the reset button
                            button[27].setForeground( Color.yellow);
                            button[27].addActionListe ner(this);

                            // add the remaining buttons to panel 2
                            panel2.add(butt on[26]);
                            panel2.add(butt on[27]);

                            // create and arrange panel 3 which will house the radio buttons for the level

                            panel3 = new Panel();
                            add("South",pan el3);

                            group = new CheckboxGroup() ;

                            // create the radio buttons

                            beg = new Checkbox("Begin ner",group,fals e);
                            beg.addItemList ener(this);

                            inte = new Checkbox("Inter mediate",group, false);
                            inte.addItemLis tener(this);

                            adv = new Checkbox("Advan ced",group,fals e);
                            adv.addItemList ener(this);

                            // add the radio buttons to panel3
                            panel3.add(beg) ;
                            panel3.add(inte );
                            panel3.add(adv) ;
                            }


                            public void actionPerformed (ActionEvent e)
                            {
                            int j=0;
                            int count=0;
                            int k=0;
                            String currentLetter;
                            String temp="";
                            StringBuffer Sanswer = new StringBuffer(an swer);
                            Sanswer.setLeng th(answer.lengt h());
                            boolean hang = false;
                            boolean correct=true;
                            store2.setLengt h(answer.length ());
                            count = Sanswer.length( );


                            for(k=0;k<=25;k +=1)
                            {
                            if (e.getSource()= =button[k])
                            {
                            currentLetter = (button[k].getLabel());
                            letter.setText( currentLetter);

                            for (j=0;j<count;j+ +)
                            {
                            //cycles through the letters in the word
                            if (currentLetter. equals(String.v alueOf(answer.c harAt(j))))
                            {
                            // replaces the letter if it is within the word
                            store2.replace( j,j+1,currentLe tter);
                            temp=store2.toS tring();
                            lives+=1; // does not decrement the lives
                            if(temp.equals( word.getText()) )
                            {
                            letter.setText( "YOU WIN");
                            letter.setForeg round(Color.blu e);
                            }
                            }

                            }
                            lives-=1; // decrements the lives
                            guess.setText(I nteger.toString (lives));
                            word.setText(st ore2.toString() );

                            if (lives<1)
                            {
                            letter.setText( "YOU LOSE");
                            letter.setForeg round(Color.red );
                            }

                            }
                            }

                            if(e.getSource( )==button[26]) // answer button
                            {

                            word.setText(an swer);
                            word.setForegro und(Color.darkG ray);
                            letter.setText( "Unlucky");
                            }

                            if(e.getSource( )==button[27]);
                            {
                            /* word.setText(nu ll);
                            guess.setText(n ull);
                            letter.setText( "delete");
                            for(int x=0;x<9;x++)
                            {
                            store2.replace( x,x+1,"-");
                            }
                            count = Sanswer.length( );
                            count=answer.le ngth(); */
                            }
                            } // ends actionPerformed

                            // invoked with the radio buttons are selected or deselected

                            public void itemStateChange d(ItemEvent e)
                            {
                            // checks if the button is pressed
                            select = (int)(java.lang .Math.random()* 4); // random number generator for the arrays
                            StringBuffer miss = new StringBuffer(an swer);
                            if (e.getSource()= =beg)
                            {
                            if(beg.getState ()==true)
                            {
                            lives = 9;
                            answer = (begin[select]);

                            for (int y=0;y<answer.le ngth();y++)
                            {
                            miss.replace(y, y+1,"-");
                            }
                            word.setText(mi ss.toString());
                            missy = miss.toString() ;
                            word.setForegro und(Color.black );
                            guess.setText(I nteger.toString (lives));
                            }
                            }
                            else if (e.getSource()= =inte)
                            {
                            if(inte.getStat e()==true)
                            {
                            lives = 8;
                            answer = (inter[select]);
                            for (int y=0;y<answer.le ngth();y++)
                            {
                            miss.replace(y, y+1,"-");
                            }
                            word.setText(mi ss.toString());
                            missy = miss.toString() ;
                            word.setForegro und(Color.black );
                            guess.setText(I nteger.toString (lives));
                            }
                            }
                            else if(e.getSource( )==adv)
                            {
                            if(adv.getState ()==true)
                            {
                            lives = 7;
                            answer = (advan[select]);
                            for (int y=0;y<answer.le ngth();y++)
                            {
                            miss.replace(y, y+1,"-");
                            }
                            word.setText(mi ss.toString());
                            missy = miss.toString() ;
                            word.setForegro und(Color.black );
                            guess.setText(I nteger.toString (lives));
                            }
                            }
                            } // ends itemStateChange d for the radio buttons

                            }//ends the class[/CODE]
                            Last edited by r035198x; Oct 10 '07, 05:37 PM. Reason: added code tags

                            Comment

                            • r035198x
                              MVP
                              • Sep 2006
                              • 13225

                              #29
                              Those are two different programs. So which one do you want to work with?

                              P.S It will have to be one that you understand because you will be making the changes to make it work.

                              Comment

                              • araujo2nd
                                New Member
                                • Oct 2007
                                • 24

                                #30
                                any, whichever 1 i could do quicker i suppose

                                Comment

                                Working...