Borrar filtros
Borrar filtros

Matlab Count to 10 game

1 visualización (últimos 30 días)
EaglesFan
EaglesFan el 9 de Nov. de 2015
Respondida: Image Analyst el 9 de Nov. de 2015
Hello, I'm currently working on this exercise and I don't know how to continue. Here is the exercise: In this exercise you are required to implement a simple two player counting game. The game starts by setting the count to 0. The two players should take alternative turns selecting between the numbers 1 and 2. In each turn the number the current player selects gets added to the count. The player who reaches a value 10 or larger wins the game. The program should check for input correctness. The image below has a sample run.
I currently have this:
clear
clc
sum=0;
player=1;
while (sum<10);
count=input('Enter 1 or 2: ');
fprintf('Player %d',player);
if (count==1|count==2)
sum=sum+count;
else
disp('Incorrect Input');
end
end
I know I'm quite far from solving the problem and help would be appreciated.
  1 comentario
Walter Roberson
Walter Roberson el 9 de Nov. de 2015
Do not name a variable "sum" as that interferes with using the important MATLAB routine named "sum".

Iniciar sesión para comentar.

Respuestas (1)

Image Analyst
Image Analyst el 9 de Nov. de 2015
You can check for correctness by making sure it's correct in the first place. Use questdlg to give them a choice of only 1 or 2:
clear
clc
theSum=0;
player=1;
while (theSum < 10);
promptMessage = sprintf('The sum so far = %d\nPlayer #%d\nDo you want 1 or 2?', theSum, player);
titleBarCaption = 'Continue?';
button = questdlg(promptMessage, titleBarCaption, '1', '2', 'Quit', '1');
if strcmpi(button, '1')
count = 1;
elseif strcmpi(button, '2')
count = 2;
elseif strcmpi(button, 'Quit')
break;
end
fprintf('Player %d selected %d\n',player,count);
theSum=theSum+count;
% Break out if the count >= 10.
if theSum >= 10
break;
end
% Switch to the next player.
player = rem(player, 2) + 1;
end
if theSum >= 10
message = sprintf('Player %d wins!\n',player);
fprintf('%s\n', message);
uiwait(helpdlg(message));
end

Categorías

Más información sobre Just for fun en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by