In: Computer Science
Can you create a player vs computer Hangman game on MATLAB using nested loops, for loops, if loops, while loops, arrays and conditional execution, as well as creating an image of the game board. The list below must be considered in the code.
- Selecting a word from a dictionary (a text file)
- Reading a single letter from the user
- Building a character array showing the letters matched so far
- Keeping count of the number of guessed letters so far
- Keeping count of the number of guesses so far
- Writing conditional logic to see whether the game is finished or not.
Note: Done accordingly. Please comment for any problem. Please Uprate. Thanks.
Download dctionary:https://raw.githubusercontent.com/dwyl/english-words/master/words_alpha.txt
Code:
fid=fopen('dict.txt');
% set linenum to the desired line number that you want to
import
linenum = randi(370103);
% use '%s' if you want to read in the entire line or use '%f' if
you want to read only the first numeric value
word = textscan(fid,'%s',1,'delimiter','\n',
'HeaderLines',linenum-1);
B=convertStringsToChars(string(word));
len = strlength(B);
guessedCorrectly=char(95+zeros(1,len));
guessedIncorrectly=[];
countCorrect=0;
countInCorrect=0;
while true
c=input('Please guess next character :','s');
c=char(c(1,1));
if ismember(c,guessedIncorrectly) ||
ismember(c,guessedCorrectly)
disp("Already Given earlier")
else
if ismember(c,B)
for i=[1:len]
if B(i)==c
guessedCorrectly(i)=c;
end
end
disp(guessedCorrectly)
countCorrect=countCorrect+1;
else
countInCorrect=countInCorrect+1;
guessedIncorrectly=[guessedIncorrectly c];
end
end
disp(["Incorrect Guesses :",guessedIncorrectly]);
if ismember('_',guessedCorrectly)
continue
else
break
end
end
fprintf("Total guesses :%d\n",(countCorrect+countInCorrect))
fprintf("Total guessed correctly :%d\n",countCorrect)
fprintf("Total guessed incorrectly :%d\n",countInCorrect)
Output: