为什么80%的码农都做不了架构师?>>> 一个用Shell脚本写的猜丁壳游戏-编程知识网

这几天在学习Linux的Shell脚本,写了一个猜丁壳游戏

游戏规则:每回合玩家和电脑各出石头、剪子、布中的一个,分别以0、1、2表示,规定石头可以胜过剪子、剪子可以胜过布、布可以胜过石头,如果玩家和电脑所出相同,则进入下一回合继续比试,否则游戏结束,本回合的胜者即为游戏的获胜方。

#!/bin/sh# generate random numbers
function rand()
{min=$1max=$(($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 Stoneecho "0-Stone, 1-Scissors, 2-Cloth, 3-GiveUp!"read choicernd=$(rand 0 2)case "$choice" in0)if [ $rnd -eq 0 ]; thenecho "Stone vs Stone: Draw"elif [ $rnd -eq 1 ]; thenecho "Stone vs Scissors: Win!"result=1elseecho "Stone vs Cloth: Defeat!"result=-1fi;;1)if [ $rnd -eq 0 ]; thenecho "Scissors vs Stone: Defeat!"result=-1elif [ $rnd -eq 1 ]; thenecho "Scissors vs Scissors: Draw"elseecho "Scissors vs Cloth: Win!"result=1fi;;2)if [ $rnd -eq 0 ]; thenecho "Cloth vs Stone: Win!"result=1elif [ $rnd -eq 1 ]; thenecho "Cloth vs Scissors: Defeat!"result=-1elseecho "Cloth vs Cloth: Draw"fi;;3)result=-1;;*)echo "bad choice";;esac# if draw then continue else breakif [ $result -eq 0 ]; thencontinue elsebreak    fidoneecho "End of program"
echo " "exit 0

运行结果

一个用Shell脚本写的猜丁壳游戏-编程知识网

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