一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

shell如何实现猜数字小游戏 shell实现猜数字小游戏代码

时间:2020-04-21 编辑:袖梨 来源:一聚教程网

shell如何实现猜数字小游戏?本篇文章小编给大家分享一下shell实现猜数字小游戏代码,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

代码如下

#!/bin/bash
# 猜数字编程游戏
# 系统随机生成一个数字,给这个数字定一个范围(1-60),让用户输入猜的数字,对输入进行判断,如果不符合要求,就给予高或低的提示。其他要求:
# 全部猜对后则给出猜对使用用的总次数。
# 根据猜的历史给出击败了百分之多少的已经猜过的用户。
# 并把关键的内容(高低以及数字部分)以特殊颜色提示用户。
 
 
# 生成一个1到60之间的随机数
number_range=$((RANDOM%60))
 
login(){
  read -p '请输入游戏昵称: ' name
  if [ -z "$name" ];then
    echo -e "33[1;31m 昵称不允许为空 33[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 "33[1;31m 请不要输入非数字字符 33[0m"
    continue
  elif [ -z "$number" ];then
    echo -e "33[1;32m 请不要输入空字符 33[0m"
  else
    if [ "$number" -lt 1 -o "$number" -gt 60 ];then
      echo -e "33[1;31m 请输入一个1到60之间的数字 33[0m"
      continue
    fi
  fi
}
 
# 提示输入和正确答案大小比对
prompt(){
  if [ "$number" -lt "$number_range" ];then
    echo -e "33[1;34m 你猜的数字太小了 33[0m"
  elif [ "$number" -gt "$number_range" ];then
    echo -e "33[1;35m 你猜的数字太大了 33[0m"
  elif [ "$number" -eq "$number_range" ];then
    echo -e "33[1;36m 恭喜你猜对了 33[0m"
    echo -e "33[1;31m 一共使用了$count次机会 33[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 "33[1;32m 您是本游戏的第一位用户哦 33[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

热门栏目