一个用Shell脚本写的猜丁壳游戏

这几天在学习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

运行结果

213528_YmzX_1425762.png

转载于:https://my.oschina.net/Tsybius2014/blog/284898

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值