471,825 Members | 827 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,825 software developers and data experts.

Help making a hangman program

Hey, I just started programming this September and I have an assignment in which I am supposed to create a hangman game. This is my first post on this forum so forgive me for any "noob" mistakes Now I'm still learning Java so this will be a basic program running in the console window (no GUI) using strings loops, arrays, etc but hopefully nothing too complicated. I've developed somewhat of an algorithm for the program, but it's really simple so far.

Title screen
main menu (play, instructions, quit)
if they choose to select play there is a choice of difficulty (easy, med, hard)
depending on what difficulty they choose there will be different words

Now I've got all that simple stuff out of the way and I've gotten up to the part where it displays the blanks such as _ _ _ _ _ and now what I'm trying to do is figure out how to get input from the user and use it to fill in the blanks, and give them 5 "lives". What kind of process do I go through to make this happen? I'm not asking for any specific code but I might need some explanations on how I can piece everything together.

Thanks in advance!!!
Nov 26 '08 #1
25 3694
2,364 Expert 2GB
Greetings, yottabyte!

Welcome to bytes... Can you show us the code you referred to? Also you'll probably need to do a lot of the work as we help you figure it all out.

It's exciting though, hope you survive it, it's quite the language, good choice.

In a bit!
Nov 26 '08 #2
13,262 8TB
For console applications, use the Scanner class to get the input from the user or the Console class if you are using Java 6.
Nov 26 '08 #3
3,112 Expert 2GB
Also, I'd create a couter lives which counts (who would guess?) how many lives are left. Then you can put it all in a while loop... you should be able to figure out the rest.

Nov 26 '08 #4
11,448 Expert 8TB
Also also, read about regular expression; in particular the String.replaceAll() method is a nice start. This game is particularly fitted to be solved by regular expressions. They take away all sorts of tedious loops and checks.

kind regards,

Nov 26 '08 #5
Yeah i haven't exactly gotten too far yet but I want to know if I'm starting this off right

I made an array that is like this:

String[] easydifficulty = new String[51];
easydifficulty[0] = "word";
easydifficulty[1] = "another word";
easydifficulty[2] = "another word";
easydifficulty[3] = "another word";

But I just did that to have all my strings in one place...how exactly do I make one random string appear as blanks _ _ _ _ _ and get the user input? I also don't fully understand what you meant by a counter to count lives
Dec 1 '08 #6
3,112 Expert 2GB
OK, now you can do it with an array and I guess as you're a beginner, that should do. To choose a random word from the array, have a look at java.util.Random. Read Reply #3 about how to get user input. And the lives counter? Well, say you may get it wrong 5 times, then you can have
Expand|Select|Wrap|Line Numbers
  1. int lives = 5
somewhere and every time a wrong letter is entered, that variable is decremented (= reduced by one). Then it checks... etc.

Oh, and writing the blanks? Well, you can find the length of a string with
Expand|Select|Wrap|Line Numbers
  1. String myString = "word";
  2. System.out.println(myString + " is " + myString.length() + " characters long.");
That should get you going.

Dec 1 '08 #7
hi there...

Last year, I did the whole hangman game in Pascal; however it was a little bit different in structure than yours is going to be; in such a way that mine first involved the first player to enter the "Secret_word", and then the second player would try to guess it. With regards to the blanks, an int variable "no_of_blanks" would read the length of the "Secret_word" entered by player 1, and then would dislpay the corresponding amount of blanks for player 2 to guess...

With regards to your question about how to get input from the user and use it to fill in the blanks, my approach to it was to read the character entered by the user, and then use an IF statement to check whether the character entered is correct (i.e. found in the "Secret_word"). If it turns out to be correct, then it should be dislpayed instead of the corresponding blank (in my case these were underscores _ ).

Hope this helps.

Kind regards,
Dec 2 '08 #8
Can you explain the secret word part a little bit more? I don't fully understand it but I think it will be important to continuing on my project.
Dec 3 '08 #9
11,448 Expert 8TB
Don't go that way: you'll end up with a highly procedural and low level solution: Pascal doesn't have regular expression handling so you'll end up with lots of nasty little loops and byte fiddling. Have a look at this:

