Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

matlab coding Let\'s write a MATLAB script to play Rock-Paper-Scissors with comp

ID: 3701288 • Letter: M

Question

matlab coding

Let's write a MATLAB script to play Rock-Paper-Scissors with computer. The program should first ask the user to indicate his handshape with an integer number (1, 2, or 3) 1 Rock 2 Scissors 3 Paper Then computer generates a random integer number between 1 and 3. The rule of the game is: Rock beats Scissors, Scissors beats Paper, Paper beats Rock. . If the given input by the user is invalid, the message is "Invalid input! Please enter either 1, 2 or 3!" . For valid input by the user, the message is either: "You Lost! "You Won!", or "It is a Tie!"

Explanation / Answer

% infinite loop

while true

    fprintf('Select your handshape... ');

    fprintf('1. Rock ');

    fprintf('2. Paper ');

    fprintf('3. Scissor ');

    % get user input

    user = input('');

     % if user eneterd invalid input

    if user ~= 1 && user ~= 2 && user ~= 3

        fprintf('Invalid Input! Please enter either 1, 2 or 3! ');

    else

        

        break;

       

    end

   

end

   

% generate a random number from 1 to 3

computer = randi(3);

if user == 1

   

    if computer == 1

       

        fprintf('It is a Tie.');

       

    elseif computer == 2

       

        fprintf('You won!');

       

    else

       

        fprintf('You lost!');

       

    end

   

elseif user == 2

   

    if computer == 1

       

        fprintf('You lost!');

       

    elseif computer == 2

       

        fprintf('It is a Tie.');

        

    else

       

        fprintf('You won!');

       

    end

   

else

   

    if computer == 1

       

        fprintf('You won!');

       

    elseif computer == 2

       

        fprintf('You lost');

       

    else

       

        fprintf('It is a Tie.');

       

    end

   

end

Sample Output

Select your handshape...
1. Rock
2. Paper
3. Scissor
7
Invalid Input! Please enter either 1, 2 or 3!

Select your handshape...
1. Rock
2. Paper
3. Scissor
2
You won!