功能簡單的吞喫蛇(shell編程)

 天老師叫我們做了個吞喫蛇,只實現了很簡單的功能,不廢話,上馬:

 

 

#!/bin/bash

trap input_key=0 20
trap input_key=1 21
trap input_key=2 22
trap input_key=3 23
trap input_key=4 24
high=15#界面長
width=50#界面寬
top=5#起始縱座標
left=5#起始橫座標
for((i=0;i<high+2;i++))
do
for((j=0;j<width+2;j++))
do
((temp=i*(width+2)+j))
if((i==0 || j==0 || i==high+1 || j==width+1))
then
imap[$temp]=-1
else
imap[$temp]=0
fi
done
done
#畫界面
drawbk()
{
for((i=0;i<high+2;i++))
do
for((j=0;j<width+2;j++))
do
((y=i+top))
((x=j+left))
((temp=i*(width+2)+j))
if((imap[temp]==-1))
then
echo -ne "/33[$y;${x}H/33[35;42m#"
fi
done
done
}
cur_y=0#蛇的縱座標
cur_x=0#蛇的橫座標
to_y=0#蛋的縱座標
to_x=0#蛋的橫座標
 
#隨機蛇的座標值
random_cur()
{
cur_y=$RANDOM
((cur_y=cur_y%high+1+top))
cur_x=$RANDOM
((cur_x=cur_x%width+1+left))
}
 
#隨機蛋的座標
random_to()
{
to_y=$RANDOM
((to_y=to_y%high+1+top))
to_x=$RANDOM
((to_x=to_x%width+1+top))
}
 
draw_cur()
{
echo -ne "/33[$cur_y;${cur_x}H/33[33;46m@"
}
draw_to()
{
echo -ne "/33[$to_y;${to_x}H/33[33;46m0"
}
 
#起始界面
init_set()
{
random_cur
random_to
drawbk
echo -ne "/33[$cur_y;${cur_x}H/33[33;46m@"
echo -ne "/33[$to_y;${to_x}H/33[33;46m0"
}
 
#按向上鍵‘w’
input_up()
{
temp=$cur_y
((cur_y--))
echo -ne "/33[$temp;${cur_x}H/33[0m "
echo -ne "/33[$cur_y;${cur_x}H/33[33;46m@"
}
 
#按向下鍵‘s’
input_down()
{
temp=$cur_y
((cur_y++))
echo -ne "/33[$temp;${cur_x}H/33[0m "
echo -ne "/33[$cur_y;${cur_x}H/33[33;46m@"
}
 
#按向左鍵‘a’
input_left()
{
temp=$cur_x
((cur_x--))
echo -ne "/33[$cur_y;${temp}H/33[0m "
echo -ne "/33[$cur_y;${cur_x}H/33[33;46m@"
}
 
#按向右鍵‘d’
input_right()
{
temp=$cur_x
((cur_x++))
echo -ne "/33[$cur_y;${temp}H/33[0m "
echo -ne "/33[$cur_y;${cur_x}H/33[33;46m@"
}
 
input_key=0#輸入的鍵值0  1  2  3分別爲上下左右
over_key=0#遊戲是否結束  0則結束
 
#判斷遊戲是否結束
is_gameover()
{
case $input_key in
0)
if((cur_y-1==top))
then
over_key=1
fi
;;
1)
if((cur_y==top+high))
then
over_key=1
fi
;;
2)
if((cur_x-1==left))
then
over_key=1
fi
;;
3)
if((cur_x==left+width))
then
over_key=1
fi
;;
esac
}
 
tosid=0
 
#運行遊戲
run_game()
{
init_set
while :
do
is_gameover
if((over_key!=0))
then
echo -ne "/33[$((top-1));${left}Hgameover!!"
echo -ne "/33[0m"
kill -9 $tosid &> /dev/tty2
exit
fi
case $input_key in
0)
input_up ;;
1)
input_down ;;
2)
input_left ;;
3) 
input_right ;;
4)
exit ;;
esac
usleep 500000
if((cur_x==to_x && cur_y==to_y))
then
random_to
draw_to
fi
done
}
 
#接收輸入
input()
{
while :
do
read -s -n 1 var
case $var in
'w')
kill -20 $1 ;;
's')
kill -21 $1 ;;
'a')
kill -22 $1 ;;
'd')
kill -23 $1 ;;
'q')
kill -9 $1 ;;
esac
done
}
 
#開始運行
if [ "$1" != "--show" ]
then
sh $0 --show $ & #另運行本程序到後臺
input $!#發送消息
else
tosid=$2
run_game 
fi
 
 
 
 以後寫註釋
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章