MapHeight=19
MapWidth=17
SnakeLength=3
SnakeX=(2 3 4)
SnakeY=(5 5 5)
MoveDirection="Right"
Food=(7 14)
Map=(1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 9
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 9
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 9
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 9
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 9
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 9
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 9
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 9
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 9
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 9
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 9
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 9
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 9
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 9
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 9
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 9
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 9)
Show()
{
#Map
for Cell in "${Map[@]}"
do
case ${Cell} in
-
printf " " ;;
-
printf "#" ;;
-
printf "\n" ;;
esac
done
#Snake
for ((i=0;i<${SnakeLength};i++))
do
tput cup ${SnakeY[i]} ${SnakeX[i]}
echo "*"
done
#Food
tput cup ${Food[0]} ${Food[1]}
echo "0"
tput cup 20 0
}
ArrayMove()
{
for i in $(seq 0 $((SnakeLength-2)))
do
SnakeX[i]=${SnakeX[i+1]}
SnakeY[i]=${SnakeY[i+1]}
done
}
FoodGenerate()
{
Food[1]=(({RANDOM}%${MapHeight}))
Food[0]=(({RANDOM}%${MapWidth}))
}
Move()
{
read -n 1 -t 0.2 input
case $input in
"s") MoveDirection="Down" ;;
"w") MoveDirection="Up" ;;
"a") MoveDirection="Left" ;;
"d") MoveDirection="Right" ;;
esac
ArrayMove
if [ "$MoveDirection" = "Right" ]; then
((++SnakeX[$((SnakeLength-1))]))
elif [ "$MoveDirection" = "Left" ]; then
((--SnakeX[$((SnakeLength-1))]))
elif [ "$MoveDirection" = "Up" ]; then
((--SnakeY[$((SnakeLength-1))]))
elif [ "$MoveDirection" = "Down" ]; then
((++SnakeY[$((SnakeLength-1))]))
fi
if [ {SnakeX\[((SnakeLength-1))]} -eq ${Food[1]} -a {SnakeY\[((SnakeLength-1))]} -eq ${Food[0]} ]; then
SnakeX[{SnakeLength}\]={SnakeX[$((SnakeLength-1))]}
SnakeY[{SnakeLength}\]={SnakeY[$((SnakeLength-1))]}
if [ "$MoveDirection" = "Down" ]; then
SnakeY[{SnakeLength}\]={SnakeY[$((SnakeLength-1))]}+1
elif [ "$MoveDirection" = "Up" ]; then
SnakeY[{SnakeLength}\]={SnakeY[$((SnakeLength-1))]}-1
elif [ "$MoveDirection" = "Right" ]; then
SnakeX[{SnakeLength}\]={SnakeX[$((SnakeLength-1))]}+1
elif [ "$MoveDirection" = "Left" ]; then
SnakeX[{SnakeLength}\]={SnakeX[$((SnakeLength-1))]}-1
fi
((++SnakeLength))
FoodGenerate
fi
}
Main()
{
while true
do
clear
echo "w:up s:down a:left d:right"
Show
Move
sleep 0.2
done
}
Main