分類  >  Web前端 >

div偏移量統制,貪吃蛇遊戲實現

tags:    時間:2013-12-10 00:08:17
div偏移量控制,貪吃蛇遊戲實現

兼容IE10 FIREFOX CHROME 效果見下圖

tcs.html

<html> <meta http-equiv="Content-Type" content="text/html; charset=GB2312" /> <head>   <title>貪吃蛇</title>   <style> 		    .desktop{       background-color:gray; 	  border:1px solid green;       width:500px;	         height:500px;    }    .textbox{ 		width:500px;	   		height:500px; 		top:8px; 		left:550px; 		position:absolute;    }    .msgbox{ 		top:258px; 		left:200px; 		color:red; 		text-align:center;height:10px;line-height:10px; 		position:absolute;     }     .bd{ 	width:10px;     height:10px; 	text-align:center;height:10px;line-height:10px; 	border:1px solid gray;     position:absolute;    }        .snake{ 		background-color:yellow;    }        .food{ 		background-color:red;    }            </style> <script src="tcs.js"></script> </head>   <body>  <div id="desktop" class="desktop"></div> <div id="textbox" class="textbox">		 	得分:<input id="score" type="text" value="0" readonly="true"></input> 	<BR/>坐標:<textarea id="vertex" cols="70" rows="5"></textarea> </div> <div id="msg" class="msgbox"></div> <br/><br/> <input id="startbtn" type="button" value="start"/>  </body> </html>

 tcs.js

