how do i make the user only input 1 letter at a time with this code?

조회 수: 9 (최근 30일)
Joshua
Joshua 2024년 11월 1일
이동: Walter Roberson 2024년 11월 1일
play = menu("Play A Word Game? ","Yes","No");
cPLAY = 1;
while play == 0 && cPLAY < 5
play = menu("Play A Word Game? ","Yes","No");
cPLAY = CPLAY + 1;
end
if play == 0
error('TOO LATE')
end
while play == 1
fprintf("Guess the 5 letter word: _____ \n\n")
index = randi(495); %the bank of words I am using has 496 words
wordstring= string(WORDS(index));
WORD = char(WORDS(index)); % must use a character array,
fprintf('A word has been chosen. Please click to continue.')
pause()
% Setup Correct and Wrong character strings (Task 2)
wrong = 0;
right = 0;
while right < 5 && wrong < 9
clc
correct = char("_____");
badGuesses = '';
disp(correct);
fprintf("\n----- %d of 9 incorrect guesses: %s ------\n\n", wrong, string(badGuesses));
GUESS = input("What is your guess? Please enter lowercase letters only: \n", 's');
GUESS = char(GUESS);
% Check if the guess is correct or not (Task 3)
anyRight = 0
for x = 1:1:5
if WORD(x) == GUESS
correct(x) = GUESS;
anyRight = 1;
right = right + 1;
end
end
if anyRight == 0
badGuesses = [badGuesses,GUESS];
wrong = wrong + 1;
end
end

답변 (1개)

Walter Roberson
Walter Roberson 2024년 11월 1일
이동: Walter Roberson 2024년 11월 1일
input() cannot be constrained to accept only single characters.
You could menu() or listdlg() listing the possible characters. As an enhancement, your list of possible characters could be changed to eliminate the characters that have already been chosen.

카테고리

Help CenterFile Exchange에서 Word games에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by