当前位置:首页 >> 网络编程

微信小程序实现的贪吃蛇游戏【附源码下载】

本文实例讲述了微信小程序实现的贪吃蛇游戏。分享给大家供大家参考,具体如下:

先来看看运行效果:

微信小程序实现的贪吃蛇游戏【附源码下载】

具体代码如下:

界面布局 pages/snake/snake/snake.wxml:

<!--snake.wxml-->
<view class="control" bindtouchstart="tapStart" bindtouchmove="tapMove" bindtouchend="tapEnd">
<view class="score">
  <view class="title">snake</view>
  <view class="scoredetail">
    <view class="scoredesc">得分</view>
    <view class="scorenumber">{{score}}</view>
  </view>
  <view class="scoredetail">
    <view class="scoredesc">历史最高</view>
    <view class="scorenumber">{{maxscore}}</view>
  </view>
</view>
<view class="ground">
  <view wx:for="{{ground}}" class="rows" wx:for-item="cols">
    <view wx:for="{{cols}}" class="block block_{{item}}" >
    </view>
  </view>
</view>
<modal class="modal" hidden="{{modalHidden}}" no-cancel bindconfirm="modalChange">
 <view> 游戏结束,重新开始吗? </view>
</modal>
</view>

逻辑功能 pages/snake/snake/snake.js:

//snake.js
var app = getApp();
Page({
  data:{
    score: 0,//比分
    maxscore: 0,//最高分
    startx: 0,
    starty: 0,
    endx:0,
    endy:0,//以上四个做方向判断来用
    ground:[],//存储操场每个方块
    rows:28,
    cols:22,//操场大小
    snake:[],//存蛇
    food:[],//存食物
    direction:'',//方向
    modalHidden: true,
    timer:''
  } ,
  onLoad:function(){
    var maxscore = wx.getStorageSync('maxscore');
    if(!maxscore) maxscore = 0
    this.setData({
    maxscore:maxscore
    });
    this.initGround(this.data.rows,this.data.cols);//初始化操场
    this.initSnake(3);//初始化蛇
    this.creatFood();//初始化食物
    this.move();//蛇移动
  },
  //计分器
  storeScore:function(){
   if(this.data.maxscore < this.data.score){
   this.setData({
    maxscore:this.data.score
    })
    wx.setStorageSync('maxscore', this.data.maxscore)
   }
 },
 //操场
  initGround:function(rows,cols){
    for(var i=0;i<rows;i++){
      var arr=[];
      this.data.ground.push(arr);
      for(var j=0;j<cols;j++){
        this.data.ground[i].push(0);
      }
    }
  },
  //蛇
  initSnake:function(len){
    for(var i=0;i<len;i++){
      this.data.ground[0][i]=1;
      this.data.snake.push([0,i]);
    }
  },
  //移动函数
  move:function(){
    var that=this;
    this.data.timer=setInterval(function(){
      that.changeDirection(that.data.direction);
      that.setData({
        ground:that.data.ground
      });
    },400);
  },
  tapStart: function(event){
    this.setData({
      startx: event.touches[0].pageX,
      starty: event.touches[0].pageY
      })
  },
  tapMove: function(event){
    this.setData({
      endx: event.touches[0].pageX,
      endy: event.touches[0].pageY
      })
  },
  tapEnd: function(event){
    var heng = (this.data.endx) "_blank" href="http://xiazai.jb51.net/201801/yuanma/wx-snakeGame(jb51.net).rar">本站下载

希望本文所述对大家微信小程序开发有所帮助。