% guessing_game_modified.m
% Russ Poldrack, 12/30/02
% example solution of Exercise 2, problem 1


magic_number_range = 8;  % the maximum allowable magic number

num_guesses=20;  % give the subject multiple guesses

correct=zeros(1,num_guesses);  % create a variable to hold accuracy data

% loop through guesses

for trial=1:num_guesses,

    % first, determine the magic random number

    magic_number = ceil(rand * magic_number_range);


    % now, ask the user to guess the magic number

    input_prompt=sprintf('Guess a number between 1 and %d\n',...
	magic_number_range);

    % make sure it's a legal guess
    good_guess=0;
    while ~good_guess,
        
        guess = input(input_prompt);
        if guess > 0 & guess < magic_number_range,
            good_guess=1;
        else,
            fprintf('your guess must be a number between 1 and %d, try again!\n\n',...
                magic_number_range);
        end;
    end;

    % test the guess to see if it is correct

    correct(trial) = (guess == magic_number);

end;

% determine the number correct

num_correct = sum(correct);

% determine the probability of this number of correct responses
% under the null hypothesis of chance guessing
if num_correct>0,
    p = 1 - spm_Icdf(num_correct-1,num_guesses,1/magic_number_range);
else,
    p=1;
end;

% print a report to the screen

fprintf('Report\n');
fprintf('You correctly guessed on %d of %d trials\n',...
	     num_correct,num_guesses);
fprintf('The probability of doing at least this well is %0.3f\n(under the H0 of chance guessing)\n',p);

% print the report to a file

fid=fopen('report.txt','w');
fprintf(fid,'Report\n');
fprintf(fid,'You correctly guessed on %d of %d trials\n',...
	     num_correct,num_guesses);
fprintf(fid,'The probability of doing at least this well is %0.3f\n(under the H0 of chance guessing)\n',p);
fclose(fid);

% plot the binomial cdf

figure;  % create a new figure

all_p = 1-spm_Icdf([0:num_guesses-1],num_guesses,1/magic_number_range);

plot([1:num_guesses],all_p);
hold on
plot(num_correct,p,'r*')