How would I translate my hand example into code?
이전 댓글 표시
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.
답변 (1개)
Image Analyst
2013년 3월 8일
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
Katherine Brideau
2013년 3월 8일
Image Analyst
2013년 3월 8일
편집: Image Analyst
2013년 3월 8일
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
카테고리
도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!