Hangman right word replacement
1 次查看(过去 30 天)
显示 更早的评论
Hi,
I am making a simple hangman game for a project. I am currently stuck on replacing a "_" and printing the correct letter in place. Can someone please help, parts of my code are below:
wordlength = strlength(word);
hide = repmat(' _ ', 1, wordlength);
fprintf('%s\n', hide);
fprintf("\nThere are %d letters in this word.\n", wordlength);
incorrect = 0;
left = 7;
while (incorrect < 7)
letter = input("Please guess a letter (1 lowercase letter): ", 's');
consists = ismember(word, letter);
if ~any(consists)
incorrect = incorrect + 1;
left = left - 1;
fprintf("\nSorry this is incorrect, you have %.0f guesses left.\n", left);
else
fprintf("This is right!");
hide(consists) = letter
end
end
if (left == 0)
fprintf("\nGAME OVER! YOU LOSE\n");
end
Example:
Lets say there are 6 letters in the word, and the word is 'wizard'. It will print " _ _ _ _ _ _ ".
It then asks for a letter, lets say i type 'w'. It says "This is right!" and shows: hide = 'w_ _ _ _ _ ' . However, It should replace the first '_'.
when it asks for another letter, lets say i type in 'i'. It says "This is right!" and shows: hide = 'wi _ _ _ _ _ ' .
then the third time i type 'd', it says "This is right!" and shows: hide = 'wi _d _ _ _ _ ' .
Thanks.
0 个评论
回答(1 个)
Mehmed Saad
2020-4-30
编辑:Mehmed Saad
2020-4-30
because
' _ '
are three characters and not 1. first index is space, 2nd is dash and 3rd is space again
what you need is replace the dashes and not the space
for example
if i have
' _ _ _ _ '
The first dash occurs at 2nd index and 2nd dash occurs at 5th index and goes on with 3 index difference
Currently you ve logical index (consists) change them to array index (using find)
For example
A = [1 0 0 1]
B = find(A)
B =
1 4
Or you can replace ismember with strfind
Once you have the index multiply them with three to access every third index and you ve to subtract 1 from them because dash is at 2,5,7,..
PS: Please add a condition for correct answer in your code i.e. if a person guess all the letters stop the game
11 个评论
Rik
2020-4-30
You don't need to change that aspect, just how you store your data. "If you separate the data storage from the data displaying your code will be much simpler." Take that advice to heart.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Line Plots 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!