Clear Filters
Clear Filters

How do i tell the player they already guessed a number?

1 view (last 30 days)
I'm building a number game and i want to tell the user that they already guessed the number before, this is what i've gotten so far but it only allerts the user to habing repeated a guess for certain numbers, any help appreciated!
comp_guess = randi([0 100]); %computer generates random number between 0 and 100
Smallest_no = 0;
Highest_no = 100;
trys = 0;
input_st = sprintf ('Guess a number between %d and %d: ', Smallest_no,Highest_no);
player_guess = input(input_st); %making it possible for user to guess number
guess1 = player_guess;
guess2 = 0;
while player_guess ~= comp_guess
if player_guess < 0 %lets the player know if their guess is out of the games range
output = ('Out of range, try again: ');
player_guess = input(output);
end
if player_guess > 100 %lets the player know if their guess is out of the games range
output = ('Out of range, try again: ');
player_guess = input(output);
end
if player_guess > comp_guess % lets the player know if their guess is higher or lower than the computers generated number
disp ('Too high! ')
else
disp ('Too low! ')
end
guess2 = player_guess;
if guess1 == guess2; %lets the player know they already tried this number
disp (' you already guessed this number, try again ');
end
new_guess = sprintf ('wrong answer, please guess again: ');
player_guess = input(new_guess); %Lets the player continue guessing
trys = trys+1; %keeps track of how many guesses you make
end
if player_guess == comp_guess
disp ('Congratulations! You win!') %displays when player guesses correctly
disp (' it took you this many trys :')
disp (trys) % displays how many guesses it took to win
end

Answers (1)

Bob Thompson
Bob Thompson on 10 Apr 2019
I would suggest keeping an array of the guessed values, and then checking if the number exists in that array.
% Outside the loop
guesses = [];
% Inside the loop
if ismember(player_guess,guesses);
disp (' you already guessed this number, try again ');
end
guesses = [guesses player_guess];
As a side note, your check for too high or too low is going to return a flag of 'too low' whenever the guess is correct. You have the condition looking for greater than the value for too high, but all other conditions (less than or equal to) will return the too low message. All you have to do is change your 'else' into an 'elseif player_guess < comp_guess'.

Categories

Find more on Number games in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!