Hello Matthew Smyth,
I understand that you want to develop a MATLAB program that can simulate the game of hangman. Particularly, you are facing an issue preventing the same input from being entered twice or stopping the correct-guesses counter from incrementing again for an already verified input.
After inspecting your code, I identified a few areas in the code that can be modified.
- This if-else block will always execute the else block as the condition can never be true.
if incorrectCount==length(guessingWord);
guessesLeft=guessesLeft-1;
fprintf('Your letter is not in the word!\n');
fprintf('You have made a correct guess!\n')
- Consider combining the first guess prompt with the while loop to make the code look cleaner easier to understand.
- The looping conditions seem to be incorrect.
- The second half of the while condition seems to be incorrect even according to your current logic
while ~(guessesLeft <= 0) || ~(correctCount == length(guessingWord-1))
Coming back to the main issue of mitigating the incrementation of the "correctCount" counter for the same input, a truth-table (boolean array) can be considered. Initially a truth-table of size "guessingWord" could be initialized with all indexes set as false. Once a correct guess is made, that index can be flipped to true so that correctCount" counter is not updated again for that particular guess.
Here is a sample implementation that combines all of the above suggestions
IsGuessed = false(1, length(guessingWord))
while ~(guessesLeft <= 0) || ~(correctCount == length(guessingWord))
UserGuess=input('Please enter your guess: ','s');
for i=1:length(guessingWord)
if (UserGuess==guessingWord(i) && IsGuessed(i) == false)
lettersLeft=lettersLeft-1;
correctCount=correctCount+1;
incorrectCount=incorrectCount+1;
fprintf('Your letter is not in the word!\n');
guessesLeft=guessesLeft-1;
fprintf('You have made a correct guess!\n');
Again, this is only a sample implementation. Please feel free to make changes to it as per your requirements.
Hope this helps!