Suppose we have three Strings: word, used and correct; the word String contains the secret word, the used String contains the characters that are used by the user (whether correct or not) and the correct String contains the correctly guessed characters.

Suppose 'x' is the current guess character. So we can do:

Expand|Select|Wrap|Line Numbers
  1. if (used.indexOf(x) >= 0) // character already used
if the above test fails 'x' represents a new guess, so:

Expand|Select|Wrap|Line Numbers
  1. used+= x; // now set x as used
  2. if (word.indexOf(x) < 0) // x is not in word
If the above test fails then x is a character in the word, so:

Expand|Select|Wrap|Line Numbers
  1. correct+= x;
  2. String leftOver= word.replaceAll("[^"+correct+"]", "-");
The last line of this code snippet replaces all characters in the word that are not present in the String correct. They are replaced by a '-'.

If there are still '-'s left in that last String the word wasn't guessed yet:

Expand|Select|Wrap|Line Numbers
  1. boolean finished= leftOver.indexOf('-') < 0;
The few lines of code above represent the core of the game logic. Note that there are no silly loops, no counting, just the handling of the game logic.

kind regards,

Dec 3 '08 #10
Okay well I got the hard (?) part of the project done I hope. I can get it to display a bunch of # symbols as the blanks, then when you put in a letter it makes it appear in the puzzle. Now can I get some help on how to make it a loop though? I want to use a do-while loop but i don't know what to put in the brackets after the while part.

Expand|Select|Wrap|Line Numbers
  1. String []easywords=new String [51];
  2.            easywords[0]="insertwordhere";
  4.                 and so on until the last word...then
  6. int which = (int)(Math.random()*51);
  7.            char[] guess= new char[easywords[which].length()];
  8.            for(int index=0; index<easywords[which].length(); index++) guess[index]='#';
  10.             ****do{ goes here?****
  11.                for(int index=0; index<easywords[which].length(); index++) System.out.print(guess[index]);
  12.                System.out.println();
  13.                System.out.print("Guess a letter: ");
  14.                char letter = In.getChar();
  15.                for(int index=0; index<easywords[which].length(); index++) if(easywords[which].charAt(index)==letter) guess[index]=letter;
  16.                for(int index=0; index<easywords[which].length(); index++) System.out.print(guess[index]);
  17.                System.out.println();
  18.                In.getChar();
  19. ****}while (???) goes here?****
Now I need to put a do and a while in the spots I marked with a star right? But what would I put in the while bracket?? I'm stumped
Dec 10 '08 #11
3,112 Expert 2GB
The place you put that loop if fine, it will do the job. Now, there are several possible ways to check if you're finished, the most simple one would be to have an int variable that holds the amount of characters you haven't guessed yet. When that's 0, you've finished.

Dec 10 '08 #12
Wait so is that supposed to be a word bank or lives?
Dec 11 '08 #13
3,112 Expert 2GB
Well, you could have two counters: one for the remaining lives, one for the letters you've guessed correctly. But that's just one way to do it - there are other possibilities.

Dec 11 '08 #14
11,448 Expert 8TB
*cough* reply #10 *cough*

kind regards,

Dec 11 '08 #15
Yeah I'm thinking that's pretty important to what I need to do, I still dont get it 100%....maybe could you elaborate on it some more please?
Dec 11 '08 #16
11,448 Expert 8TB
Sure, you tell me what you don't understand (yet) w.r.t. reply #10

kind regards,

Dec 12 '08 #17
Ok let me post what I've got so far.

