MATLAB Answers

Saving Output in a While Loop

4 views (last 30 days)
Benjamin Cullum
Benjamin Cullum on 28 Apr 2021
Edited: Turlough Hughes on 22 May 2021
dict=readDictionary('dictionary_long.txt'); % read dictionary
idx=randperm(length(dict),1);
randWord = dict{idx};
str = randWord;
for i = 1:length(randWord)
fprintf("*");
end
fprintf("\n");
for i = 1:length(str)
disp(str(i))
end
Correct = [];
while (some condintion)
A = input('Enter a Letter: ','s');
for i=1:strlength(str)
Correct = strrep(randWord,str(i),A);
if Correct == randWord
fprintf(A)
else fprintf('*')
end
end
fprintf('\n')
end
I'm making a game of hangman and have gotten the code to produce a random word in a dictionary, however i can't save the letter I guess from the while loop. This means the user can't keep track of the letters they have tried. Is there any way to save these correct attempts into a vector?

Answers (1)

Turlough Hughes
Turlough Hughes on 28 Apr 2021
Edited: Turlough Hughes on 22 May 2021
You could store the letters as follows in the variable currentResult. I've added in some conditions to count lives. One could also add other conditions like, checks to ensure you don't guess the same letter twice. The while loop runs until one of the conditions in the second if else block becomes true, i.e. after you win or you die.
dict= {'filter','random','ubiquitous','solid','granular','torment'}; % small sample dictionary
idx=randperm(length(dict),1);
randWord = dict{idx};
% Displays current known letters, and number of letters
currentResult = repmat('*',size(randWord));
disp(currentResult)
% ?? I'm guessing this is useful for testing
for i = 1:length(randWord)
disp(randWord(i))
end
numLives = 4; % this can decrement by 1 for each incorrect attempt
while true
A = input('Enter a Letter: ','s');
idx = randWord == A; % Check if input, A, matches any letters in randWord.
if any(idx) % One or more letters matched
currentResult(idx) = A; % Insert matched letter(s) into currentResult
disp('Correct!')
fprintf('Word: %s\n\n',currentResult) % display updated 'currentResult'
else % case for incorrect guess.
numLives = numLives-1; % lose a life
fprintf('Incorrect! Number of lives left: %d\n',numLives) % display numLives
fprintf('Word: %s\n\n',currentResult) % display current result
end
% if one of these conditions passes, let user know they won/died and
% exit loop.
if numLives == 0
disp('You died.')
break % exits the loop
elseif ~any(currentResult=='*') % if there are no *'s left then you win.
disp('Congratulations, you win!')
break % exits the loop
end
end

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by