as3学习从头开始(二)-100行代码的贪吃蛇

100行代码的贪吃蛇

    贪吃蛇 

 

 

package
{
	import flash.display.Sprite;
	import flash.events.KeyboardEvent;
	import flash.geom.Point;
	import flash.utils.setInterval;
	
	[swf(frameRate=30, width=480, height=360)]
	public class Main extends Sprite
	{
		private var step:int=12;//步长
		private var mapWidth:int=40;//地图宽
		private var mapHeight:int=30;//地图高
		private var snake:Vector.<Point>;//蛇身
		private var change:Point;//运动方向
		private var food:Point;//食物
		public function Main()
		{
			newGame();//新游戏
			throwFood();//抛出食物
			stage.addEventListener(KeyboardEvent.KEY_DOWN,onDown);//键盘事件侦听
			drawSnake();//画蛇
			setInterval(go,100);//蛇自己的游动运动
			stage.color=0xCCCCCC;
		}
		private function go():void{//蛇游动
			addChange();
			drawSnake();
		}
		private function drawSnake():void{//画蛇
			this.graphics.clear();
			this.graphics.lineStyle(0.5,0x666666)
			this.graphics.beginFill(0x999999)
			for(var i:int=0;i<snake.length;i++){
				this.graphics.drawRect(snake[i].x*step,snake[i].y*step,step,step);
			}
			this.graphics.endFill();		
			drawfood();
		}
		private function throwFood():void{//抛出食物
			var p:Point=new Point(int(Math.random()*(mapWidth-5)+2),int(Math.random()*(mapHeight-5)+2));
			if(checkHit(p)){
				throwFood();
				return;
			}
			food=p;			
		}
		private function drawfood():void{//画食物
			this.graphics.beginFill(0x990000)
			this.graphics.drawRect(food.x*step,food.y*step,step,step);
			this.graphics.endFill();
		}
		private function checkHit(p:Point):Boolean{//检测碰撞
			for(var i:int=0;i<snake.length;i++){
				if(p.equals(snake[i]))return true;
			}
			return false;
		}
		private function onDown(e:KeyboardEvent):void{//键盘事件控制蛇的游动
			switch(e.keyCode){
				case 37:change=new Point(-1,0);
					break;
				case 38:change=new Point(0,-1);
					break;
				case 39:change=new Point(1,0);
					break;
				case 40:change=new Point(0,1);
					break;
			}
			addChange();
			drawSnake();
		}
		private function addChange():void{//蛇的变化
			if(change.x==0&&change.y==0)return;//蛇不动时,不处理
			var p:Point=new Point(snake[0].x+change.x,snake[0].y+change.y);
			if(checkHit(p)){//吃到自己的身体时,则重新开始游戏
				newGame();
			}
			else if(p.equals(food)){//吃到食物,身体加长
				snake.unshift(p);
				throwFood();
			}
			else if(p.x<0||p.y<0||p.x>mapWidth||p.y>mapHeight){
				newGame();
			}
			else{
				snake.unshift(p);
				snake.pop();
			}
		}
		private function newGame():void{//新游戏
			snake=new Vector.<Point>;
			change=new Point(0,0);
			snake.push(new Point(0,0));
			snake.push(new Point(0,1));
			snake.push(new Point(0,2));
			snake.push(new Point(0,3));
		}
	}
}

 

你可能感兴趣的:(as3)