1. 程式人生 > 程式設計 >如何基於javascript實現貪吃蛇遊戲

如何基於javascript實現貪吃蛇遊戲

這篇文章主要介紹瞭如何基於javascript實現貪吃蛇遊戲,文中通過示例程式碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下

html程式碼:

<div class="content">
  <div class="btn startBtn">       <!-- 開始按鈕 -->  
    <button type="button"></button>
  </div>
  <div class="btn stopBtn">        <!-- 暫停按鈕 -->
    <button type="button"></button>
  </div>
  <div id="snakeWrap"></div>     <!-- 主題內容 -->
</div>

css程式碼:

* {
  margin: 0;
  padding: 0;
}
body {
  background-color: #565F65;
  width: 100%;
  height: 10vh;
  overflow: hidden;
}

.content {
  width: 500px;
  height: 500px;
  position: absolute;
  top: 50%;
  left: 50%; 
  margin-top: -250px;
  margin-left: -250px;
  background-color: #565F65;
  border: 10px solid #E7E7E7;
  box-shadow: inset 0px 0px 5px 2px #000;
}
.btn {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  background-color: rgba(0,.3);  /*遊戲未開始時和暫停時的遮罩*/
  z-index: 2;
}
.btn button {
  background: none;
  border: none;
  background-size: 100% 100%;
  cursor: pointer;
  outline: none;
  position: absolute;
  left: 50%;
  top: 50%;
}
.startBtn button{
  width: 170px;
  height: 80px;
  background-image: url(img/startbtn.png);
  margin-top: -40px;
  margin-left: -85px;
}
.stopBtn {
  display: none;
}
.stopBtn button{
  width: 70px;
  height: 70px;
  background-image: url(img/stopbtn.png);
  margin-top: -35px;
  margin-left: -35px;
}

#snakeWrap {
  width: 500px;
  height: 500px;
  position: relative;
}
.snakeHead { /*蛇頭樣式*/
  background-color: aqua;
  border-radius: 50%;
}
.snakeBody { /*蛇身樣式*/      
  background-color: navajowhite;
  border-radius: 50%;
}
.food {  /*食物樣式*/
  background-image: url(img/food.png);
  background-size: cover;
}

javascript 程式碼:

var sw = 20,//一個方塊的寬
   sh = 20,//一個方塊的高
    tr = 25,//行數
    td = 25;  //列數
var snake = null,//蛇的例項
    food = null,//食物的例項
    game = null;  //遊戲的例項
function Square(x,y,classname) {
  this.x = x * sw;     //方塊實際的位置
  this.y = y * sh;     //方塊實際的位置
  this.class = classname;
  
  this.viewContent = document.createElement('div');  //方塊對應的DOM元素
  this.viewContent.className = this.class;
  this.parent = document.getElementById('snakeWrap'); //方塊的父級
}

Square.prototype.create = function() {  //建立方塊 DOM,並新增到頁面裡
  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);
};

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,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,'snakeHead');
  snakeHead.create();
  this.head = snakeHead;    // 儲存蛇頭資訊
  this.pos.push([2,0]);    //把蛇頭的位置存起來
  
  //建立蛇身體
  var snakeBody1 = new Square(1,'snakeBody');
  snakeBody1.create();
  this.pos.push([1,0]);    //把蛇身1的位置存起來
  
  var snakeBody2 = new Square(0,'snakeBody');
  snakeBody2.create();
  this.tail = snakeBody2;    //把蛇尾的資訊存起來
  this.pos.push([0,0]);    //把蛇身1的位置存起來
  
  //讓蛇頭蛇身形成連結串列關係
  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 selfCollind = false;   //是否撞到自己
  this.pos.forEach(function(value) {
    if(value[0] == nextPos[0] && value[1] == nextPos[1]) {
      //如果陣列中的兩個資料都相等,就說明下一個點在蛇身上裡面能找到,代表撞到自己了
      selfCollind = true;
    }
  });
  if(selfCollind) {
    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]) {
    //如果這個條件成立說明現在蛇頭要走的下一個點是食物的那個點
    console.log('撞到食物了了!');
    this.strategies.eat.call(this);
    return;
  }
  //下一個點什麼都不是,走
  this.strategies.move.call(this);
};

//處理碰撞後要做的事 
Snake.prototype.strategies = {
  move : function(format) {  //這個引數用於決定要不要刪除最後一個方塊(蛇尾),當傳了這個引數後就表示要做的事情是吃
    //建立新身體(在蛇頭位置)
    var newBody = new Square(this.head.x/sw,this.head.y/sh,'snakeBody');
    //更新連結串列關係
    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')
    //更新連結串列關係
    newHead.next = newBody;
    newHead.last = null;
    newBody.last = newHead;
    newHead.viewContent.style.transform = 'rotate('+this.direction.rotate+'deg)';
    newHead.create();
    
    
    //蛇身上每一個方塊的座標也要更新
    this.pos.splice(0,[this.head.x/sw + this.direction.x,this.head.y/sh + this.direction.y]);
    this.head = newHead;   //還要把this.head的資訊更新一下
    
    if(!format) {  //如何format 的值為 false,表示需要刪除(除了吃之外的操作)
      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();
  }
}

snake = new Snake();

//建立食物
function createFood() {
  //食物小方塊的隨機座標
  var x = null;
  var y = null;
  
  var include = true;  //迴圈跳出的條件,true表示食物的座標在蛇身上(需要繼續迴圈),false表示食物座標不在蛇身上(不迴圈了)
  while(include) {
    x = Math.round(Math.random() * (td - 1)); //0-29
    y = Math.round(Math.random() * (tr - 1));
    
    snake.pos.forEach(function(value) {
      if(x != value[0] && y != value[1]) {
        //這個條件成立說明現在隨機出來的這個座標,在蛇身上並沒有找到
        include = false;
      }
    });
    
  }
  //生成食物
  food = new Square(x,'food');
  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;
  this.speed = 200;
}
Game.prototype.init = function() {
  snake.init();
  snake.getNextPos();
  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.dowm) {
      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();
    
  },this.speed);
}
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('.startBtn');
  startBtnWrap.style.display = 'block'; 
}
//開啟遊戲
game = new Game();
var startBtn = document.querySelector('.startBtn button');
startBtn.onclick = function() {
  startBtn.parentNode.style.display = 'none';
  game.init();
};


//暫停
var snakeWrap = document.getElementById('snakeWrap');
var puseBtn = document.querySelector('.stopBtn button')
snakeWrap.onclick = function() {
  game.pause();
  puseBtn.parentNode.style.display = 'block';
}

puseBtn.onclick =function() {
  game.start();
  puseBtn.parentNode.style.display = 'none';
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。