當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
javascript实战项目——网页版贪吃蛇
生活随笔
收集整理的這篇文章主要介紹了
javascript实战项目——网页版贪吃蛇
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
前言
這是一個網頁版本的貪吃蛇項目,用了html和js實現,代碼有很多注釋,方便閱讀,是一個不錯的練手項目。
代碼
1.html代碼
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>GluttonousSnake</title><link rel = "stylesheet" href="../index.css"> </head> <body><div class="content"><div class="btn statrtBtn"><input type = "image" src="../startGame.png"></div><div class="btn pausBtn"><input type = "image" src="../start.png"></div><div id = "snakeWrap"></div></div><script src = "index.js" ></script> </body> </html>2.css樣式
.content{width: 640px;height: 640px;margin: 100px auto;position: relative; } .btn{width: 100%;height: 100%;position: absolute;left: 0;top: 0;background-color: rgba(0,0,0,0.3);z-index: 2; }.btn input{background: none;border: none;background-size: 100% 100%;cursor: pointer;outline: none;position: absolute;left: 50%;top:50%; }.statrtBtn input {width: 200px;height: 200px;margin-left: -100px;margin-top: -100px; }.pausBtn{display: none; }.pausBtn input{width: 128px;height: 128px;margin-left: -64px;margin-top: -64px; }#snakeWrap{width: 600px;height: 600px;background: #225675;border: 20px solid #7dd9ff;position: relative; } #snakeWrap div{width: 20px;height: 20px; } .snakeBody{background-color: #9ddbb1;border-radius: 50%; }3.js代碼
var sw = 20,//一個格子的寬sh = 20,//格子的高度tr = 30,//行數td = 30;var snake = null; var food = null;//食物的實例 var game = null;//構造函數(構造方格) function Square(x,y,classnmae,src) {this.x = x*sw;this.y = y*sh;this.class = classnmae;//創建標簽并添加標簽this.viewContent = document.createElement('img');//格子對應的DOM元素this.viewContent.className = this.class;this.viewContent.src = src;this.parent = document.getElementById('snakeWrap');//格子的父級 }//創建格子DOM(添加) Square.prototype.create = function () {this.viewContent.style.position = 'absolute';this.viewContent.style.width = sw + 'px';this.viewContent.style.height = sh + 'px';this.viewContent.style.left = this.x + 'px';this.viewContent.style.top = this.y + 'px';this.parent.appendChild(this.viewContent);//添加到頁面 }; //刪除格子DOM元素 Square.prototype.remove = function () {this.parent.removeChild(this.viewContent); }//蛇的構造函數 function Snake() {this.head = null;//保存蛇頭的信息this.tail = null;this.pos = [];//保存蛇身方格的位置//存儲蛇走的方向this.directionNum = {left:{x:-1,y:0,rotate:180},right:{x:1,y:0,rotate:0},up:{x:0,y:-1,rotate:-90},down:{x:0,y:1,rotate:90}} }//初始化蛇 Snake.prototype.init = function () {//創建蛇頭var snakeHead = new Square(2,0,'snakeHead', "../snake.png");snakeHead.create();this.head = snakeHead;//存儲蛇頭信息this.pos.push([2,0]);//存儲蛇頭的坐標//創建蛇身體第一個var snakeBody1 = new Square(1,0,'snakeBody',"../body.png");snakeBody1.create();this.pos.push([1,0]);//創建蛇身體第二個var snakeBody2 = new Square(0,0,'snakeBody',"../body.png");snakeBody2.create();this.tail = snakeBody2;//把蛇尾的信息存起來this.pos.push([0,0]);//讓蛇形成鏈表關系snakeHead.last = null;snakeHead.next = snakeBody1;snakeBody1.last = snakeHead;snakeBody1.next = snakeBody2;snakeBody2.last = snakeBody1;snakeBody2.next = null;//給蛇添加一個屬性,用來表示蛇走的方向this.direction = this.directionNum.right; };//獲取蛇頭的下一個位置對應的元素 Snake.prototype.getNextPos = function () {//蛇頭要走的下一個點的坐標var nextPos = [this.head.x/sw+this.direction.x,this.head.y/sh+this.direction.y];//下一個點是自己,代表撞到了自己,游戲結束var selfCollied = false;this.pos.forEach(function (value){if(value[0] == nextPos[0] && value[1] == nextPos[1]){selfCollied = true;}});if(selfCollied){console.log("撞到自己了!");this.strategies.die.call(this);return;}//下一個點是圍墻,游戲結束if(nextPos[0] < 0 || nextPos[1] < 0 || nextPos[0] > td-1 || nextPos[1] > tr -1 ){console.log("撞墻了!");this.strategies.die.call(this);return;}//條件成立,蛇頭撞到食物if(food && food.pos[0] == nextPos[0] && food.pos[1] == nextPos[1]){this.strategies.eat.call(this);return;}//下一個點沒有標記,繼續走this.strategies.move.call(this);//this指向實例 }//使用call方法,能調用父類的實例 Snake.prototype.strategies ={move:function (format)//參數決定要不要刪除最后一個方塊{//創建新身體(在舊蛇頭的位置)var newBody = new Square(this.head.x/sw,this.head.y/sh,'snakeBody',"../body.png");//更新鏈表的關系newBody.next = this.head.next;newBody.next.last = newBody;newBody.last = null;this.head.remove();//把舊蛇頭從位置上刪除newBody.create();//創建新的蛇頭(蛇頭下一個移動的點)var newHead = new Square(this.head.x/sw+this.direction.x,this.head.y/sh+this.direction.y,'snakeHead',"../snake.png");//更新鏈表的關系newHead.next = newBody;newHead.last = null;newBody.last = newHead;//旋轉蛇頭圖像方向newHead.viewContent.style.transform = 'rotate('+this.direction.rotate+'deg)';newHead.create();//蛇身上的每一個坐標都要更新this.pos.splice(0,0,[this.head.x/sw+this.direction.x,this.head.y/sh+this.direction.y]);//更新蛇頭的位置this.head = newHead;if(!format)//刪除蛇尾{this.tail.remove();this.tail = this.tail.last;this.pos.pop();}},eat:function (){this.strategies.move.call(this,true);createFood();game.score ++;},die:function (){game.over();}, }//1.開始創建蛇頭 snake = new Snake(); //2.碰撞后處理的事件 function createFood() {//食物方格的隨機坐標//1.食物不能出現在墻上//2.食物不能出現在蛇的身上var x = null;var y = null;var includeSnake = true;//為ture表示生成在蛇身上,那么就要繼續生成食物while (includeSnake){x = Math.round(Math.random()*(td-1));y = Math.round(Math.random()*(tr-1));snake.pos.forEach(function (value){if(x != value[0] && y != value[1]){includeSnake = false;}});//生成食物food = new Square(x,y,'food',"../food.png");food.pos = [x,y];//存儲食物坐標,用與判斷是否與蛇頭相撞var foodDom = document.querySelector('.food');if(foodDom){foodDom.style.left = x*sw+'px';foodDom.style.top = y*sh+'px';}else{food.create();}} }function Game() {this.timer = null;this.score = 0; }Game.prototype.init = function () {snake.init();createFood();document.onkeydown = function (ev){if(ev.which === 37 && snake.direction != snake.directionNum.right)//用戶按下左鍵時,蛇的移動方向不能是向右{snake.direction = snake.directionNum.left;}else if(ev.which === 38 && snake.direction != snake.directionNum.down){snake.direction = snake.directionNum.up;}else if(ev.which === 39 && snake.direction != snake.directionNum.left){snake.direction = snake.directionNum.right;}else if(ev.which === 40 && snake.direction != snake.directionNum.up){snake.direction = snake.directionNum.down;}}this.start(); }Game.prototype.start = function () {this.timer = setInterval(function (){snake.getNextPos();},200); }Game.prototype.pause = function () {clearInterval(this.timer); }Game.prototype.over = function () {clearInterval(this.timer);alert("當前得分為:" + this.score);//游戲回到最初的狀態var snakeWrap = document.getElementById('snakeWrap');snakeWrap.innerHTML = '';snake = new Snake();game = new Game();var startBtnWrap = document.querySelector('.statrtBtn');startBtnWrap.style.display = 'block';}//開啟游戲 game = new Game(); var startBtn = document.querySelector('.statrtBtn input'); startBtn.onclick = function () {startBtn.parentNode.style.display = 'none';game.init(); };//暫停游戲 var snakeWrap = document.getElementById('snakeWrap'); var pauseBtn = document.querySelector('.pausBtn input'); snakeWrap.onclick = function () {game.pause();pauseBtn.parentNode.style.display = 'block'; }pauseBtn.onclick = function () {game.start();pauseBtn.parentNode.style.display = 'none'; }4.實現效果
5.整個項目的源碼與資源:https://download.csdn.net/download/matt45m/85073431
總結
以上是生活随笔為你收集整理的javascript实战项目——网页版贪吃蛇的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 深度学习目标检测(YoloV5)项目——
- 下一篇: Codeblocks更改编译器为VC++