Script Realization Man-machine < stone, scissors, cloth > Game, Machine Application random method, combined with user input to give the result, the article has two methods, the first method is the logical aspect of the script, the second is easier to understand.
One: The first method, let the machine give a random number 0-2, we can assume that there is an array for the game (stone scissors cloth), game[0]= stone game[1]= scissors game[2]= cloth, we will Num's variable to be game[num], array inside bit. In combination with the case statement, we give the user the impression that when the input 1 is a stone, then the game "0" for the stone, directly inside the case statement to make judgments. give the corresponding result.
If it's hard to understand, you can turn num into nmu=$[random%3+1], so we can see the shell as a tiger chicken. Or compare the numbers, of course, the effect here and the stone scissors cloth effect is the same.
Here's the code:
#!/bin/bash
NUM=$[RANDOM%3]
echo "Please select your punch gesture according to the following tips"
echo "1 stone"
echo "2 Scissors"
echo "3 cloth"
Read-p "Please select 1-3" person
Case $person in
1)
If [$num-eq 0];then
echo "Draw"
elif [$num-eq 1];then
Echo, "You won."
Else
Echo, "you lost."
fi;;
2)
If [$num-eq 1];then
echo "Draw"
elif [$num-eq 2];then
Echo, "You won."
Else
Echo, "you lost."
fi;;
3)
If [$num-eq 2];then
echo "Draw"
elif [$num-eq 3];then
Echo, "You won."
Else
Echo, "you lost."
fi;;
*)
echo "Please enter"
Esac
Two: The second method, the definition of two variables, one is the machine out of the definition of Y, the user's definition for x, and then make three judgments, the following is the code:
#!/bin/bash
NUM=$[RANDOM%3+1]
Case $num in
1)
Y= "stone";;
2)
Y= "scissors";;
3)
y= "cloth";;
Esac
Read-p "Please input stone, scissors, Cloth:" X
echo "The machine is out: $y"
echo "You're out: $x"
if [$x = = $y];then
echo "Tie"
elif [[$x = = "Stone" && $y = = "Scissors"] | |
[$x = = "Scissors" && $y = = "Cloth"] | |
[$x = = "Cloth" && $y = = "Stone"]];then
Echo, "You won."
Else
Echo, "you lost."
Fi
There must be different ways to write a shell on demand, and there are better ways to share it with a private blogger, or in a comment area. Thank you.
(Stone, scissors, cloth) shell scripts, random comparisons, case applications