当前位置: 移动技术网 > 网络运营>服务器>Linux > linux实现猜数字小游戏源码

linux实现猜数字小游戏源码

2020年05月12日  | 移动技术网网络运营  | 我要评论

一个简单的linux猜数字小游戏源码

游戏规则:

猜数字游戏通常由两个人玩,一方出数字,一方猜。出数字的人要想好一个没有重复数字的 4 个数,不能让猜的人知道。猜的人就可以开始猜。每猜一个数字,出数者就要根据这个数字给出几 a 几 b,其中 a 前面的数字表示位置正确的数的个数,而 b 前的数字表示数字正确而位置不对的数的个数。如正确答案为 5234,而猜的人猜 5346,则是 1a2b,其中有一个 5 的位置对了,记为 1a,而 3 和 4 这两个数字对了,而位置没对,因此记为 2b,合起来就是 1a2b。接着猜的人再根据出题者的几 a 几 b 继续猜,直到猜中(即 4a0b)为止。

猜的人有 8 次机会。

例如:

乙出一个数字,甲猜。
甲 乙
1234 1a0b
5678 2a1b
5674 1a1b
5638 1a1b
2678 2a2b
6278 4a0b(猜中)

源码:

#!/bin/bash
clear
echo
echo "###################################################################"
echo "# this is a bash-shell game write by lee       #"
echo "# this game is infinite frequency 猜数字       #"
echo "#    version 2.1.1.20200421        #"
echo "###################################################################"
echo -e "\n\n"
declare input
declare password
declare len_pwd
declare a
declare b
declare loop

#this function is create random number
random_number()
{
 password=$random
 len_pwd=`echo $password | wc -l`
 if [[ $len_pwd -ne 4 ]]
 then
 random_number
 else
 #输出标准值,测试需要,开发完成注释掉
 echo $password
 input
 fi
}

#this function is accept the input from user's keyboard
input()
{
 read -n4 -p "please input a number between 0000-9999:" input
# 10#${input} 进制转换
 if [[ 10#${input} -eq 10#${password} ]]
 then
 echo -e "\n"
 echo "#############################################"
 echo "#congratulations!you have tried $loop times!#"
 echo "# the password is $password !   #"
 echo "#############################################"
 exit
 elif [[ $loop -eq 6 ]]
 then
 echo -e "\n"
 echo "you have tried $loop times!game over!"
 exit
 else
 a=0
 b=0
 count_a
 count_b
 echo -e "\n"
 echo "****************************"
  echo "*  "$a"a"$b"b   *"
  echo "****************************"
 echo "you have tried $loop times! you left `expr 6 - $loop` times!"
 loop=`expr $loop + 1`
 input
 fi
}

#this function is count the variable a's value
count_a()
{
 for i in `seq 4`
 do
 var_input=`expr substr $input $i 1`
 for j in `seq 4`
 do
 var_password=`expr substr $password $j 1`
 if [[ $var_input -eq $var_password ]] && [[ $i -eq $j ]]
 then a=`expr $a + 1`
 fi
 done
 done
}

#this function is count the variable b's value
count_b()
{
 for i in `seq 4`
 do
 var_input=`expr substr $input $i 1`
 for j in `seq 4`
 do
 var_password=`expr substr $password $j 1`
 if [[ $var_input -eq $var_password ]] && [[ $i -ne $j ]]
 then b=`expr $b + 1`
 fi
 done
 done
}

loop=1
random_number

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网