Matlab Count to 10 game
조회 수: 1 (최근 30일)
이전 댓글 표시
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/151538/image.png)
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
Walter Roberson
2015년 11월 9일
Do not name a variable "sum" as that interferes with using the important MATLAB routine named "sum".
답변 (1개)
Image Analyst
2015년 11월 9일
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
댓글 수: 0
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!