MATLAB: How to replace ‘_’ with a guessed word

#hidden words

Hi,
I am making a hangman game for a school project and needed help with how to replace hidden words with the right word if guessed.
This part of the code prints "__" for each letter in the word.
word = char(word);
wordlength = strlength(word); % To find length of word
for i = 1:wordlength
fprintf(" __ ");
end
I have given the user 6 incorrect guesses until they lose the game. I was planning to use a while loop for this step:
incorrect = 0;
left = 7;
while (incorrect < 7)
guess = input("Please guess a letter (lowercase): ", 's');
if guess ~= word(i) % unsure about this


incorrect = incorrect + 1;
left = incorrect - 1
fprintf("That is incorrect, you have %.0f incorrect guesses left.", left)
end
for i = 1:wordlength
if word(i) == guess % unsure about this
= % unsure about this
end
end
end
Can someone please tell me how i could replace __ with the right word if guessed?
Thanks

Best Answer

Here are some tips. Rename the generic variable names I created.
  • Instead of the wordlength loop, s = repmat(' _ ', 1, wordlength); fprintf('%s\n',s); That's 1 underscore per letter.
  • Instead of if guess ~= word(i), use idx = strfind(word, guess); if ~isempty(idx)
  • To insert a correctly guessed letter, dashidx = strfind(s, '_'), s(dashidx(idx)) = guess;
  • You'll also need to add something that stops the game when the correct word was chosen.
Related Question