您的位置:首页 > 运维架构 > Shell

shell实现猜数字小游戏

2020-04-22 18:15 260 查看

本文实例为大家分享了shell实现猜数字游戏的具体代码,供大家参考,具体内容如下

#!/bin/bash
# 猜数字编程游戏
# 系统随机生成一个数字,给这个数字定一个范围(1-60),让用户输入猜的数字,对输入进行判断,如果不符合要求,就给予高或低的提示。其他要求:
# 全部猜对后则给出猜对使用用的总次数。
# 根据猜的历史给出击败了百分之多少的已经猜过的用户。
# 并把关键的内容(高低以及数字部分)以特殊颜色提示用户。

# 生成一个1到60之间的随机数
number_range=$((RANDOM%60))

login(){
read -p '请输入游戏昵称: ' name
if [ -z "$name" ];then
echo -e "\033[1;31m 昵称不允许为空 \033[0m"
exit 1
fi
}

# 检查输入是否合法,含有非数字、为空、大于60小于1都属于非法行为
check_number(){
if [ -z "$number" -o $(echo "$number"|egrep -o '[^0-9]'|wc -l) -gt 1 ];then
echo -e "\033[1;31m 请不要输入非数字字符 \033[0m"
continue
elif [ -z "$number" ];then
echo -e "\033[1;32m 请不要输入空字符 \033[0m"
else
if [ "$number" -lt 1 -o "$number" -gt 60 ];then
echo -e "\033[1;31m 请输入一个1到60之间的数字 \033[0m"
continue
fi
fi
}

# 提示输入和正确答案大小比对
prompt(){
if [ "$number" -lt "$number_range" ];then
echo -e "\033[1;34m 你猜的数字太小了 \033[0m"
elif [ "$number" -gt "$number_range" ];then
echo -e "\033[1;35m 你猜的数字太大了 \033[0m"
elif [ "$number" -eq "$number_range" ];then
echo -e "\033[1;36m 恭喜你猜对了 \033[0m"
echo -e "\033[1;31m 一共使用了$count次机会 \033[0m"
echo "$name $count" >> Game_history
check_beat
fi
}

# 判断击败了多少历史玩家
check_beat(){
beat_count=0
for history in $(awk '{print $2}' Game_history)
do
total=$(expr $(cat Game_history|wc -l) - 1)
if [ "$total" -eq 0 ];then
echo -e "\033[1;32m 您是本游戏的第一位用户哦 \033[0m"
exit 1
else
if [ "$count" -lt "$history" ];then
let beat_count++
fi
fi
done
echo |awk -v beat_count=$beat_count -v total=$total '{printf "您一共击败了%.2f%%的历史玩家\n",beat_count/total*100}'
exit 1
}

# 主菜单
menu(){
login
count=0
while :
do
read -p '请输入一个1到60之间的数字: ' number
let count++
check_number
prompt
done
}
menu

小编再为大家分享一段:shell实现猜数字游戏的代码

#/*********************************
#  > File Name: guessgame.sh
#  > Author: liyong
#  > Mail: 2550702985@qq.com
#  > Created Time: 2017-03-22 01:57
#  > Last modified: 2017-03-22 01:57
randNum=$(date +%s%N)
let luckNum=${randNum:0-1:1}
echo $luckNum
let num=luckNum+1
while [ $luckNum -ne $num ];do
read -p'Please input a num: ' num
#expr 当num为0结果非0,故不能作为数字判断的标准
# expr $num + 0 &> /dev/null ||{ echo '请输入数字';exit 2; }
echo $num |grep -E '^[[:digit:]]+$' &> /dev/null ||{ echo '请输入数字
';exit 2;}
if [ $luckNum -eq $num ];then
echo 'Congratulates';
exit;
elif [ $luckNum -gt $num ];then
echo 'The num you input is smaller'
else
echo 'The num you input is bigger'
fi
done

以上就是本文的全部内容,希望对大家的学习有所帮助

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  shell 猜数字