Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 13 of 13
  1. #1
    New to the CF scene
    Join Date
    Feb 2013
    Posts
    6
    Thanks
    3
    Thanked 0 Times in 0 Posts

    word guessing game applet help

    My problem is:
    To write an applet to play the game "hangman", according to the following requirements.

    The applet runs through the following two stages:

    1)After the applet starts (and after restart, see below), a new word can be input, and the default maximum number of error can be changed. Then click "OK" to start the game.
    After the game stars, the user can enter one letter at a time at the bottom row.
    The "restart" button can be pressed at any time to restart a new game.

    I have the layout of the applet set up how it needs to be and two of my buttons work correctly. If you run the code yourself, you will see what it looks like. The only button I can't figure out is the "Guess" button. It is supposed to take the character entered in the textfield next to it(guessField) and search the word in the text field that the original word was entered in and replace any letters that match the letter entered.
    Here is my code so far:

    Code:
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    
    public class HangmanGame extends Applet implements ActionListener{
    
        /**
         * Initialization method that will be called after the applet is loaded into
         * the browser.
         */
        private char guessChar;
        private int error, newErrorCount, i, wordLength, j;
        private String blankWord, actualWord, guessedWord;
        private Button okay, guess, restart;
        private TextField wordField, errorField, guessField;
        private Panel northPanel, centerPanel, southPanel;
    
       
        @Override
        public void init() {
            setBackground(Color.LIGHT_GRAY);
            setLayout(new BorderLayout());
            error = 10;
            okay = new Button("OK");
            okay.addActionListener(this);
            guess = new Button("Guess!");
            guess.addActionListener(this);
            restart = new Button("Restart");
            restart.addActionListener(this);
            wordField = new TextField(15);
            wordField.addActionListener(this);
            errorField = new TextField("" +error);
            errorField.addActionListener(this);
            guessField = new TextField(2);
            guessField.addActionListener(this);
            northPanel = new Panel();
            centerPanel = new Panel();
            southPanel = new Panel();
            northPanel.setLayout(new FlowLayout());
            northPanel.add(new Label("Phrase to be guessed:"));
            northPanel.add(wordField);
            centerPanel.setLayout(new FlowLayout());
            centerPanel.add(new Label("Maximum errors:"));
            centerPanel.add(errorField);
            centerPanel.add(okay);
            southPanel.setLayout(new FlowLayout());
            southPanel.add(guessField);
            southPanel.add(guess);
            southPanel.add(restart);
            add(northPanel, BorderLayout.NORTH);
            add(centerPanel, BorderLayout.CENTER);
            add(southPanel, BorderLayout.SOUTH);
        }
    
        @Override
        public void actionPerformed(ActionEvent e) {
            Object source = e.getSource();
            
            newErrorCount = Integer.parseInt(errorField.getText());//changes the string in the field to an int to be set to the int variable and reused
            wordLength = wordField.getText().length();
            char[] blankWordArray = new char[wordLength];
            actualWord = wordField.getText();
            for(i=0; i<wordLength; i++){  
                if(wordField.getText().charAt(i) ==' '){
                    blankWordArray[i] = ' ';
                }else{
                    blankWordArray[i] = '*';
                }
            }
            blankWord = new String(blankWordArray);
            if(source == okay){
                 errorField.setText(""+newErrorCount);
                 wordField.setText(blankWord);
                 
            }else if(source == guess){
                guessChar = guessField.getText().charAt(0);
                guessField.setText("");
                for(j=0; j<actualWord.length(); j++){
                    if(guessChar==actualWord.charAt(j)){
                        blankWordArray[j]=guessChar;
                        guessedWord = new String(blankWordArray);
                        wordField.setText(guessedWord);
                    }else{
                        newErrorCount--;
                        errorField.setText(""+newErrorCount);
                    }
                }
                
            }else if(source == restart){
                wordField.setText("");
                errorField.setText(""+error);
                guessField.setText("");
            }
        }
    }
    Last edited by kyledkatz; 02-17-2013 at 09:55 PM.

  • #2
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,592
    Thanks
    0
    Thanked 645 Times in 635 Posts
    You have posted in the wrong forum - that code is NOT JavaScript.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #3
    New to the CF scene
    Join Date
    Feb 2013
    Posts
    6
    Thanks
    3
    Thanked 0 Times in 0 Posts
    My apologies, I've reposted in the correct forum.

  • #4
    UE Antagonizer Fumigator's Avatar
    Join Date
    Dec 2005
    Location
    Utah, USA, Northwestern hemisphere, Earth, Solar System, Milky Way Galaxy, Alpha Quadrant
    Posts
    7,691
    Thanks
    42
    Thanked 637 Times in 625 Posts
    A string is an array of characters so just loop through the characters of the guess string, comparing each character to the answer string. If there's a match, fill in the blank.

  • #5
    The fat guy next door VIPStephan's Avatar
    Join Date
    Jan 2006
    Location
    Halle (Saale), Germany
    Posts
    8,608
    Thanks
    6
    Thanked 997 Times in 970 Posts
    Quote Originally Posted by kyledkatz View Post
    My apologies, I've reposted in the correct forum.
    1. No, you haven’t. The correct forum would be the Java forum.
    2. Don’t do that. Rather, ask a moderator to move your thread to the appropriate forum (which I’ve done now as someone else has reported your thread). We wanna keep the forum tidy, you know?

  • #6
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 Posts
    Ultimately the problem is that you've overwritten the actualWord with that of the guessed word after the first guess action.
    Within actionPerformed, you want to split it up logically into what its source is first. So branch for each statement available. You currently have a check for guess and restart, but not for initialize (the okay button). So all the work the okay button would be doing executes every time an event handle is passed to the actionPerformed. This has an assignment of actualWord = wordField.getText();, so after your first guess you then end up with the actualWord being that of the replaced first guess (so if my word is test and I guess 't', than I'd have actualWord being t**t). Group all that logic into the okay branch.
    You'll need to fix up the incorrect guesses as well. Currently you check within the loop during char iteration, so if I guessed 't' on 'test', than I'd still end up with 2 incorrect guesses (the e and the s). You may want to implement case insensitive compare as well. The error count can be easily fixed by adding a boolean within the iteration loop. So long as it matches one result you have bMatches=true, and after the loop check for !bMatches and then increment the incorrect count.
    Looks good otherwise. It's missing error handling, but I won't suggest adding it unless you have learned that. You'll also want to implement some type of functionality in the guess that allows you to indicate that the word is fully guessed and relay that to the user.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 

  • Users who have thanked Fou-Lu for this post:

    kyledkatz (02-17-2013)

  • #7
    New to the CF scene
    Join Date
    Feb 2013
    Posts
    6
    Thanks
    3
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by Fou-Lu View Post
    Ultimately the problem is that you've overwritten the actualWord with that of the guessed word after the first guess action.
    Within actionPerformed, you want to split it up logically into what its source is first. So branch for each statement available. You currently have a check for guess and restart, but not for initialize (the okay button). So all the work the okay button would be doing executes every time an event handle is passed to the actionPerformed. This has an assignment of actualWord = wordField.getText();, so after your first guess you then end up with the actualWord being that of the replaced first guess (so if my word is test and I guess 't', than I'd have actualWord being t**t). Group all that logic into the okay branch.
    Does that mean that if the code is not within one of my sources( if(source==okay)) that anytime any source is used, all of the code that is not in any source brackets will also be executed?

  • #8
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 Posts
    That's correct. Since it doesn't have a particular branch to go down, that is executed all the time and then it determines which branch to go down (guess or restart).
    You can likely group both the restart and okay buttons together though, the functionality sounds like it'd be the same.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 

  • Users who have thanked Fou-Lu for this post:

    kyledkatz (02-17-2013)

  • #9
    New to the CF scene
    Join Date
    Feb 2013
    Posts
    6
    Thanks
    3
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by Fou-Lu View Post
    That's correct. Since it doesn't have a particular branch to go down, that is executed all the time and then it determines which branch to go down (guess or restart).
    You can likely group both the restart and okay buttons together though, the functionality sounds like it'd be the same.
    Thank you so much for your help so far!

    I improved my code a bit now and it almost works. The problem now is if the word is "test" and you guess 't' it comes up "t**t" but then if you guess s after that, it comes up "**s*". I know the issue is with the for loop resetting the the array every time the guess button is pushed but I can't think of what to do so that isn't done every time the button is pressed. You've been a big help so far, any other help will be greatly appreciated.
    Here is my updated code(just the actionPerformed section):
    Code:
        public void actionPerformed(ActionEvent e) {
            Object source = e.getSource();
            
            if(source == okay){
                newErrorCount = Integer.parseInt(errorField.getText());
                wordLength = wordField.getText().length();
                char[] blankWordArray = new char[wordLength];
                actualWord = wordField.getText();
                for(i=0; i<wordLength; i++){  
                    if(wordField.getText().charAt(i) ==' '){
                        blankWordArray[i] = ' ';
                    }else{
                        blankWordArray[i] = '*';
                    }
                }
                blankWord = new String(blankWordArray);
                errorField.setText(""+newErrorCount);
                wordField.setText(blankWord);
                 
            }else if(source == guess){
                char[] guessedWordArray = new char[wordLength];
                for(i=0; i<wordLength; i++){  
                    if(wordField.getText().charAt(i) ==' '){
                        guessedWordArray[i] = ' ';
                    }else{
                        guessedWordArray[i] = '*';
                    }
                }
                guessChar = guessField.getText().charAt(0);
                guessField.setText("");
                guessMatched=false;
                for(i=0; i<actualWord.length(); i++){
                    if(guessChar==actualWord.charAt(i)){
                        guessedWordArray[i]=guessChar;
                        guessedWord = new String(guessedWordArray);
                        wordField.setText(guessedWord);
                        guessMatched = true;
                    }else{
                } 
                }
                if(guessMatched==false){
                    newErrorCount--;
                    errorField.setText(""+newErrorCount);
                }else{
                    
                }
            }else if(source == restart){
                wordField.setText("");
                errorField.setText(""+error);
                guessField.setText("");
            }
        }
    Last edited by kyledkatz; 02-17-2013 at 07:26 PM. Reason: edited my code further and added well deserved thanks

  • #10
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 Posts
    Okay, so look at the loop within the guess branch. If you mach the char, you show the char, otherwise you replace it with *. This isn't what you want to do; you've already created the *'s within the okay source branch, so you've already got the string you need. All you need to do is go through the actualWord char[], and check to see if this current character is found. If it is, replace the same offset of the wordField's text with the replaced value from actual word.
    Do the actual write back after the loop, not within it. So, create a new char array from the wordField, foreach of the chars within the actual word check to see if char = entered char, and if so replace the new char's value with the same char from the actualWord in the corresponding offset. Then when you've checked all chars, write the new char array back into the wordField. I suggest taking from the actualWord instead of the guessed char since if you want to make an case insensitive replacement, it's simply a matter of altering the comparison.
    Make sense?
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 

  • #11
    New to the CF scene
    Join Date
    Feb 2013
    Posts
    6
    Thanks
    3
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by Fou-Lu View Post
    All you need to do is go through the actualWord char[], and check to see if this current character is found. If it is, replace the same offset of the wordField's text with the replaced value from actual word.
    Do the actual write back after the loop, not within it. So, create a new char array from the wordField, foreach of the chars within the actual word check to see if char = entered char, and if so replace the new char's value with the same char from the actualWord in the corresponding offset. Then when you've checked all chars, write the new char array back into the wordField.
    Make sense?
    I kinda understand what you were saying but I'm still a bit confused. I'm sorry for being so difficult but I have edited my code further and retried but I'm still having the same issue. I created a new array and didnt define any elements. Now I added an if/else statement so if the guessed char matches a char in the actual word, it replaces that char in the new array. Also, since not every character in the array was defined, I have it look for empty elements and fill them with *'s. I also moved the write back to after the loop.

    This is what I have now(just the guess section since I didnt edit anything else:
    Code:
           
     }else if(source == guess){
                guessMatched=false;
                char[] answerWordArray = new char[wordLength];
                guessChar = guessField.getText().charAt(0);
                guessField.setText("");
                for(i=0; i<wordLength; i++){
                    if(guessChar==actualWord.charAt(i)){//checks the char entered with each char of the actual word
                        answerWordArray[i]=guessChar;//sets the char to that index of a new array
                        guessMatched = true;//sets the error counter boolean  to true so errors dont go down.
                    }else if(answerWordArray[i]=='\u0000'){//checks for empty elements
                        answerWordArray[i]='*';//sets empty elements to '*'
                    }
                }
                guessedWord = new String(answerWordArray);
                wordField.setText(guessedWord);          
                if(guessMatched==false){
                    newErrorCount--;
                    errorField.setText(""+newErrorCount);
                }else{
                }
        }
    Last edited by kyledkatz; 02-17-2013 at 09:16 PM.

  • #12
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 Posts
    You're still doing a bit too much work. You're letting the guess decide if it should flip each character, when this operation has already been done with the initialization of the word. All you need to do is flip it if it matches:
    PHP Code:
    }else if(source == guess){
                
    boolean bGuessMatched false;
                
    char[] currentWord this.wordField.getText().toCharArray();
                
    char guessChar guessField.getText().charAt(0);
                           
                for (
    int i 0actualWord.length(); ++i)
                {
                    if (
    actualWord.charAt(i) == guessChar)
                    {
                        
    currentWord[i] = actualWord.charAt(i);
                        
    bGuessMatched true;
                    }
                }
                if (!
    bGuessMatched)
                {
                    --
    this.newErrorCount;
                    
    this.errorField.setText(this.newErrorCount "");
                }
                
                
    this.wordField.setText(new String(currentWord));            
            } 
    Like that. If you want to insensitively compare, you can do so by using the static Character class methods .toUpperCase or .toLowerCase on each of the chars during comparison. That way 'T' and 't' will both match 'T' and 't'.
    After this, you just need to deal with the win / lose functionality based on the error counter.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 

  • Users who have thanked Fou-Lu for this post:

    kyledkatz (02-17-2013)

  • #13
    New to the CF scene
    Join Date
    Feb 2013
    Posts
    6
    Thanks
    3
    Thanked 0 Times in 0 Posts
    That makes so much sense and I feel really dumb for not figuring it out on my own. Thank you so much!


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •