function connectDotsSol(positions)
% An interactive game to play connect the dots.
% positions is an n-by-2 matrix. positions(:, 1) are the x coordinates of
% the dots in order of connection, and positions(:, 2) are the y
% coordinates of the dots

% set up graphics
close all
board = imread('connect_dots.jpg');

% start game
continuing= 1;
numDots = 0;
totalDots = size(positions, 1);
figLims = plotBoard(board);

% store positions in these vectors
x = [];
y = [];

% each loop does a click
while continuing	
	% notify user in title of current number of dots
	title(sprintf('Select the next dot. Currently have %d dots.', numDots));
	
	% select new dot
	[x1, y1] = ginput(1);
	
	% check if dot is within game board
	if isWithinLims(x1, y1, figLims)
		
		% get number of first selected dot
		i = getSelectedNodeIndex(x1, y1, positions);
		
		% display message for dot click or missed click
		if i > 0
			title(sprintf('Selected dot %d!', i));
            pause(0.5)
		else
			title(sprintf('Not a valid dot, try again.'));
			pause(1)
		end
		
		% check if correct dot is clicked
		if i == numDots + 1
			% draw line to selected dot
			x = [x; x1];
			y = [y; y1];
			numDots = numDots + 1;
			
			if numDots > 1
				plot([x(end - 1) x(end)], [y(end - 1) y(end)], 'r', 'LineWidth', 2);
			end
		else
			% incorrect dot, tell user which dot number to click
			title(sprintf('That is incorrect! Please find dot %d.', numDots + 1));
            pause(1)
		end
		
		if numDots == totalDots
			% win game
			continuing = 0;
		end
	else
		% pressed outside the boundaries --> game over
		continuing = 0;
	end
end

if numDots < totalDots
	% display message for quit game
	title('You quit the game!');
else
	% redraw board with solutions, display message for winning game
	plotBoard(board);
	plot(positions(:, 1), positions(:, 2), 'k', 'LineWidth', 2);
	title('You won the game! Congrats, you are awesome!');
end

hold off


function res  = isWithinLims(x, y, figLims)
% checks if the coordinate is within the figure limits
% x, y, coordinate of mouse button click
% figLims: limits of an immages
res = (x >= figLims(1) && x <=figLims(2) && y >= figLims(3) && y <= figLims(4));


function i = getSelectedNodeIndex(x, y, positions)
% given coordinates (x,y) determine the index  i for which the point with
% coordinates (positions(i,1), positions(i,2) )  is closest to (x,y) AND
% within distance at most 10 units.
% returns 0 if no such point exists

distances = sqrt((positions(:,1) - x).^2 + (positions(:,2) - y).^2);

[d , minI] = min(distances);

if d(1) <= 10
	i = minI;
else
	i = 0;
end


function figLims = plotBoard(board)
% given an image matrix 'board', set up graphics and return dimensions
clf

[n, m] = size(board);
imshow(board);
axis off

figLims = [1 m 1 n];
hold on