【SHELL】贪吃蛇

declare -i snake_length #-i将变量声明为整型

snake_x=(10 11 12)
snake_y=(5 5 5)
snake_length=3
move_direction="right"
food=(7 14) #y, x
MapHeight=16
MapWidth=19
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)

main()
{
	while true
	do 
		clear
		echo "== w:向上 s:向下 a:向左 d:向右 =="
		show
		move
		sleep 1
	done
}

show() 
{
	for data in "${Map[@]}";  #显示所有的元素
	do
		case $data in
			[0]) printf " ";; #空白			
			[1]) printf "■";; #墙
			[9]) printf "\n";; #墙
		esac
	done		

	for ((i=0;i<${snake_length};i++))
	do
		tput cup ${snake_y[i]} ${snake_x[i]}  
		echo "☆"
	done

	tput cup ${food[0]} ${food[1]}
	echo "◎"

	tput cup 20 0 #y, x
}

function ArrayMove()
{
	for i in $(seq 0 $((snake_length-2))) 
	do
		echo "i: $i"
		snake_y[i]=${snake_y[i+1]}
		snake_x[i]=${snake_x[i+1]}  
	done
}

function FoodGenerate()
{
	echo "Food Generate!"
	food[1]=$((${RANDOM} % ${MapHeight}))
	food[0]=$((${RANDOM} % ${MapWidth}))
}

function move()
{
	
	read -n 1 -t 0.5 input
	case $input in
		"w")
			move_direction="up" #echo "up"
			;;

		"a")
			move_direction="left"  #echo "left"			
			;;

		"d")
			move_direction="right"  #echo "right"			
			;;	

		"s")
			move_direction="down" #echo "down"			
			;;	
	esac

	ArrayMove
	if [ "$move_direction" = "right" ]; then
		((snake_x[$((snake_length-1))]=snake_x[$((snake_length-1))]+1))
	elif [ "$move_direction" = "down" ]; then	 	
		((snake_y[$((snake_length-1))]=snake_y[$((snake_length-1))]+1))
	elif [ "$move_direction" = "up" ]; then	 	
		((snake_y[$((snake_length-1))]=snake_y[$((snake_length-1))]-1))
	elif [ "$move_direction" = "left" ]; then	 	
		((snake_x[$((snake_length-1))]=snake_x[$((snake_length-1))]-1))
	fi

	if [ ${snake_y[$((snake_length-1))]} -eq ${food[0]} -a ${snake_x[$((snake_length-1))]} -eq ${food[1]} ]; then
		 if [ "$move_direction" = "down" ]; then
			snake_x[${snake_length}]=${snake_x[$((snake_length-1))]}
			snake_y[${snake_length}]=${snake_y[$((snake_length-1))]}+1
		 fi
		((++snake_length)) 
		 echo "food eated..snake_length: ${snake_length}"
		FoodGenerate
	fi

	echo "${snake_y[2]} : ${food[1]} : ${snake_x[2]} : ${food[0]}"
}

main

你可能感兴趣的:(linux)