Expand|Select|Wrap|Line Numbers
  1. public static void easypuzzle()
  2.        {
  3.            String []easywords=new String [51];
  4.            easywords[0]="cheat ";
  5.            easywords[1]="photo";
  6.            easywords[2]="mathematics";
  7.            easywords[3]="official";
  8.            easywords[4]="service";
  9.            easywords[5]="favourite";
  10.            easywords[6]="chair";
  11.            easywords[7]="cheap";
  12.            easywords[8]="variable";
  13.            easywords[9]="trapping";
  14.            easywords[10]="west";
  15.            easywords[11]="Bind";
  16.            easywords[12]="teach";
  17.            easywords[13]="attitude";
  18.            easywords[14]="danger";
  19.            easywords[15]="hat";
  20.            easywords[16]="bright";
  21.            easywords[17]="die";
  22.            easywords[18]="engineer";
  23.            easywords[19]="interface";
  24.            easywords[20]="million";
  25.            easywords[21]="steal";
  26.            easywords[22]="pattern";
  27.            easywords[23]="local";
  28.            easywords[24]="sharing";
  29.            easywords[25]="dump";
  30.         easywords[26]="event";
  31.            easywords[27]="lower";
  32.            easywords[28]="man";
  33.            easywords[29]="hang";
  34.            easywords[30]="governor";
  35.            easywords[31]="chose";
  36.            easywords[32]="showing";
  37.            easywords[33]="assembler";
  38.            easywords[34]="informing";
  39.            easywords[35]="monitor";
  40.            easywords[36]="core";
  41.            easywords[37]="opportunity";
  42.            easywords[38]="process";
  43.            easywords[39]="unfortunate";
  44.            easywords[40]="wall";
  45.            easywords[41]="instruction";
  46.            easywords[42]="total";
  47.            easywords[43]="angle";
  48.            easywords[44]="outside";
  49.            easywords[45]="pipe";
  50.            easywords[46]="connection";
  51.            easywords[47]="ground";
  52.            easywords[48]="flash";
  53.            easywords[49]="movement";
  54.            easywords[50]="repeating";
  56.         int lives=10;
  57.         char [] alphabet=new char[26];
  58.         alphabet[0]='a';
  59.         alphabet[1]='b';
  60.         alphabet[2]='c';
  61.         alphabet[3]='d';
  62.         alphabet[4]='e';
  63.         alphabet[5]='f';
  64.         alphabet[6]='g';
  65.         alphabet[7]='h';
  66.         alphabet[8]='i';
  67.         alphabet[9]='j';
  68.         alphabet[10]='k';
  69.         alphabet[11]='l';
  70.         alphabet[12]='m';
  71.         alphabet[13]='n';
  72.         alphabet[14]='o';
  73.         alphabet[15]='p';
  74.         alphabet[16]='q';
  75.         alphabet[17]='r';
  76.         alphabet[18]='s';
  77.         alphabet[19]='t';
  78.         alphabet[20]='u';
  79.         alphabet[21]='v';
  80.         alphabet[22]='w';
  81.         alphabet[23]='x';
  82.         alphabet[24]='y';
  83.         alphabet[25]='z';
  85.            System.out.println("You have chosen easy difficulty");
  86.            int which = (int)(Math.random()*51);
  87.            char[] guess= new char[easywords[which].length()];
  88.            for(int index=0; index<easywords[which].length(); index++) guess[index]='-';
  90.         while(lives>0&&!check(guess,easywords[which]))    
  91.         {
  92.                for(int index=0; index<easywords[which].length(); index++) System.out.print(guess[index]);
  93.                System.out.println();
  94.                System.out.print("Guess a letter: ");
  95.                char letter = In.getChar();
  96.                boolean found=false;
  97.                for(int index=0; index<alphabet.length; index++)
  98.                {
  100.                    if(letter == alphabet[index])
  101.                    {
  102.                        found=true;
  103.                        alphabet[index]=' ';
  104.                        for(int i=0; i<easywords[which].length(); i++) if(easywords[which].charAt(i)==letter) guess[i]=letter;
  105.                        break;
  106.                    }    
  108.                }
  109.                if(found==false) 
  110.                lives--;
  111.                System.out.println("Lives remaining: "+lives+"");
  113.         }
  115.        }
Now the problem is how can i lower the lives whenever they get a letter wrong?
The lives--; isn't working for me!
Dec 15 '08 #18
3,112 Expert 2GB
Actually, the lives--; part shouldn't be the problem. But you probably don't want
Expand|Select|Wrap|Line Numbers
  1. if(found==false) 
  2. lives--;
  3. System.out.println("Lives remaining: "+lives+"");
but instead
Expand|Select|Wrap|Line Numbers
  1. if(found==false) {
  2.    lives--;
  3.    System.out.println("Lives remaining: "+lives+"");
  4. }
That way, both of those commands are run if the if-clause is correct. Otherwise, only the lives-- is done.

