shell+C实现猜数字游戏
在刚学shell的是候,使用它实现过猜数字游戏,今天把它贴到这里。然后我们沿这个最简单的小程序,继续进行更加深入的讨论。
#/bin/bash game.sh
############################################
# @brief play one time, user will give one
# number, compared with rank number.
# @param num the user given number.
# @param target the aim number.
# @return 0 sucess
# -1 failed
###########################################
game_play()
{
if [ $1 -gt $2 ]; then
echo “the number you entered is to bigger”
return -1
elif [ $1 -lt $2 ]; then
echo “the number you entered is to little”
return -1
fi
echo “congratulations, you get lotters”
return 0
}
#########################################
# game start
#########################################
main()
{
logic=-1
target=$RANDOM
target=$[target%100]
while ! [ $logic -eq 0 ]; do
read num
game_play $num $target
logic=$?
done
}
main
#########################################
# END
#########################################
如上的shell就编写了一个简单猜数字的游戏,现在我们近一步讨论。比如存在这样一种情况,就是用户如果不知道$RANDOM函数,但有C的对应实现,因此他想在shell里面调用这个模块又该如何实现呢?如果该用户又觉得game_play使用C实现对他来讲比较方便,又该如何取返回值呢?实际上,shell调用C同样使用$?取返回值,明白了这一点,所有问题就都解决了。下面我们就使shell+c来实现这个游戏。
//random.c
#include <stdlib.h>
int main(int argc, char **argv)
{
srand((unsigned int)(time(NULL)));
return rand() % 100;
}
//end random.c
////////////////////////////////////////////////////////////////////
//game_play.c
#include <stdio.h>
#include <stdio.h>
int main(int argc, char **argv)
{
int num = atoi(argv[1]);
int target = atoi(argv[2]);
if (num > target) {
printf(”the number you entered is to bigger”);
return -1;
}
else if (num < target) {
printf(”the number you entered is to little”);
return -1;
}
printf(”congratulations, you get lotters”);
return 0;
}
//end game_play.c
////////////////////////////////////////////////////////////////
下面我们要实现的shell也就简单了。
#!/bin/shell game.sh
#########################################
# game start
#########################################
main()
{
logic=-1
./random
target=$?
while ! [ $logic -eq 0 ]; do
read num
./game_play $num $target
logic=$?
done
}
main
#END game.sh
############################################
简单吧,和调shell一样。
现在动手试试吧:)
thx
张久安
If you enjoyed this post, make sure you subscribe to my RSS feed!









No Comments, Comment or Ping
Reply to “shell+C实现猜数字游戏”
You must be logged in to post a comment.