Go Back   CodingForums.com > :: Server side development > Java and JSP

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 02-16-2013, 11:22 PM   PM User | #1
kyledkatz
New to the CF scene

 
Join Date: Feb 2013
Posts: 6
Thanks: 3
Thanked 0 Times in 0 Posts
kyledkatz is an unknown quantity at this point
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..
kyledkatz is offline   Reply With Quote
Old 02-16-2013, 11:32 PM   PM User | #2
felgall
Master Coder

 
felgall's Avatar
 
Join Date: Sep 2005
Location: Sydney, Australia
Posts: 5,532
Thanks: 0
Thanked 503 Times in 494 Posts
felgall is a jewel in the roughfelgall is a jewel in the roughfelgall is a jewel in the rough
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/
felgall is offline   Reply With Quote
Old 02-17-2013, 12:17 AM   PM User | #3
kyledkatz
New to the CF scene

 
Join Date: Feb 2013
Posts: 6
Thanks: 3
Thanked 0 Times in 0 Posts
kyledkatz is an unknown quantity at this point
My apologies, I've reposted in the correct forum.
kyledkatz is offline   Reply With Quote
Old 02-17-2013, 02:10 AM   PM User | #4
Fumigator
UE Antagonizer


 
Fumigator's Avatar
 
Join Date: Dec 2005
Location: Utah, USA, Northwestern hemisphere, Earth, Solar System, Milky Way Galaxy, Alpha Quadrant
Posts: 7,687
Thanks: 42
Thanked 637 Times in 625 Posts
Fumigator is a glorious beacon of lightFumigator is a glorious beacon of lightFumigator is a glorious beacon of lightFumigator is a glorious beacon of lightFumigator is a glorious beacon of light
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.
__________________
Fumigator is offline   Reply With Quote
Old 02-17-2013, 12:26 PM   PM User | #5
VIPStephan
The fat guy next door


 
VIPStephan's Avatar
 
Join Date: Jan 2006
Location: Halle (Saale), Germany
Posts: 7,703
Thanks: 5
Thanked 875 Times in 850 Posts
VIPStephan is a jewel in the roughVIPStephan is a jewel in the roughVIPStephan is a jewel in the rough
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?
__________________
Don’t click this link!
VIPStephan is offline   Reply With Quote
Old 02-17-2013, 04:11 PM   PM User | #6
Fou-Lu
God Emperor


 
Fou-Lu's Avatar
 
Join Date: Sep 2002
Location: Saskatoon, Saskatchewan
Posts: 15,752
Thanks: 4
Thanked 2,468 Times in 2,437 Posts
Fou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to all
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'); 
Fou-Lu is offline   Reply With Quote
Users who have thanked Fou-Lu for this post:
kyledkatz (02-17-2013)
Old 02-17-2013, 04:49 PM   PM User | #7
kyledkatz
New to the CF scene

 
Join Date: Feb 2013
Posts: 6
Thanks: 3
Thanked 0 Times in 0 Posts
kyledkatz is an unknown quantity at this point
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?
kyledkatz is offline   Reply With Quote
Old 02-17-2013, 04:54 PM   PM User | #8
Fou-Lu
God Emperor


 
Fou-Lu's Avatar
 
Join Date: Sep 2002
Location: Saskatoon, Saskatchewan
Posts: 15,752
Thanks: 4
Thanked 2,468 Times in 2,437 Posts
Fou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to all
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'); 
Fou-Lu is offline   Reply With Quote
Users who have thanked Fou-Lu for this post:
kyledkatz (02-17-2013)
Old 02-17-2013, 05:30 PM   PM User | #9
kyledkatz
New to the CF scene

 
Join Date: Feb 2013
Posts: 6
Thanks: 3
Thanked 0 Times in 0 Posts
kyledkatz is an unknown quantity at this point
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
kyledkatz is offline   Reply With Quote
Old 02-17-2013, 07:58 PM   PM User | #10
Fou-Lu
God Emperor


 
Fou-Lu's Avatar
 
Join Date: Sep 2002
Location: Saskatoon, Saskatchewan
Posts: 15,752
Thanks: 4
Thanked 2,468 Times in 2,437 Posts
Fou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to all
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'); 
Fou-Lu is offline   Reply With Quote
Old 02-17-2013, 09:12 PM   PM User | #11
kyledkatz
New to the CF scene

 
Join Date: Feb 2013
Posts: 6
Thanks: 3
Thanked 0 Times in 0 Posts
kyledkatz is an unknown quantity at this point
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..
kyledkatz is offline   Reply With Quote
Old 02-17-2013, 09:31 PM   PM User | #12
Fou-Lu
God Emperor


 
Fou-Lu's Avatar
 
Join Date: Sep 2002
Location: Saskatoon, Saskatchewan
Posts: 15,752
Thanks: 4
Thanked 2,468 Times in 2,437 Posts
Fou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to all
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'); 
Fou-Lu is offline   Reply With Quote
Users who have thanked Fou-Lu for this post:
kyledkatz (02-17-2013)
Old 02-17-2013, 09:46 PM   PM User | #13
kyledkatz
New to the CF scene

 
Join Date: Feb 2013
Posts: 6
Thanks: 3
Thanked 0 Times in 0 Posts
kyledkatz is an unknown quantity at this point
That makes so much sense and I feel really dumb for not figuring it out on my own. Thank you so much!
kyledkatz is offline   Reply With Quote
Reply

Bookmarks

Tags
button, buttons, gui, hangman, java

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 04:06 AM.


Advertisement
Log in to turn off these ads.