Chris, try this:
word = 'MyMatlab';
masked = repmat('*', size(word));
wrongGuesses = 0;
wordGuessed = false;
while wrongGuesses < 6
clc; fprintf('Word : %s\n',masked);
letter = lower(input('Guess a letter : ','s'));
wordMask = lower(word)==letter;
if any(wordMask)
masked(wordMask) = letter;
else
wrongGuesses = wrongGuesses+1;
end
if ~any(masked=='*')
wordGuessed = true;
break;
end
end
clc; fprintf('Word : %s\n',masked);
You'll see above that we can use lower to remove case-sensitivity. Also note that I'm using a straight letter comparison via the == operator. This is because findstr is not recommended (it will be removed in a future version of MATLAB), but you could just as easily use strfind (I know... confusing.)
Also note the two ways to exit the loop. One coming from too many wrong guesses, another coming from the break statement if all asterixs have been replaced. You'll be able to tell which exit happened by checking the wordGuessed boolean.
Best Answer