• Post Reply Bookmark Topic Watch Topic
  • New Topic

Basic Hangman game attempt  RSS feed

 
Patrick De
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am going to try a simple hangman game project. After thinking about it, I might have to use Array (which I don't know)
I want the player ONE to input ONE word up to 7 letters and then ask player TWO to guess letters in the alphabet until the hangman is either created (just using words) or they get the right answer.

So the easy part would be inputting the string, and separating the characters. BUT this means separating each word into characters and store them, right? Here is what I have, most code taken from one source or another. I think I have the information stored in an array, but I don't know how to access it afterwards. I might be doing this completely backwards as well. What do you think?

I am also aware that my comments are meaningless and annoying, but truly they help me understand and remember. No offense to anyone I am just new and finding this extremely difficult.

 
Stefan Evans
Bartender
Posts: 1837
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What you've got so far looks ok, but you haven't quite managed to copy things into the array as of yet.
You have created an array of 7 characters, but you haven't copied them over.

To put the letter 'a' into the first slot in the array you would need a line such as


You can probably take it from there and add the missing line of code to your loop.
The other thing you might consider doing is rather than creating an array of seven characters, create it the same size as the String the user entered.

However, I don't know that you absolutely need to.
A String by definition is a sequence of characters.
You have already shown that you can get at the characters one by one using the charAt method.
I see no problem with keeping the word to guess in a String.

The next questions then
- How do you keep track of what guesses the other player has made?
- How do you print out the word using ONLY the letters that the person has guessed so far.
 
Patrick De
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for that, I cannot believe how challenging this is trying to get my head around what it is doing. I even created a flowchart (as I heard that is helpful with programming) but I am not sure even where to go from here. I think I am going to go back and try without the array. I was looking at this code and thinking it could help me (taken from MarkVowels There are a couple of things I don't understand.

1) What does the int. vowelCount = 0 do? I haven't seen it called on after it is declared.
2) What does the StringBuilder do?

Thank you.

 
Patrick De
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok I tried this, and I am getting an error. I am well aware that I am not doing it the right way, but I thought it might work.
1) what I am trying (without an array because I don't understand them yet) is that the user inputs a word.
2) The computer runs a DO WHILE loops that takes each character of the word (until the length is reached) and assigns it as such oldChar(i) = userInput.charAt(i)
My thinking on this is as such. The first letter is character ZERO, so it assigns the variable oldChar0 to the user input of the charAt(0) , oldChar1 would be assigned to charAt(1) etc. Each time the value of "i" would dictate the variable for oldChar(i)
I hope that makes sense.


 
Campbell Ritchie
Marshal
Posts: 56598
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The way that code is developing makes me think you are guessing. You can guess 1000000 times and as long as the guesses are different you will probably have a correct solution somewhere. Or you can plan the code and get it right first time.

Start by writing down the rules in small simple words, the you will be able to work out the correct logic and the correct code to embody that logic.
Line 47 is horrible. Not only is it so long that it messes up the formatting, which I corrected for you so you can see how to do it. But also, it constitutes repeated code. I think that test should be refactored into a method of its own. Why did you not put the guesses into an array or similar?

Please check your formatting. Your indentation is inconsistent. Look at line 41, and line 52. you should have spaces before every { if you use K&R indentation. And spaces after } if you write } else { all on one line. You also have too many blank lines where one blank would do.
 
Patrick De
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I got a little help from a friend that said to use Arrays in this case - I am extremely glad because I just about gave up. I did try it the other way (without arrays), but this way seems to be in the right direction for someone that is sucking at this

1) I tried to clean up the code, putting curly braces right underneath the corresponding curly brace. I think that is what you do.
2) I tried to eliminate un-needed spaces (I like spaces because it helps me differentiate what each part is doing)
3) The problem with the code below is that I am not sure how to store the part where they got the right letter and eliminate it from guesses.
4) still much more work to be done
5) any suggestions?

 
Stefan Evans
Bartender
Posts: 1837
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok, so you have got the user to enter a word
You have got the user to enter a letter to guess
You can output whether or not that letter is in the word

Next: how to keep track of what letters have been guessed, and output the word with the appropriate guessed letters.
I would suggest writing a method: outputWordToGuess(wordToGuess, guessedCharacters) (You will need to define what the data types for those parameters are)


Here is one quick and hacky suggestion:
Declare a String variable called "guessedLetters"

Every time the user guesses a letter add it to this string.

To output the word, go through your array of letters.
If a letter is in the 'guessedString' somewhere you can output it.
If not then you can output a placeholder. e.g. '_'
String's indexOf method might be useful here .

Does that make sense?


 
Patrick De
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok I will try. With Methods, does it matter where it goes in the code? Are method only used when they are called upon? For example if I had a method to generate a random number but never call the method, will it execute the method or only if I ask it to?
 
