How would I translate my hand example into code?
1 view (last 30 days)
Show older comments
I'm trying to come up with a while loop for hangman, I have a random word selected and then I used ~isspace to change the letters to a * symbol. I'm new to programming and am having trouble translating my hand example to actual code.
word_hide = mystword;
word_hide(~isspace(word_hide)) = '#';
My hand example is
- 1) get a letter from the player
- 2) check to see if it's in the mystery word
- 3) if it's in the mystery word, update the hidden word to show the letter there
- 4) if it isn't in the mystery word, update the counter for wrong guesses (+1)
- 5) ask player for a new letter
The game would end when there are 6 wrong guesses or if the word is guessed.
Any suggestions would be really appreciated.
0 Comments
Answers (1)
Image Analyst
on 8 Mar 2013
You might start with something like
if strcmpi(usersString, correctAnswer)
% Then they guessed correctly.
uiwait(msgbox('You got it right!'));
else
% They got it wrong.
end
Put that in a while loop where you're counting the number of guesses, and so on.
2 Comments
Image Analyst
on 8 Mar 2013
Edited: Image Analyst
on 8 Mar 2013
No. As soon as you increment right_guess, your loop will quit because of this line:
while right_guess == 0
Plus, you're asking your user to input only single letters, not whole words but the comparison will only be true if the whole word matches. I think you need to think some more about the logic. Try using strfind() if you want to find only a single letter. You might have a "hidden" word that starts out as all * and then change the * to the correct letter if they guess the letter correctly.
location = strfind(mystword, guess);
if ~isempty(location)
word_hide(location) = guess;
fprintf('%s\n', word_hide);
end
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!