1. 程式人生 > 程式設計 >用JS實現貪吃蛇小遊戲

用JS實現貪吃蛇小遊戲

本文例項為大家分享了實現貪吃蛇小遊戲的具體程式碼,供大家參考,具體內容如下

效果圖:

用JS實現貪吃蛇小遊戲

完整程式碼如下:

HTML

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width,initial-scale=1.0">
  <link rel="stylesheet" href="/index.css">
  <title>Document</title>
</head>

<body>
  <div class="content">
    <div class="btn startBtn"><button></button></div>
    <div class="btn pauseBtn"><button></button></div>
    <div id="snakeWrap">
      <!-- <div class="snakeHead"></div>
      <div class="snakeBody"></div>
      <div class="food"></div> -->
    </div>
  </div>

  <script src="js/index.js"></script>
</body>

</html>

CSS

.content {
  width: 640px;
  height: 640px;
  margin: 100px auto;
  position: relative;
}

.btn {
  width: 100%;
  height: 100%;
  position: absolute;
  left: 0;
  thttp://www.cppcns.comop: 0;
  background-color: rgba(0,.3);
  z-index: 2;
}

.btn button {
  background: none;
  border: 0;
  background-size: 100% 100%;
  cursor: pointer;
  outline: none;
  position: absolute;
  left: 50%;
  top: 50%;
}

.startBtn button {
  width: 200px;
  height: 130px;
  background-image: url(../imgs/startBtn.gif);
  margin-left: -100px;
  margin-top: -75px;
}

.pauseBtn {
  display: none;
}

.pauseBtn button {
  width: 70px;
  height: 70px;
  background-image: url(../imgs/pauseBtn.png);
  margin-left: -35px;
  margin-top: -35px;
}

#snakeWrap {
  position: relative;
  width: 600px;
  height: 600px;
  background: #225675;
  border: 20px solid #7dd9ff;
}


/* #snakeWrap div {
  width: 20px;
  height: 20px;
} */

.snakeHead {
  background-image: url(../imgs/snake.png);
  background-size: cover;
}

.snakeBody {
  background-color: #9ddbb1;
  border-radius: 50%;
}

.food {
  background-image: url(../imgs/food.png);
  background-size: cover;
}

JS

// 宣告方塊的寬高,行數和OWHxGjWHp列數
var sw = 20,sh = 20,tr = 30,td = 30;

var snake = null,//蛇的例項
  food = null,//食物的例項
  game = null; //遊戲的例項

function Square(x,y,classname) {
  this.x = sw * x;
  this.y = sh * y;
  this.class = classname;

  this.viewContent = dochttp://www.cppcns.comument.createElement('div'); //方塊對應的DOM元素
  this.viewContent.className = this.class;
  this.parent = document.getElementByIdwww.cppcns.com
('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); }; Square.prototype.remove = function() { this.parent.removeChild(this.viewContent); }; //