Carey Brown
Saloon Keeper
Posts: 3329
46
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Only if you explicitly call the method.
 
Patrick De
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am lost again. Do I use a DO WHILE loop so the person keeps guessing?
 
Stefan Evans
Bartender
Posts: 1837
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
>I am lost again. Do I use a DO WHILE loop so the person keeps guessing?

Sounds like the right approach to me.

What would your end condition for the loop be?
i.e. How do you know when to stop looping.



 
Patrick De
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That is the problem, I don't know. I am trying to put in a do while loop, but wherever I put the code, I start to get errors that were never there before in my existing code. I thought the do while loop would reside before the guessing started - and end after the it added to the string, but that seems to give me nothing but errors. It would end looping after it runs out of guesses?
Here is the code, I know it is pretty stupid looking, but I am just dumb when it comes to figuring this stuff out

 
Stefan Evans
Bartender
Posts: 1837
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So pseudocode I would do for it looks something like:




I trust you have something similar :-)
 
Stefan Evans
Bartender
Posts: 1837
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In terms of a syntax error, the end of your while loop is in the wrong place.
you have



Put like that you should see that you have too many closing brackets, and your end for do-while needs to be after the end of your for.
 
Patrick De
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I apologize in a advance for this but I am just not getting it right. I followed the curly brackets to ensure I had the right amount and that they were inline with each other AND that I had the right amount going through the entire code. I then looked at the pseudo code and tried to line up my do while loop in the same way (I wish Eclipse had a way to COLOUR code the code so it might be easier to look at blocks of it, but alas.)

I took a screen grab of the side by side code to show that I am trying to get the curly brackets and such on track . I know I have messed up in a few places, but I can't see where or why.

Here is the code :
question-code.jpg
[Thumbnail for question-code.jpg]
comparison code
 
Stefan Evans
Bartender
Posts: 1837
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok, here are some minimal changes to make things compile/run again.
But I think it is time to do some refactoring/simplifying of this code.

 
Stefan Evans
Bartender
Posts: 1837
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok, time for some refactoring into smaller methods.

Step1: Move code from the static main method into a regular method. Change main to just call that method. Also renamed class to HangmanTest2 to follow conventions of capitalizing class names.




Step 2: Extract some logic into a method:
I made a method "readSecretWordFromPlayer"
It contains all your own code, just grouped into this logical method. The playGame() method now delegates to this method rather than having the code itself.




I have added another method stub of what I think should be the next bit pulled out.
So if you want to keep going in this way, move the relevant code from the "playGame" method into "askUserForLetter"

Doing this breaks your code up into manageable pieces - which is where you seemed to be wanting to go.

Do you follow so far?
 
Patrick De
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am trying to get my head around it. I can see the changes you made and thank you for that. After running the first iteration of the code you changed, it does not add letter to the string (the ones already guessed), it just seems to add the new guessed letter and after trying again and again, it only shows the most recent guessed letter rather then adding to a string.

Out of curiosity, is there a program like Eclipse that will let the user color blocks of code or at least change the text colour?
 
Stefan Evans
Bartender
Posts: 1837
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
> After running the first iteration of the code you changed, it does not add letter to the string (the ones already guessed),
>it just seems to add the new guessed letter and after trying again and again, it only shows the most recent guessed letter rather then adding to a string.

That is correct, and that is the way it worked before I fiddled with your code.
I was trying to do the least amount of change to
- get things compiling
- refactor some code out into methods.

I have deliberately left some bugs in there for you to fix yourself. This is NotACodeMill.

The String "addTo" is declared within your for loop which is checking to see if a letter matches.
Think about the scope you want for this variable. How long do you want to use it? If you want to keep it across multiple guesses, you will have to shift that declaration.


Also consider the following input:

Please enter ONE secret word: java
Please guess a letter: a

What output do you get?
What output do you expect?


>Out of curiosity, is there a program like Eclipse that will let the user color blocks of code or at least change the text colour?
Eclipse is completely configurable with regards to colours. Check out http://eclipsecolorthemes.org/
Not sure about other tool capabilities but I would think so...
 
Patrick De
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I actually appreciate the fact that you haven't handed it to me, I need to work it out myself with assistance.
Yes I can see that right I need to use a IndexOf (I think) to handle adding things to a string.

As for the colours, I was thinking that I could HIGHLIGHT blocks of code and color-code them, like in a word processing editor. I did see the color themes, but that wasn't what I was hoping for.

I do like the ideas of Methods, but I have to get my head around them. Reading about them and understanding their use is different for me. I need to truly get what they are doing that is why I am still working with the original code that you changed the first time.

