[Shell]贪吃蛇

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
			0) printf " "  ;;
			1) printf "#"  ;;
			9) 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

这个游戏还有些BUG没修复:

比如蛇撞到边界,

蛇自己撞自己等等,

但是可以供学习参考,

运行效果图:

[Shell]贪吃蛇_第1张图片

 

你可能感兴趣的:(IT相关,php,开发语言)