文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

微信小程序实现贪吃蛇游戏

2024-04-02 19:55

关注

本文实例为大家分享了微信小程序实现贪吃蛇游戏的具体代码,供大家参考,具体内容如下

一、项目截图

二、源代码

1.WXML

代码如下(示例):


<view class='container'>
 <view class='content-bottom' bindtouchmove='touchMove' bindtouchstart='touchStart' bindtouchend='touchEnd'>
  <view wx:for="{{ground}}" wx:for-item="cols" class='ground-row'>
   <view wx:for="{{cols}}" class='ground-col'>
    <view class='block block{{item}}'></view>
   </view>   
  </view>
 </view>
 <view class='content-top'>
  <view class='top-item top-score'>
   <view class='score-description'>得分</view>
   <view class='score-number'>{{score}}</view>
  </view>
  <view class='top-item top-start' bindtap='goStart'>START</view>
  <view class='top-item top-score'>
   <view class='score-description'>历史最高</view>
   <view class='score-number'>{{maxScore}}</view>
  </view>
 </view>
</view>

2.WXSS

代码如下(示例):



.content-top {
 display: flex;
}
.top-item {
 flex: 1;
 height: 150rpx;
 margin: 0 20rpx;
 line-height: 150rpx;
 text-align: center;
 border-radius: 16rpx;
}
.top-start {
 font-size: 22px;
 background: deepskyblue;
 color: #fff;
}
.top-score {
 background: #eee4da;
}
.score-description {
 line-height: 70rpx;
}
.score-number {
 line-height: 60rpx;
}
.content-bottom {
 display: flex;
 flex-direction: column;
 width: 660rpx;
 height: 840rpx;
 margin: 50rpx auto 0;
}
.ground-row {
 display: flex;
}
.ground-col {
 flex: 1;
 width: 30rpx;
 height: 30rpx;
}
.block {
 width: 100%;
 height: 100%;
 background: #eee;
}
.block1 {
 background: black;
 border-radius: 5px;
}
.block2 {
 background:red;
 border-radius: 5px;
}

3.JS

代码如下(示例):


