Untitled
unknown
plain_text
3 years ago
1.8 kB
15
Indexable
% Read in a list of words from a text file
words = textread('words.txt','%s');
% Choose a random word from the list
target_word_index = randi(numel(words));
target_word = words{target_word_index};
% Set the maximum number of guesses
max_guesses = 5;
% Initialize the number of correct guesses
correct_guesses = 0;
% Loop until the player runs out of guesses or correctly guesses the target word
while (correct_guesses < numel(target_word)) && (max_guesses > 0)
% Display the blank board
board = blanks(numel(target_word));
for i = 1:numel(target_word)
plot(i,0,'o','MarkerSize',50,'MarkerFaceColor','w','LineWidth',2);
text(i,0.2,board(i),'HorizontalAlignment','center');
end
axis([0 numel(target_word)+1 -1 1]);
axis off;
% Allow the player to enter a guess
guess = input('Enter a guess: ','s');
% Check the guess against the target word
for i = 1:numel(target_word)
if guess(i) == target_word(i)
% Letter is correct and in the correct position
board(i) = guess(i);
plot(i,0,'o','MarkerSize',50,'MarkerFaceColor','g','LineWidth',2);
text(i,0.2,board(i),'HorizontalAlignment','center');
correct_guesses = correct_guesses + 1;
elseif ~isempty(strfind(target_word,guess(i)))
% Letter is correct but in the wrong position
plot(i,0,'o','MarkerSize',50,'MarkerFaceColor','y','LineWidth',2);
end
end
% Decrement the number of guesses
max_guesses = max_guesses - 1;
end
% Display a message to the player
if correct_guesses == numel(target_word)
disp('Congratulations, you guessed the word!');
else
disp(['Sorry, you ran out of guesses. The word was ' target_word]);
end
Editor is loading...