//全局參數 var snakeTrain = [],//蛇身  allFood=[],//食物倉庫  block,//自動行走定時器  direction=39,//默認方向  desktop ={top:0,left:0},//桌布  foodBox = {x:0,y:0},//食物BOX  nextRandFoodIndex=0,//下一個食物隨機點索引  score=0,//得分  gameStatus = 0;//遊戲狀態 0未啟動 1運行中 -1遊戲結束   //初始化方法 window.onload = function(e){  desktop.top = getTop($("desktop"));  desktop.left = getLeft($("desktop"));  initallFood();  initKeyDownListener();    $("startbtn").onclick = function(){   gameStatus = 1;   initSnake();   initFood();   block = window.setInterval("startTrain()",500);    };     } //根據id獲得dom對象 function $(id){    return document.getElementById(id); } //隨機產生一個界於min和max之間的整數 function getRandomNum(Min,Max) {    var Range = Max - Min;    var Rand = Math.random();    return(Min + Math.round(Rand * Range));    }    //獲得dom對象的top function getTop(e){       var offset=e.offsetTop;       if(e.offsetParent!=null) offset+=getTop(e.offsetParent);       return offset;   }   //獲得dom對象的left function getLeft(e){       var offset=e.offsetLeft;       if(e.offsetParent!=null) offset+=getLeft(e.offsetParent);       return offset;   }   //初始化食物池 function initallFood(){  for(var i=0;i<50;i++){   for(var j=0;j<50;j++){      allFood.push({x:i*10,y:j*10});   }  }  var len = allFood.length;  for(var i=0;i<len*2;i++){   var n1 = getRandomNum(0,len-1);   var n2 = getRandomNum(0,len-1);   var tmp = allFood[n1];   allFood[n1] = allFood[n2];   allFood[n2] = tmp;  } } //初始化食物 function initFood(addScore){  var len = allFood.length;  if (nextRandFoodIndex == len-1){   nextRandFoodIndex = 0;  }  for(var i=nextRandFoodIndex++;i<len;i++){    if (!inSnakeTrain(allFood[i].x, allFood[i].y)){      createBox(allFood[i].x, allFood[i].y, "food");   foodBox = {x:allFood[i].x , y:allFood[i].y};   break;    }  }  if (addScore){   score += 10;   $("score").value = score;  } } //初始化蛇 function initSnake(){  var n = 3;  for(var i=0;i<n;i++){   createBox(10*i,0,"snake");     snakeTrain.push({x:10*i,y:0});  }  drawHead(); }
//初始化鍵盤監聽事件 function initKeyDownListener(){  document.onkeydown = function(e){   if (gameStatus != 1){    return -1;   }   var code = e.keyCode;   if (code<37 || code>40){    return -1;   }   startTrain(code);  } } //上下左右手動行走 function leftGo(){  if (direction == 39){//朝右走,不能左轉   return -1;  }  if (outside("x-")){   gameOver("撞牆啦!Game Over");   return -1;  }  if (eatSelf("x-")){   gameOver("咬到自己啦!Game Over");   return -1;  }  var len = snakeTrain.length;  var snake = snakeTrain[len-1];  if (foodBox.x == snake.x-10 && foodBox.y == snake.y){//eatting   removeBox(foodBox.x,foodBox.y,"food");   createBox(foodBox.x,foodBox.y,"snake");   snakeTrain.push({x:foodBox.x , y:foodBox.y});   initFood(true);  }else{   trainGo();   snake.x -= 10;   drawSnakeTrain();   }  } function upGo(){  if (direction == 40){//朝下走,不能北上   return -1;  }  if (outside("y-")){   gameOver("撞牆啦!Game Over");   return -1;  }  if (eatSelf("y-")){   gameOver("咬到自己啦!Game Over");   return -1;  }  var len = snakeTrain.length;  var snake = snakeTrain[len-1];  if (foodBox.x == snake.x && foodBox.y == snake.y-10){//eatting   removeBox(foodBox.x,foodBox.y,"food");   createBox(foodBox.x,foodBox.y,"snake");   snakeTrain.push({x:foodBox.x , y:foodBox.y});   initFood(true);  }else{   trainGo();   snake.y -= 10;   drawSnakeTrain();  }   } function rightGo(){  if (direction == 37){//朝左走,不能右轉   return -1;  }  if (outside("x+")){   gameOver("撞牆啦!Game Over");   return -1;  }  if (eatSelf("x+")){   gameOver("咬到自己啦!Game Over");   return -1;  }  var len = snakeTrain.length;  var snake = snakeTrain[len-1];  if (foodBox.x == snake.x+10 && foodBox.y == snake.y){//eatting   removeBox(foodBox.x,foodBox.y,"food");   createBox(foodBox.x,foodBox.y,"snake");   snakeTrain.push({x:foodBox.x , y:foodBox.y});   initFood(true);  }else{   trainGo();   snake.x += 10;   drawSnakeTrain();  }   } function downGo(){  if (direction == 38){//朝上走,不能南下   return -1;  }  if (outside("y+")){   gameOver("撞牆啦!Game Over");   return -1;  }  if (eatSelf("y+")){   gameOver("咬到自己啦!Game Over");   return -1;  }  var len = snakeTrain.length;  var snake = snakeTrain[len-1];  if (foodBox.x == snake.x && foodBox.y == snake.y+10){//eatting   removeBox(foodBox.x,foodBox.y,"food");   createBox(foodBox.x,foodBox.y,"snake");   snakeTrain.push({x:foodBox.x , y:foodBox.y});   initFood(true);  }else{   trainGo();   snake.y += 10;   drawSnakeTrain();  } } //蛇身跟上蛇頭 function trainGo(){  var len = snakeTrain.length;  var i = len-1;  var tmp = snakeTrain[i];  while(i>=1){   removeBox(tmp.x,tmp.y,"snake");   var tmp2 = {'x':snakeTrain[i-1].x , 'y':snakeTrain[i-1].y};   snakeTrain[i-1].x = tmp.x;   snakeTrain[i-1].y = tmp.y;   tmp = tmp2;     i--;  }  removeBox(tmp.x,tmp.y,"snake"); }
//畫蛇 function drawSnakeTrain(){  var len = snakeTrain.length;  var str = "";  for(var i=0;i<len;i++){   var snake = snakeTrain[i];   createBox(snake.x,snake.y,"snake");   str += " {x:"+snake.x+",y:"+snake.y+"}";  }  $("vertex").value = str; }
//裝飾蛇頭 function drawHead(){  var snake = snakeTrain[snakeTrain.length-1];  var snake2 = snakeTrain[snakeTrain.length-2];  $("snake_"+snake.x+"_"+snake.y).style.backgroundColor = "orange";  $("snake_"+snake2.x+"_"+snake2.y).style.backgroundColor = "yellow"; }
//是否出界 function outside(act){  var snake = snakeTrain[snakeTrain.length-1];  switch(act){   case "x+":    return snake.x + 10 > 490;   case "x-":    return snake.x - 10 < 0;   case "y+":    return snake.y + 10 > 490;   case "y-":    return snake.y - 10 < 0;  } }
//是否咬到自己 function eatSelf(act){  var snake = snakeTrain[snakeTrain.length-1];  switch(act){   case "x+":    return inSnakeTrain(snake.x + 10 , snake.y);   case "x-":    return inSnakeTrain(snake.x - 10 , snake.y);   case "y+":    return inSnakeTrain(snake.x ,snake.y + 10);   case "y-":    return inSnakeTrain(snake.x ,snake.y - 10);  } }
//是否在火車車廂內 function inSnakeTrain(x,y){   for(var i=0;i<snakeTrain.length;i++){   var train = snakeTrain[i];   if (x== train.x && y == train.y){      return true;   }    }   return false; }
//創建方塊 function createBox(x,y,sl){    var newNode = document.createElement("div");//創建P標籤    newNode.id = sl+"_"+x+"_"+y;    newNode.name = "boxs";    newNode.className="bd "+sl;    document.body.appendChild(newNode);    newNode.style.left = (desktop.left+x)+"px";    newNode.style.top = (desktop.top+y)+"px";   }
//移除方塊 function removeBox(x,y,sl){  document.body.removeChild($(sl+"_"+x+"_"+y)); }
//自動開火車 function startTrain(code){  if ("undefined" == typeof(code)){   code = direction;  }  var rs = 0;  switch(code){   case 37://左   rs = leftGo();   break;   case 38://上   rs = upGo();   break;   case 39://右   rs = rightGo();   break;   case 40://下   rs = downGo();   break;  }  if (rs != -1){   direction = code;   drawHead();  } }
function gameOver(msg){  gameStatus = -1;  var link = '<a href="javascript:reloadGame()">再來一次</a>';  $("msg").innerHTML = msg+"<br/><br/>"+link;  window.clearInterval(block);   }
function reloadGame(){  location.replace(location.href); }

 

推薦閱讀文章

Bookmark the permalink ,來源:互聯網