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 个)

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 个评论

So far I have this, I'm not sure if I'm on the right track?
% Hides the word by changing the letters to x's
word_hide = mystword;
word_hide(~isspace(word_hide)) = '#';
% Starts the counters for the game
right_guess = 0;
wrong_guess = 0;
pick = '';
while right_guess == 0
%Displays the mystery word to player and asks for a guess
fprintf('\nThe word is %s\n',word_hide);
disp('Please enter a letter')
guess = input('==>', 's');
pick = num2str(guess);
if strcmpi(mystword,pick)
right_guess = right_guess + 1;
else
wrong_guess = wrong_guess +1;
end
end
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!

Translated by