JavaScript, 實現貪喫蛇小遊戲

歡迎大家提出寶貴的意見和建議,歡迎批評指正!微笑


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>貪喫蛇</title>
<style type="text/css">
	div#gameBoard{ position:relative; width: 1000px; height: 500px; background: gray; margin: 0 auto;}
	div#gameControl{ width: 998px; height: 50px; line-height: 50px; border: 1px solid gray; margin: 0 auto;}
	
	div#gameControl span#banner{ float: left;}
	div#gameControl div#buttons{ float: right;}
	
	div.block{ width: 20px; height: 20px; float: left;}
	div.snake_block{ background-color: red; position: absolute; }
	div.food_block{ background-color: yellow; position: absolute; }
</style>
<script type="text/javascript">

	var SNAKE = {};//命名空間
	SNAKE.Config = {
		MAX_ROWS : 25,//定義面板的最大行數
		MAX_COLS : 50	//定義面板的最大列數
	};
	/**
		定義蛇類
	*/
	SNAKE.Snake = function (oBoard){
		
		this.snakeBody = [];//蛇身體
		this.isDead = false;//標識蛇是否死亡
		this.dir = 4;	//1:上 2:下 3:左 4:右
		this.isAlive = true;
		
		//	(20,40),(40, 40),(60, 40)
		for(var i = 3 ; i > 0 ; i--){
			//(20*i, 40)
			var oDivBlock = document.createElement("div");
			oDivBlock.className = "block snake_block";
			oDivBlock.style.left 	= 20*i + "px";
			oDivBlock.style.top 	= 40 + "px";
			oBoard.container.appendChild(oDivBlock);	
			this.snakeBody.push(oDivBlock);//將產生的每一個蛇的div block添加到蛇的身體數組中
			
		}
		this.snakeHead = this.snakeBody[0];
		
		this.moveOn = function(){
			var nextPos 	= {};
			nextPos.left 	= parseInt(this.snakeHead.style.left);
			nextPos.top 	= parseInt(this.snakeHead.style.top);
			//var snakeTail = this.snakeBody.pop();	
			switch(this.dir){
				case 1://↑
					nextPos.top 	-= 20;
					break;
				case 2:	//↓
					nextPos.top 	+= 20;
					break;
				case 3://←
					nextPos.left 	-= 20;
					break;
				case 4://→
					nextPos.left 	+= 20;
					break;
			}
			var oNewHead = document.createElement("div");
			oNewHead.className 	= "block snake_block";
			oNewHead.style.left = nextPos.left + "px";
			oNewHead.style.top 	= nextPos.top + "px";
			this.snakeBody.unshift(oNewHead);
			oBoard.container.appendChild(oNewHead);
			
			var snakeTail = this.snakeBody.pop();
			snakeTail.parentNode.removeChild(snakeTail);
			this.snakeHead =this.snakeBody[0];
			this.eat(oBoard.food);
					
		};//蛇遊走
		this.eat = function(food){
			var oFoodBlock = food.getFoodBlock();
			//alert("head"+this.snakeHead.style.left +",food"+ oFoodBlock.style.left)
			if(parseInt(this.snakeHead.style.left) == parseInt(oFoodBlock.style.left) && 
				parseInt(this.snakeHead.style.top) == parseInt(oFoodBlock.style.top)){
				//喫到食物
				this.increaseBody(oFoodBlock);
				oFoodBlock.parentNode.removeChild(oFoodBlock);
				food.locate();
			} else {
				//撞到自己的身體
				for(var i = 1 ; i < this.snakeBody.length ; i++){
					var oSnakeBlock = this.snakeBody[i];
					if( parseInt(this.snakeHead.style.left) == parseInt(oSnakeBlock.style.left) &&
						 parseInt(this.snakeHead.style.top) == parseInt(oSnakeBlock.style.top) ){
						alert("die");
						this.die();
						return;
					}
				}
				//撞牆
				if(parseInt(this.snakeHead.style.left) == -20 || parseInt(this.snakeHead.style.left) == 1000 ||
					parseInt(this.snakeHead.style.top) == -20 || parseInt(this.snakeHead.style.top) == 500){
					alert("die");
					this.die();
					return;
				}
			}
			
		};//蛇喫東西
		this.increaseBody = function(oFoodBlock){
			
			var oNewBlock = document.createElement("div");
			oNewBlock.style.left 	= oFoodBlock.style.left;
			oNewBlock.style.top 	= oFoodBlock.style.top;
			oNewBlock.className		= oFoodBlock.className;
			oBoard.container.appendChild(oNewBlock);
			this.snakeBody.push(oNewBlock);
			
		};//蛇喫到食物長身體 
		this.turnTo = function(dir){
			
			this.dir = dir;
			
		};//蛇改變方向
		this.die = function(){
			this.isAlive = false;
		}
		
	}
	
	/**
		定義食物類
	*/
	SNAKE.Food = function(oBoard){
		this.oFoodBlock ;
		
		this.locate = function(){
			var reLocate ;//表示是否需要重新定位
			this.oFoodBlock = document.createElement("div");
			this.oFoodBlock.className 	= "block food_block";
			do{
				var tempX	= Math.floor(Math.random() * 1000);
				var tempY	= Math.floor(Math.random() * 500);
				tempX = tempX - tempX%20;
				tempY = tempY - tempY%20;		
				
				this.oFoodBlock.style.left = tempX + "px";
				this.oFoodBlock.style.top 	= tempY + "px";
				oBoard.container.appendChild(this.oFoodBlock);
				reLocate = false;
				
				var snake = oBoard.snake;
				for(var i = 0 ; i < snake.snakeBody.length ; i++){
					var oSnakeBlockDiv = snake.snakeBody[i];
					if(( tempX == parseInt(oSnakeBlockDiv.style.left) ) && ( tempY == parseInt(oSnakeBlockDiv.style.top)) ){
					
						reLocate = true;
						break;
						
					}
				}
			}while(reLocate);
			
		
		};//得新定位食物
		//this.locate();
		this.getFoodBlock = function(){
			return this.oFoodBlock;
		}
	}
	
	/**
		定義面板類
	*/
	SNAKE.Board = function (){
		var oGameBoard = document.getElementById("gameBoard");
		
		//this.display = function(){};
		
		//畫面板
		for(var rows=0; rows<SNAKE.Config.MAX_ROWS; rows++){
			for(var cols=0; cols<SNAKE.Config.MAX_COLS; cols++){
				//創建div對象,並且給div添加樣式
				var oDiv = document.createElement("div");
				oDiv.className = "block";
				oGameBoard.appendChild(oDiv);
			}
		}
		
		this.container = oGameBoard;//定義一個容器屬性,代表當前Board對象擁有的容器Dom Div
		
		this.snake = new SNAKE.Snake(this);//面板中有一個小蛇對象
		this.food = new SNAKE.Food(this);//面板中有一個食物對象
		this.food.locate();
		
	}
	
	/**
		定義遊戲控制類
	*/
	SNAKE.Game = function(){
		
		this.board 	= null;
		this.snake 	= null;
		this.timer 	= null;
		this.pause	= true;

		this.init 	= function(){//遊戲初始化
			this.board = new SNAKE.Board();
			
			snake = this.board.snake;//得到蛇對象
			document.onkeydown = function(keyEvent){
		
				keyEvent = window.event;
				var keyNum = keyEvent.which || keyEvent.keyCode;
				switch(keyNum){		
					case 37://←
						if(snake.dir == 4) break;
						snake.turnTo(3);
						break;
					case 38:
						if(snake.dir == 2) break;
						snake.turnTo(1);
						break;
					case 39:
						if(snake.dir == 3) break;
						snake.turnTo(4);
						break;
					case 40:
						if(snake.dir == 1) break;
						snake.turnTo(2);
						break;
				}
		
			}

		};
		this.startGame = function (){
		
			this.timer = setInterval( function(){

				if(snake.isAlive){
					snake.moveOn();
				}else{
					this.stopGame();	
				}
			
			} , 300);
			
		};
		this.stopGame = function(){
			clearInterval(this.timer);
			alert("Game Over");
		};
		this.pauseGame = function(){
			if(!this.paused){
				clearInterval(this.timer);
				this.paused = true;
			}
			
		};
		this.resumeGame = function(){

			if(this.paused){
				this.startGame();
				this.paused = false;
			}
		};
		
	}
	
	window.onload = function(){
		//創建遊戲Game對象
		var game = new SNAKE.Game();
		game.init();//初始化遊戲
		
		var oBtnStart = document.getElementById("btnStart");
		oBtnStart.onclick = function(){
			if(this.value == "開始"){
				game.startGame();//開始遊戲
				this.value = "結束";
			} else {
				oBtnStart.value = "開始";
				this.stopGame();
			} 
		
		}	
		var oBtnPause = document.getElementById("btnPause");
		oBtnPause.onclick = function(){
			if(this.value == "暫停"){
				game.pauseGame(this);
				this.value = "恢復";
			} else {
				this.value = "暫停";
				game.resumeGame();//開始遊戲
			} 
			game.pauseGame(this);
		}
	};
	
</script>
</head>

<body>
	<div id="gameBoard">
    	
    </div>
    <div id="gameControl">
    	<span id="banner">JavaScript 貪喫蛇 By Zhang Bing</span>
        <div id="buttons">
        	<input type="button" value="開始" id="btnStart"/>
            <input type="button" value="暫停" id="btnPause"/>
        </div>
    </div>
</body>
</html>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章