Dec 15 '08 #19
I can't get it to display the lives remaining now, where should I move the line of code to?

The line of code i'm referring to

Expand|Select|Wrap|Line Numbers
  1. System.out.println("Lives remaining: "+lives+"");
Now what it does is only display the lives remaining after I guess over 10 times.
Dec 15 '08 #20
11,448 Expert 8TB
I fail to see how you're using the methods I described in reply #10; you're heading towards the procedural, low level way of solving this: hundreds of lines of (buggy) code and a messy control flow.

Don't be afraid to throw away your old code and start afresh.

kind regards,

Dec 15 '08 #21
Yeah I know, but it's just hard for me to let go of all the other stuff I've been doing, and I've got a deadline for tomorrow. Basically everything is working except for the lives. I just want to know how I can fix that part up since I really don't think I have the time to start all over again.
Dec 15 '08 #22
3,112 Expert 2GB
OK, I checked it out and found your flaw:
Expand|Select|Wrap|Line Numbers
  1. if(found==true) // that could be just "if(found)"
  2.       lives--;
  3. System.out.println("Lives remaining: "+lives+"");
Dec 16 '08 #23
Bah...I ended up figuring it out myself, although I really appreciate the help you guys gave.

Thanks a bunch! The program works perfectly now!
Dec 16 '08 #24
11,448 Expert 8TB
Congrats; I think your deadline has passed by now and I want you to have a look at the following implementation: no loops, no char arrays and no convoluted control flow. Please study it a bit and see how it can be done in a more neat way:

Expand|Select|Wrap|Line Numbers
  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;
  5. public class HangMan {
  7.     private BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
  8.     private String correct, used, word;
  9.     private int lives;
  11.     private void setup(String w, int turns) {
  13.         correct= "-"; used= ""; word= w;
  14.         lives= turns;
  15.     }
  17.     private String word(String prompt) {
  19.         String word= this.word.replaceAll("[^"+correct+"]", "-");
  20.         System.out.println(prompt+": "+word);
  21.         return word;
  22.     }
  24.     private boolean wins(String word) {
  26.         boolean wins= word.indexOf('-') < 0;
  28.         if (wins)
  29.             System.out.println("You guessed the word");
  30.         return wins;
  31.     }
  33.     private String guess(char x) {
  35.         if (used.indexOf(x) >= 0) 
  36.             return word("Character '"+x+"' already used");
  38.         used+= x;
  40.         if (word.indexOf(x) < 0) {
  41.             lives--;
  42.             return word("Character '"+x+"' is incorrect");
  43.         }
  45.         correct+= x;
  47.         return word("Character '"+x+"' is correct");
  48.     }
  50.     private char input() {
  52.         String s= "";
  53.         try {
  54.             for (; (s= s.trim()).length() == 0; s= br.readLine()) 
  55.                 System.out.print("Guess a character: ");
  56.         } catch (IOException ioe) { System.exit(1); }
  58.         if (s.equals("stop")) System.exit(0);
  60.         return s.charAt(0);
  61.     }
  63.     public boolean play(String word) {
  65.         for (setup(word, word.length());; System.out.println("lives: "+lives)) 
  66.             if (wins(guess(input()))) 
  67.                 return true;
  68.             else if (lives == 0) {
  69.                 System.out.println("You lose");
  70.                 return false;
  71.             }
  72.     }
  74.     public static void main(String[] args) {
  76.         new HangMan().play("defenestration");
  77.     }
  78. }
kind regards,

Dec 16 '08 #25
Hello. So I am trying to learn about Java on my own because I thought it would be interesting. I would be really interested in seeing how you did your program. I bought the Java book by C. Thomas Wu and there is a similar problem in the book that is giving me a hard time.

Dec 8 '11 #26

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

1 post views Thread by rainbowii7 | last post: by
5 posts views Thread by tigrfire | last post: by
4 posts views Thread by princessfrost | last post: by
47 posts views Thread by araujo2nd | last post: by
3 posts views Thread by kaka_hunter | last post: by
8 posts views Thread by tidiz | last post: by
reply views Thread by NeoPa | last post: by
reply views Thread by YellowAndGreen | last post: by
reply views Thread by aboka | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.