I know the program is looking at each character in the do while loop.
For example, when the word JAVA is inputted and the user selects "a", it looks at the first characters and says "missed" then the second character and says "got it", the third characters and says "missed" and the forth characters and says "Got it!". I want it to take that "a" and add it to a string that I can compare everything to so the user does not input the same letter twice. I know I don't need to print out the "got it!" and "missed" that is more for me.

Next Steps
1) I need to have a counter when they miss, so a limb can be added. I think an Array string that would have a list of limbs (maybe random for fun) that pulls out names like arm, legs etc. as the count of misses goes up (all of this I don't know how to do but will try to figure out).
2) A way of appending a string



 
Carey Brown
Saloon Keeper
Posts: 3329
46
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
David De wrote:A way of appending a string
s1 = s1 + s2; or more concisely s1 += s2;
 
Stefan Evans
Bartender
Posts: 1837
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Heh. Methods are so fundamental to me now that I forget the time when I struggled to understand them.

>as for the colours, I was thinking that I could HIGHLIGHT blocks of code and color-code them, like in a word processing editor
Nope, don't know of an editor that can do that sort of thing. That is why I was suggesting methods because it does separate the code into logical chunks - which is probably why such highlighting isn't so necessary.

The easiest way to add things to a string is just to add things to the beginning or end with the '+' operator, or concat method.


I would actually suggest separating out the 'letters guessed so far" from the message " already guessed letters:"
That way you can update the one without having to worry about slicing up the string every time.
 
Campbell Ritchie
Marshal
Posts: 56598
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When I went to Devoxx somebody said the correct way to concatenate Strings is with +. But that only applies when you are all in one statement. If you have one statement you can join as many Strings as you like with the + operator. You can use + a hundred times in the same statement and that is still the best way to catenate Strings. But when you have multiple statements, that no longer applies.

If you are in a loop and usingi
s += text;
you are risking going into slow execution. If I try that in a loop running 10000 times I can see how long the loop takes to run. If I run the loop 1000000 times, I can go and have dinner while the loop is running. So there is an alternative for multiple statements appending Strings (or appending in loops):-Two suggestions for your game:
  • 1: If you use a Scanner to enter the solution it will be visible to the other player. Try word = new String(System.console().readPassword("Please enter secret word: "));
  • 2: If you use a Scanner to enter the solution it will be visible to the other player. Try word = JOptionPane.showInputDialog(null, "Please enter secret word.");
  • JOptionPane is a very old‑fashioned method for keyboard entry, and must be imported with import javax.swing.JOptionPane; before the name of the class. Old‑fashioned maybe, but useful here.
    If you open the program from an IDE or from an executable .jar with javaw rather than from the command line/terminal with the java tool, the console will be null and you will suffer a null pointer exception.
     
    Patrick De
    Ranch Hand
    Posts: 131
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    I am not sure where to even start now. I wonder if I am over my head and should start with something simpler rather than tackle this, although this might be simple project, I find I am staring at the code for hours on end not getting where to go from here...

    1) I tried to download some themes and they seem to have screwed up my eclipse. How can I revert to normal?
    2) How does a method work? To me, it almost seems like a folder with some programming in it that you can look in when you call upon it. The only challenge is if the programming is only called on when you need it, do the variables or outputs carry across to other folders? If I got an output of i=4 from a method, and I switch to another method, is it going to tell me I need to define the variable for "i" because it is not in that method? Does the RETURN function mean it returns everything that was used in that method?

     
    Carey Brown
    Saloon Keeper
    Posts: 3329
    46
    Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    I would suggest getting a beginner's book on Java and reading it thoroughly and work on the assignments that it provides. Having a book that feeds you bite sized information and has exercises that only uses the information it has given you so far is an excellent way to learn. I also suggest becoming very familiar with the Java API Javadocs and how to navigate them and interpret what they are telling you. If you have trouble working out a particular assignment you can always come back here.
     
    Patrick De
    Ranch Hand
    Posts: 131
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    I bought Java all in one for dummies 9 in 1 books, but it doesn't seem to help. I was hoping for a book with projects in it that takes step by step instructions for beginners. Any recommendations?
     
    Liutauras Vilda
    Sheriff
    Posts: 4928
    334
    BSD
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    David De wrote:I bought Java all in one for dummies 9 in 1 books, but it doesn't seem to help. I was hoping for a book with projects in it that takes step by step instructions for beginners. Any recommendations?

    1. Very popular book among beginners is - Head First Java. It contains nice projects to do, with detailed explanations
    2. Java For Everyone: Late Objects (loved in academic life, since it starts from the very basics, there are plenty of exercises at the end of each chapter)
    3. https://docs.oracle.com/javase/tutorial/ (quite good place so start as well)

    Best Luck,
    Liu
     
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!