JavaScript, 實現貪吃蛇小遊戲

來源:互聯網
上載者:User

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

<!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 Divthis.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>
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.