// pages/demo/snake/snake.js
Page({

  
  data: {
  gameStart: false,  // 游戏是否开始
  score: 0, // 当前得分
  maxScore: 0, // 历史最高分
  isMaxActive: false,
  rows: 28, // 操场行数
  cols: 22, // 操场列数
  ground: [[]], // 操场方块位置
  snake: '', // 贪吃蛇的位置
  food: [], // food位置
  startX: 0,
  startY: 0,
  endX: 0,
  endY: 0,
  flag: 0, // 当前贪吃蛇移动的方向,0 右,1 下,2 左, 3 上

  timer: null,
  modaleHidden: true
  },

  
  onLoad: function (options) {
  this.initGround(this.data.rows, this.data.cols) // 初始化操场
  console.log(wx.getStorageSync("MaxScore"))
  if (wx.getStorageSync("MaxScore")) {
   this.setData({
    maxScore: wx.getStorageSync("MaxScore"),
    isMaxActive: true
   })
  } else {
   this.setData({
    isMaxActive: false
   })
  }
  },

 goStart: function () {
  this.setData({
   gameStart: true
  })
  this.onLoad()
  this.initSnake(3)      // 初始化贪吃蛇位置
  this.initFood()        // 初始化food
  this.move(0)
 },

 
 initGround: function (rows, cols) {
  this.data.ground = []
  for (let i = 0; i < rows; i++) {
   let arr = []
   this.data.ground.push(arr)
   for (let j = 0; j < cols; j++) {
    this.data.ground[i].push(0)
   }
  }
  this.setData({
   ground: this.data.ground
  })
 },

 
 initSnake: function (n) {
  this.data.snake = []
  for (let i = 0; i < n; i++) {
   this.data.ground[0][i] = 1
   this.data.snake.push([0,i])
  }
  this.setData({
   ground: this.data.ground,
   snake: this.data.snake
  })
 },

 
 initFood: function () {
  let row = Math.floor(Math.random()*this.data.rows)
  let col = Math.floor(Math.random() * this.data.cols)
  var ground = this.data.ground
  ground[row][col] = 2
  this.setData({
   ground: ground,
   food: [row, col]
  })
  console.log(this.data.food)
 },

 
 touchStart: function (event) {
  this.data.startX = event.touches[0].pageX
  this.data.startY = event.touches[0].pageY
 },

 touchMove: function (event) {
  this.data.endX = event.touches[0].pageX
  this.data.endY = event.touches[0].pageY
  // console.log(this.data.endX, this.data.endY)
 },

 touchEnd: function (event) {
  let tX = this.data.endX ? (this.data.endX - this.data.startX) : 0
  let tY = this.data.endY ? (this.data.endY - this.data.startY) : 0
  console.log(tX, tY)
  if (!this.data.gameStart) {
   return false
  }
  if (tY < 0 && Math.abs(tX) <= Math.abs(tY)) { // 向下滑动
   this.data.flag = 3
  } else if (tY > 0 && Math.abs(tX) <= Math.abs(tY)) { // 向上滑动
   this.data.flag = 1
  } else if (tX < 0 && Math.abs(tX) > Math.abs(tY)) { // 向左滑动
   this.data.flag = 2
  } else if (tX > 0 && Math.abs(tX) > Math.abs(tY)) { // 向右滑动
   this.data.flag = 0
  }
  if(this.data.modaleHidden){
   this.move(this.data.flag)
  }  
 },
 
 move: function (state) {
  clearInterval(this.data.timer)
  // console.log(this.data.snake.length)
  var that = this
  switch(state){ // 判断滑动方向
   case 0:
    this.data.timer = setInterval(function(){
     that.moveRight()
    }, 600)
    break
   case 1:
    this.data.timer = setInterval(function () {
     that.moveBottom()
    }, 600)
    break
   case 2:
    this.data.timer = setInterval(function () {
     that.moveLeft()
    }, 600)
    break
   case 3:
    this.data.timer = setInterval(function () {
     that.moveTop()
    }, 600)
    break
  }
 },

 moveRight: function () {
  // console.log(this.data.snake)
  var snakeArr = this.data.snake
  var snakeLen = snakeArr.length
  var snakeHead = snakeArr[snakeLen - 1]
  var snakeTail = snakeArr[0]
  var ground = this.data.ground

  for (var i = 0; i < snakeLen - 1; i++) {
   snakeArr[i] = snakeArr[i + 1]
  }

  var x = snakeHead[0]
  var y = snakeHead[1] + 1

  if (y >= this.data.cols) {
   this.gameOver()
   return
  }

  snakeArr[snakeLen - 1] = [x, y]
  ground[x][y] = 1
  ground[snakeTail[0]][snakeTail[1]] = 0
  this.setData({
   snake: snakeArr,
   ground: ground
  })
  this.checkGame(snakeTail, [x, y]) // 检查是否gameover
 },
 moveBottom: function () {
  var snakeArr = this.data.snake
  var snakeLen = snakeArr.length
  var snakeHead = snakeArr[snakeLen - 1]
  var snakeTail = snakeArr[0]
  var ground = this.data.ground

  for (var i = 0; i < snakeLen - 1; i++) {
   snakeArr[i] = snakeArr[i + 1]
  }

  var x = snakeHead[0] + 1
  var y = snakeHead[1]

  if (x >= this.data.rows) {
   this.gameOver()
   return
  }

  snakeArr[snakeLen - 1] = [x, y]
  ground[x][y] = 1
  ground[snakeTail[0]][snakeTail[1]] = 0
  this.setData({
   snake: snakeArr,
   ground: ground
  })
  this.checkGame(snakeTail, [x, y]) // 检查是否gameover
 },
 moveLeft: function () {
  var snakeArr = this.data.snake
  var snakeLen = snakeArr.length
  var snakeHead = snakeArr[snakeLen - 1]
  var snakeTail = snakeArr[0]
  var ground = this.data.ground

  for (var i = 0; i < snakeLen - 1; i++) {
   snakeArr[i] = snakeArr[i + 1]
  }

  var x = snakeHead[0]
  var y = snakeHead[1] - 1

  if (y < 0) {
   this.gameOver()
   return
  }

  snakeArr[snakeLen - 1] = [x, y]
  ground[x][y] = 1
  ground[snakeTail[0]][snakeTail[1]] = 0
  this.setData({
   snake: snakeArr,
   ground: ground
  })
  this.checkGame(snakeTail, [x, y]) // 检查是否gameover
 },
 moveTop: function () {
  var snakeArr = this.data.snake
  var snakeLen = snakeArr.length
  var snakeHead = snakeArr[snakeLen - 1]
  var snakeTail = snakeArr[0]
  var ground = this.data.ground

  for (var i = 0; i < snakeLen - 1; i++) {
   snakeArr[i] = snakeArr[i + 1]
  }

  var x = snakeHead[0] - 1
  var y = snakeHead[1]

  if (x < 0) {
   this.gameOver()
   return
  }

  snakeArr[snakeLen - 1] = [x, y]
  ground[x][y] = 1
  console.log(y)
  ground[snakeTail[0]][snakeTail[1]] = 0
  this.setData({
   snake: snakeArr,
   ground: ground
  })
  this.checkGame(snakeTail, [x, y]) // 检查是否gameover
 },

 
 checkGame: function  (snakeTail, snakeHead) {
  console.log("测试snake移动")
  console.log(snakeHead)
  
  var snakeArrs = this.data.snake
  var len = this.data.snake.length
  var food = this.data.food
  var ground = this.data.ground

  console.log(this.data.snake[len-1])
  // 判断有没有撞墙
  if (snakeHead[0] >= 0 & snakeHead[0] < this.data.rows & snakeHead[1] >= 0 & snakeHead[1] < this.data.cols)
  {   
   this.data.modaleHidden = true
   this.collisionSnakeFood(snakeTail, snakeHead, food)
   this.setData({
    // snake: this.data.snakeArr,
    // ground: this.data.ground,
    modaleHidden: this.data.modaleHidden
   })
  } else {
   this.gameOver()
   return
  }
 },

 // 撞到食物,游戏继续
 collisionSnakeFood: function (tail, head, food) {
  let snake = this.data.snake
  let ground = this.data.ground
  let row = food[0]
  let col = food[1]
  let score = this.data.score
  let maxScore = this.data.maxScore
  if (head[0] === food[0] & head[1] === food[1]) {
   ground[row][col] = 1
   snake.unshift(tail)
   ground[tail[0]][tail[1]] = 1
   this.initFood()
   score += 5
   if (!this.data.isMaxActive) {
    maxScore = score
   }
  }
  this.setData({
   snake: snake,
   ground: ground,
   score: score,
   maxScore: maxScore
  })
 },

 // 游戏结束
 gameOver: function () {
  clearInterval(this.data.timer)
  let _that = this
  let maxS = this.data.maxScore
  this.setData({
   modaleHidden: false,
   timer: null
  })
  if (wx.getStorageSync("MaxScore")){
   let hisScore = wx.getStorageSync("MaxScore")
   if (hisScore < maxS) {
    wx.setStorageSync("MaxScore", maxS)
   }
  } else {
   wx.setStorageSync("MaxScore", maxS)
  }
  wx.showModal({
   title: '游戏失败',
   content: '点击确定,重新开始新一局游戏;点击取消,返回首页',
   success: function(res) {
    if(res.confirm) {
     _that.setData({
      score: 0,
      gameStart: false,  // 游戏是否开始
      snake: '', // 贪吃蛇的位置
      food: [], // food位置
      modaleHidden: true
     })
     _that.onLoad()
    }
   }
  })
 },

  
  onShareAppMessage: function () {
  
  }
})

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程网。

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-前端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