这几天在学习Linux的Shell脚本,写了一个猜丁壳游戏。
游戏规则:每回合玩家和电脑各出石头、剪子、布中的一个,分别以0、1、2表示,规定石头可以胜过剪子、剪子可以胜过布、布可以胜过石头,如果玩家和电脑所出相同,则进入下一回合继续比试,否则游戏结束,本回合的胜者即为游戏的获胜方。
#!/bin/sh
# generate random numbers
function rand()
{
min=$1
max=$(($2-$min+1))
num=$(($RANDOM+10000))
echo $(($num%$max+$min))
}
result=0
echo "Game Start!"
while [ true ]; do
# Stone win Scissors
# Scissors win Cloth
# Cloth win Stone
echo "0-Stone, 1-Scissors, 2-Cloth, 3-GiveUp!"
read choice
rnd=$(rand 0 2)
case "$choice" in
0)if [ $rnd -eq 0 ]; then
echo "Stone vs Stone: Draw"
elif [ $rnd -eq 1 ]; then
echo "Stone vs Scissors: Win!"
result=1
else
echo "Stone vs Cloth: Defeat!"
result=-1
fi;;
1)if [ $rnd -eq 0 ]; then
echo "Scissors vs Stone: Defeat!"
result=-1
elif [ $rnd -eq 1 ]; then
echo "Scissors vs Scissors: Draw"
else
echo "Scissors vs Cloth: Win!"
result=1
fi;;
2)if [ $rnd -eq 0 ]; then
echo "Cloth vs Stone: Win!"
result=1
elif [ $rnd -eq 1 ]; then
echo "Cloth vs Scissors: Defeat!"
result=-1
else
echo "Cloth vs Cloth: Draw"
fi;;
3)result=-1;;
*)echo "bad choice";;
esac
# if draw then continue else break
if [ $result -eq 0 ]; then
continue
else
break
fi
done
echo "End of program"
echo " "
exit 0
运行结果