How can I play many rounds in Rock, Paper and Scissors game?

조회 수: 1 (최근 30일)
Jaime Vera
Jaime Vera 2017년 12월 2일
답변: Image Analyst 2017년 12월 2일
Hi,
I have a script to simulate this classic game. The question is: How can I play many rounds? I was thinking that was using for loop, but I could not find the correct way to accomplish that.
Here the script without repetition:
disp('Stone, Paper and Scissors')
disp('Stone (1)')
disp('Paper (2)')
disp('Scissors (3)')
n=input('Which choice?: ')
pc=[1,2,3];
switch(n)
case 1
MATChoice=datasample(pc,1)
if c1==1
return
end
if MATChoice==2
display('MATLAB win; Player LOSE')
return
end
if MATChoice==3
display('MATLAB lose; Player WIN')
return
end
case 2
MATChoice=datasample(pc,1)
if MATChoice==1
disp('MATLAB lose; Player WIN')
return
end
if MATChoice==2
return
end
if MATChoice==3
disp('MATLAB win; Player LOSE')
return
end
case 3
MATChoice=datasample(pc,1)
if MATChoice==1
disp('MATLAB win; Player LOSE')
return
end
if MATChoice==2
disp('MATLAB lose; Player WIN')
return
end
if MATChoice==3
return
end
otherwise
error('Choose 1,2 or 3')
return
end
return
end
Could you help me, please?
Thank you.

채택된 답변

Image Analyst
Image Analyst 2017년 12월 2일
Try this:
numberOfTrials = 30; % Whatever you want...
for k = 1 : numberOfTrials
choices = {'Rock', 'Paper', 'Scissors', 'Quit'};
userChoice = menu('Which choice?: ', choices)
if userChoice == 4
break;
end
computerChoice =randi([1,3])
message = sprintf('You chose %s and computer chose %s', ...
choices{userChoice}, choices{computerChoice})
switch userChoice
case 1
switch computerChoice
case 1
message = sprintf('%s\nTie', message);
case 2
message = sprintf('%s\nComputer wins.', message);
case 3
message = sprintf('%s\nYou win', message);
end
case 2
switch computerChoice
case 1
message = sprintf('%s\nYou win!', message);
case 2
message = sprintf('%s\nTie', message);
case 3
message = sprintf('%s\nComputer wins', message);
end
case 3
switch computerChoice
case 1
message = sprintf('%s\nComputer wins.', message);
case 2
message = sprintf('%s\nYou win!', message);
case 3
message = sprintf('%s\nTie', message);
end
case 4
break;
end
uiwait(helpdlg(message));
end

추가 답변 (1개)

Image Analyst
Image Analyst 2017년 12월 2일
Use a for loop
numberOfTrials = 15; % Whatever you want...
for k = 1 numberOfTrials
% your existing code.....
end
  댓글 수: 1
Jaime Vera
Jaime Vera 2017년 12월 2일
I thought that too, but when I do that, the script does not ask me again, after one round, about the n option: 1, 2 or 3.
Do you know why is this happening?
Thank you.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Just for fun에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by