how to replace '_' with a guessed word?
Show older comments
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
3 Comments
Stephen23
on 22 Apr 2020
This could be done very easily using logical indexing. It would let you simplify your code (get rid of some loops).
Kunal Kumar
on 22 Apr 2020
Edited: Kunal Kumar
on 22 Apr 2020
darova
on 22 Apr 2020
Try strrep
Accepted Answer
More Answers (0)
Categories
Find more on Number games 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!