2048小游戏

2048小游戏

1. 启动页设计
1.整理初始代码,删除部分文件代码。(跟以往文章删除方式一样。)
2.新建如下图文件

2.启动页的视图层渲染
2.1修改pages/index/index.wxml文件

<!--index.wxml-->

<view class='container'>
  <text class='textStyle'>每次可以选择上下左右其中一个方向去滑动,每滑动一次,所有的数字方块都会往滑动的方向靠拢外,系统也会在空白的地方乱数出现一个数字方块,相同数字的方块在靠拢、相撞时会相加。不断的叠加最终拼凑出2048这个数字就算成功。</text>
  <button wx:if='{{!hasUserInfo}}' open-type='getUserInfo' bindgetuserinfo='getUserInfo'>开始游戏</button>
  <block wx:else>
    <view>
      <image class='logo' src='../../img/logo.png'></image>
      <view class='load'>
        <text class='{{current==0?"sct":""}}'></text>
        <text class='{{current==1?"sct":""}}'></text>
        <text class='{{current==2?"sct":""}}'></text>
        <text class='{{current==3?"sct":""}}'></text>
      </view>
    </view>
  </block>
</view>

2.2修改pages/index/index.wxss文件

/**index.wxss**/
.container{
  background-color: #faf8ee;
  height: 100vh;
  width: 100vw;
}
.textStyle{
  padding: 10vh;
  word-break: break-all;
  font-size: 28rpx;
}
.logo{
  width: 100px;
  height: 100px;
  border-radius: 20px;
}
.load{
  text-align: center;
  margin-top: 10px;
}
.load text{
  display: inline-block;
  width: 6px;
  height: 6px;
  border: 1px solid #ccc;
  border-radius: 4px;
  margin: 0 5px;
}
.load text.sct{
  background-color: #ccc;
}

3. 启动页逻辑层开发
3.1 定义数据变量。
打开index.js文件,添加如下代码:

//index.js
//获取应用实例
const app = getApp()
var timer;
const AV = require('../../utils/av-weapp-min.js')
Page({
    data:{
      current:0,
      hasUserInfo:false
    },
    onLoad:function(){
      wx.getSetting({
        success:res=>{
          console.log(res)
          if (res.authSetting['scope.userInfo']) {
            this.setData({
              hasUserInfo: true
            })
            this.load();
            this.getInfo();
          }
        }
      })
    },
    getInfo:function(){
      AV.User.loginWithWeapp().then(user => {
        console.log("登录成功")
        const users=AV.User.current();
        if (users.attributes.url){
          console.log("非第一次登录")
          // clearInterval(timer)
          // app.globalData.userInfo = users.attributes;
          // wx.redirectTo({
          //   url: '../game/game',
          // })
        }else{
          console.log("第一次登录")
          wx.getUserInfo({
            success:(u)=>{
              console.log(u)
              console.log(u.userInfo.avatarUrl)
              users.set('name', u.userInfo.nickName)
              users.set('url', u.userInfo.avatarUrl)
              users.set('score',0)
              users.set('count',2)
              users.save();
              // clearInterval(timer)
              // app.globalData.userInfo = users.attributes;
              // wx.redirectTo({
              //   url: '../game/game',
              // })
            }
          })
        }
        console.log("操作成功")
        console.log(app.globalData.userInfo)
        clearInterval(timer)
        app.globalData.userInfo = users.attributes;
        wx.redirectTo({
          url: '../game/game',
        })
      }).catch(console.error);
    },
    getUserInfo:function(){
      this.setData({
        hasUserInfo:true
      })
      this.load();
      this.getInfo();
    },
    load:function(){
      var  n=1;
      var that=this;
      timer=setInterval(function(){
        that.setData({
          current: that.data.current+1
        });
        if (that.data.current>3){
          that.setData({
            current: 0
          });
        }
        n++;
      },400);
    }

})

任务2.2 leancloud的使用

  1. 注册leancloud账号
    访问https://leancloud.cn/dashboard/login.html#/signin注册页面,根据提示注册账号。
  2. 创建应用
    根据提示创建应用。
  3. 下载存储SDK
    前往 https://releases.leanapp.cn/#/leancloud/javascript-sdk/releases,下载最新版本的 av-weapp-min.js。
  4. 引用SDK
    将下载的js文件拷贝至utils目录下。
  5. 配置SDK环境
    5.1 获取微信信息。
    在微信公众平台获取AppID(小程序ID)和AppSecret(小程序密钥)
    5.2 配置微信小程序有效服务器域名。
    将app-router.leancloud.cn和hjmgfpv1.api.lncld.net配置进微信小程序服务器有效域名中。
    注意:此处域名配置可能会根据项目而有变化,在后续实际操作中,如遇错误提示,将域名按照错误提示添加即可。
    5.3 配置微信信息
    进入leancloud控制台,点击组件中的社交,配置微信id和key。
    5.4 获取leancloud基本参数。
    进入leancloud自控制台,点击设置中的应用key
    5.5 配置参数
    打开app.js文件,注意替换自己项目的key和id,添加如下代码:
const AV = require(./utils/av-weapp-min’);
AV.init({
appId: ‘HjmgFpV1WcVwPPDiSIS0oo3e-gzGzoHsz’,
appKey: ‘LxQ3GLuoePHEqLUBphrpT2V1’,
});

任务2.3 用户信息的存储
1 定义全局变量存储用户信息
1.1 打开app.js文件,在App下添加变量,代码如下:

globalData: {
userInfo: null
  }

任务2.4游戏页设计

  1. 设置页面不可滑动
    打开game.json文件,添加如下代码:
{
  "disableScroll":true
}
  1. 项目公共设置。
    修改app.json文件,替换window字段下代码:
  "window": {
    "backgroundTextStyle": "light",
    "navigationBarBackgroundColor": "#faf8ee",
    "navigationBarTitleText": "2048",
    "navigationBarTextStyle": "black"
  }
  1. 项目公共样式。
    修改app.wxss文件,替换container字段下代码:
.container {
height:100%;
display:flex;
flex-direction:column;
align-items:center;
justify-content:space-between;
padding:200rpx0;
box-sizing:border-box;
} 
  1. 修改game.wxml文件,替换如下代码:
<!--pages/game/game.wxml-->
<view class='container'>
  <loading hidden='{{!hidden}}'>加载中。。。</loading>
  <view class='head'>
    <view class='lside'>
      <text class='title'>2048</text>
      <text class='play' bindtap='gameStart'>{{start}}</text>
    </view>
    <view class='rside'>
      <text >score <text class='score'>{{score}}</text>
      </text>
    </view>
  </view>

  <view class='game' bindtouchstart='touchStart' bindtouchmove='touchMove' bindtouchend='touchEnd'>
    <!--funfunnn[[2,2,2,2],[2,2,2,2],[2,2,2,2],[2,2,2,2]]-->
    <view wx:for='{{num}}' wx:for-item='row' wx:key='row.key'>
      <view class='cell' wx:for='{{row}}' wx:for-item='cell' wx:key='cell.key'> 
        <view class='cell-con cell-con-{{cell}}'>{{cell}}</view>
      </view>
    </view>
    <!-- 游戏结束-->
    <view class='game-over' hidden='{{!over}}'>
      <text class='nowScore'>历史最高分:{{bestScore}}</text>
      <text class='nowScore'>本次成绩:{{score}}</text>
      <text class='pro'>{{endMsg}}</text>
    </view>
  </view>

  <view class='bottom'>
    <view class='bottom-left'>
     <text>best score:{{bestScore}}</text>
     <text>最高连击:{{bestCount}}</text>
    </view>
    <text class='order' bindtap='record_click'>排行榜</text>
  </view>
</view>

  1. 为游戏页面添加样式。
    修改game.wxss文件,添加如下代码:
/* pages/game/game.wxss */
.container{
  color: #776e65;
  background-color: #faf8ee;
  height: 100vh;
  position: relative;
}
.head{
  display: flex;
  justify-content: space-around;
  flex-direction: row ;
  text-align: center;
  width: 93vw;
  position:absolute;
  top: 5vh;
}
.lside{
  display: flex;
  flex-direction: column;
  width: 130px;
  height: 100px;
  justify-content:center;
}
.title{
  font-size: 40px;
  font-weight: bold;
}
.play{
  font-size: 20px;
  background-color: #bbada0;
  color: #fff;
  border-radius: 5px;
  width: 130px;
  text-align: center;
  height: 40px;
  line-height: 40px;
  font-weight: bold;
}
.rside{
  background-color: #bbada0;
  width: 100px;
  height: 100px;
  padding-top: 10px;
  border-radius: 5px;
}
.rside text{
  display: block;
  text-align: center;
  font-size: 30px;
  font-weight: bold;
}

.score{
  color: #fff;
}
.game{
  margin-top: 12vh;
  position: absolute;
  padding-top: 5vw;
  padding-left: 1vw;
  background: #bbada0;
  border-radius: 5px;
  width: 93vw;
  height: 93vw;
  box-sizing: border-box;
}
.cell{
  width: 19vw;
  height: 19vw;
  margin-left: 3vw;
  margin-bottom: 3vw;
  float: left;
  border-radius: 5px;
  box-sizing: border-box;
  background: rgba(238, 228, 228,0.35);
  overflow:hidden;
}
.cell-con{
  width: 19vw;
  height: 19vw;
  line-height: 19vw;
  position: absolute;
  font-size: 35px;
  font-weight: bold;
  text-align: center;
  border-radius: 5px;
}
.cell-con-2 { background: #eee4da; }
.cell-con-4 { background: #ede0c8; }
.cell-con-8 {
  color: #f9f6f2;
  background: #f2b179;
}
.cell-con-16 {
  color: #f9f6f2;
  background: #f59563;
}
.cell-con-32 {
  color: #f9f6f2;
  background: #f67c5f;
}
.cell-con-64 {
  color: #f9f6f2;
  background: #f65e3b;
}
.cell-con-128 {
  color: #f9f6f2;
  background: #edcf72;
  font-size: 30px;
}
.cell-con-256 {
  color: #f9f6f2;
  font-size: 30px;
  background: #edcc61;
}
.cell-con-512 {
  color: #f9f6f2;
  font-size: 30px;
  background: #edc850;
}
.cell-con-1024 {
  color: #f9f6f2;
  font-size: 25px;
  background: #edc53f;
}
.cell-con-2048 {
  color: #f9f6f2;
  font-size: 25px;
  background: #edc22e;
}  
.game-over{
  position: absolute;
  background-color: rgba(255, 255, 255,0.8);
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  text-align: center;
  padding-top: 20vh;
  box-sizing: border-box;
  
}
.game-over text{
  display: block;
}
.nowScore{
  font-size: 20px;
  margin-bottom: 10px;
}
.pro{
  font-weight: bold;
  font-size: 30px;
}
.bottom{
  position: absolute;
  bottom: 1vh;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items:center;
  width: 93vw;
  height: 130rpx;
}
.bottom-left{
  display: flex;
  flex-direction: column;
  text-align: left;
  justify-content: center;
}
.order{
  font-size: 20px;
  background-color: #bbada0;
  color: #fff;
  border-radius: 5px;
  width: 130px;
  text-align: center;
  height: 40px;
  line-height: 40px;
  margin-top:auto;
  margin-bottom:auto;
}

任务3.1 游戏页表格的实现
1.2 新建grid.js文件,作为滑动表格的操作工具类。

function Board(size){
  this.size=size;
  this.grid = this.init();
} 
Board.prototype={
  init(){//形成一个空矩阵
    var grid=[];
    for(var i=0;i<this.size;i++){
      //[[],[],[],[]]
        grid[i]=[];
        for(var j=0;j<this.size;j++){
          //["","","",""]
          grid[i].push("");
        }
    }
    //[["","","",""],["","","",""],["","","",""],["","","",""]]
    return grid;
  },
  usefulCell(){//记录为空的格子
    var cells=[];
    for(var i=0;i<this.size;i++){
      for (var j = 0; j < this.size; j++) {
          if(this.grid[i][j]==""){
            cells.push({
              x:i,
              y:j
            });
          }
      }
    }
    return cells;
  },
  selectCell(){ //随机选择一个空的格子
    var cells= this.usefulCell();
    if (cells.length){
      return cells[Math.floor(Math.random()*cells.length)]
    }
  },
  cellEmpty(){ //判断是否还有可用的格子
    return !this.usefulCell().length;
  }
}
module.exports=Board;

1.3 新建main.js文件,作为游戏操作工具类。

var Board=require('./grid.js')
function Main(size){
  this.size=size;
  this.startData = 2;//初始填充2个数据
  this.init();
  this.score=0;
  this.isChange=false;
  this.isCombine=false;
  
}
Main.prototype={
  init(){
    this.board = new Board(this.size);
    this.bproto = this.board.__proto__;
    this.setDataRandom();
    this.startData=1;
  },
  setDataRandom(){
    for(var i=0;i<this.startData;i++){
      
      this.addRandomData();
    }
  },
  addRandomData(){
    if (!this.board.cellEmpty()){
      var value=Math.random()<0.9?2:4;
      var cell = this.board.selectCell();
      cell.val = value;
      this.update(cell);
    }
  },
  update(cell){
    this.board.grid[cell.x][cell.y]=cell.val;
  },
  //根据滑动方向,生成数组列表
  formList(dir){
    var list=[[],[],[],[]];
    for(var i=0;i<this.size;i++){
      for (var j = 0; j < this.size; j++) {
        switch (dir){
          case 0:
            list[i].push(this.board.grid[j][i])
            break;
          case 1:
            list[i].push(this.board.grid[i][this.size - 1 - j])
            break;
          case 2:
            list[i].push(this.board.grid[this.size-1-j][i])
            break;
          case 3:
            list[i].push(this.board.grid[i][j])
            break;
        }
      }
    }
    return list;
  },
  changeItem(item){ //将[0202]改为[2200]
    var cnt=0;
    for(var i=0;i<item.length;i++){
      if(item[i]!=''){
        if (cnt!=i){
          //数据有变化
          this.isChange=true;
        }
        item[cnt++]=item[i];
      }
    }
    //[2200]
    for(var j=cnt;j<item.length;j++){
      item[j]='';
    }
    return item;
  },
  combine(list){ //滑动时合并相同的项
    for (var i = 0; i < list.length;i++){
      list[i] = this.changeItem(list[i]);
    }
    for(var i=0;i<this.size;i++){
      for (var j = 1; j < this.size; j++) {
        if (list[i][j - 1] == list[i][j] && list[i][j]!=''){
          list[i][j-1]+=list[i][j];
          //list[i][j-1]=list[i][j-1]+list[i][j];
          list[i][j]='';
          this.score = this.score + list[i][j - 1];
          this.isCombine=true;
        }
      }
    }
    for (var i = 0; i < list.length; i++) {
      list[i] = this.changeItem(list[i]);
    }
    return list;
  },
  move(dir){
    this.board.__proto__=this.bproto;
    var curList=this.formList(dir);
    var list = this.combine(curList);
    var result=[[],[],[],[]];
    for(var i=0;i<this.size;i++){
      for (var j = 0; j < this.size; j++) {
        switch(dir){
          case 0:
            result[i][j]=list[j][i];
            break;
          case 1:
            result[i][j] = list[i][this.size-1-j];
            break;
          case 2:
            result[i][j] = list[j][this.size-1-i];
            break;
          case 3:
            result[i][j] = list[i][j];
            break;
        }
      }
    }
    this.board.grid=result;
    if(this.isCombine){
      this.setDataRandom();
      this.isChange=false;
      this.isCombine=false
    }else{
      if(this.isChange){
        this.setDataRandom();
        this.isChange=false;
      }
    }
    
    return result;
  },
  getScore(){
    return this.score;
  },
  isOver(){
    this.board.__proto__ = this.bproto;
    if(!this.board.cellEmpty()){
        return false;
    }else{
      for(var i=0;i<this.size;i++){ //左右不等
        for(var j=1;j<this.size;j++){
          if (this.board.grid[i][j] == this.board.grid[i][j-1]){
            return false;
          }
        }
      }
      for (var j = 0; j < this.size; j++) { //上下不等
        for (var i= 1; i < this.size; i++) {
          if (this.board.grid[i][j] == this.board.grid[i-1][j]) {
            return false;
          }
        }
      }
    }
    return true;
  }
}
module.exports=Main;

1.4 页面实现
打开game.js文件,在页面最上方添加如下代码:

// pages/game/game.js
var Board = require('./grid.js')
var Main=require('./main.js')
const AV = require('../../utils/av-weapp-min.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
      start:"开始游戏",
      hidden:false,
      num:[],
      score:0,//此局最高分
      bestScore:0,//历史最高分
      bestCount:0,//历史最高连击
      maxCount: 0,//此局最高连击
      endMsg:"",
      over:false,
      newRecord:false
  },
  saveRecord:function(){
    var local_count=getApp().globalData.userInfo.count;
    var local_score = getApp().globalData.userInfo.score;
    const users=AV.User.current();
    if(local_count<this.data.maxCount){
      users.set('count',this.data.maxCount);
      users.save();
    }
    if (local_score < this.data.score) {
      users.set('score', this.data.score);
      users.save();
    }
    getApp().globalData.userInfo=users.attributes;
    var Record=AV.Object.extend('Record');
    var record=new Record();
    record.set("username", getApp().globalData.userInfo.username);
    record.set("count",this.data.maxCount);
    record.set("score",this.data.score);
    record.save().then(function(todo){
      console.log("success record");
    }, function(error){
      console.log(er)
    });
  },
  gameStart:function(){
    var main=new Main(4);
    this.setData({
      main:main
    })
    this.data.main.__proto__ = main.__proto__;
    this.setData({
      over:false,
      score:0,
      bestCount: wx.getStorageSync("bestCount"),
      bestScore: wx.getStorageSync("bestScore"),
      num:this.data.main.board.grid,
      newRecord:false
    })
  },
  touchStartX:0,
  touchStartY: 0,
  touchEndX:0,
  touchEndY: 0,
  touchStart:function(ev){ //触摸开始坐标
    var touch=ev.touches[0];
    this.touchStartX = touch.clientX;
    this.touchStartY=touch.clientY;

  },
  touchMove:function(ev){ //触摸最后移动时的坐标
    var touch = ev.touches[0];
    this.touchEndX = touch.clientX;
    this.touchEndY = touch.clientY;
  },
  touchEnd:function(){ //触摸离开的时候的坐标
    if(this.data.over){
      return;
    }
    var disX = this.touchStartX - this.touchEndX;
    var absdisX = Math.abs(disX);
    var disY = this.touchStartY - this.touchEndY;
    var absdisY = Math.abs(disY);
    if(this.data.main.isOver()){
      this.gameOver()
    }else{
      if (Math.max(absdisX, absdisY) > 10) { //确定是否在滑动
        this.setData({
          start: '重新开始'
        })
        var direction = absdisX > absdisY ? (disX < 0 ? 1 : 3) : (disY < 0 ? 2 : 0);//0:向上滑动 1:向右 2:向下 3:向左
        //console.log("方向:"+direction);
        var dataList = this.data.main.move(direction);
        this.updateView(dataList);
      }
    }
    
  },
  gameOver(){
    this.setData({
      over:true
    })
    if(this.data.newRecord && this.data.maxCount>=2048){
      this.setData({
        endMsg:"恭喜达到2048,创造新纪录!"
      })
    } else if (this.data.maxCount >= 2048){
      this.setData({
        endMsg: "恭喜达到2048!"
      })
    } else if (this.data.newRecord){
      this.setData({
        endMsg: "创造新纪录!"
      })
    }else{
      this.setData({
        endMsg: "游戏结束!"
      })
    }
    this.saveRecord();
  },
  updateView(dataList){
    var max=0;
    for(var i=0;i<4;i++){
      for (var j = 0; j < 4; j++) {
        if (dataList[i][j] != "" && dataList[i][j]>max){
          max = dataList[i][j];
        }
      }
    }
    if(max>this.data.bestCount){
      wx.setStorageSync("bestCount", max);
      this.setData({
        bestCount:max,
        newRecord:true
      })
    }
    if(this.data.main.getScore()>this.data.bestScore){
      wx.setStorageSync("bestScore", this.data.main.getScore())
      this.setData({
        bestScore: this.data.main.getScore(),
        newRecord:true
      })
    }
    this.setData({
      num: dataList,
      score: this.data.main.getScore(),
      maxCount:max
    })
  },
  record_click:function(){
    wx.navigateTo({
      url: '../record/record',
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
      if(!wx.getStorageSync("bestCount")){
        wx.setStorageSync("bestCount", 2)
      }
      if (!wx.getStorageSync("bestScore")) {
        wx.setStorageSync("bestScore", 0)
      }
    this.gameStart();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})

任务4.1 排行榜

  1. 新建页面
    新建pages/record目录,在该目录下新建record页面,用来展示排行榜。打开record.wxml文件,添加如下代码:
<!--pages/record/record.wxml-->
<view class='swiper-tab'>
  <view class="tab-list-left {{currentTab==0?'on':''}}" data-current='0' bindtap='switchNav'>个人排行</view>
  <view class="tab-list-right {{currentTab==1?'on':''}}" data-current='1' bindtap='switchNav'>全部排行</view>
</view>
<scroll-view scroll-y class='scroll'>
  <block wx:for="{{list}}">
    <view class='content'>
      <text class='order' hidden='{{isshow}}'>{{index+1}}</text>
      <image class='logo' mode='widthFix' src='{{item.url}}'></image>
      <view class='right'>
        <text class='name'>{{item.name}}</text>
        <text class='record'>最高连击:{{item.count}}</text>
        <text class='record'>最高分数:{{item.score}}</text>
        <text class='record' hidden='{{isshowTime}}'>{{item.time}}</text>
      </view>
    </view>
  </block>
</scroll-view>

  1. 打开record.wxss文件,添加如下代码:
/* pages/record/record.wxss */
.swiper-tab{
  text-align: center;
  line-height: 10vh;
  height: 10vh;
  margin-top: auto;
}
.tab-list-left{
  font-size: 30rpx;
  display: inline-block;
  width: 25%;
  border: 1px solid #bbada0;
  line-height: 60rpx;
  color: #bbada0
}
.tab-list-right{
  font-size: 30rpx;
  display: inline-block;
  width: 25%;
  border: 1px solid #bbada0;
  line-height: 60rpx;
  color: #bbada0
}
.on{
  background-color: #bbada0;
  color: #fff
}
.content{
  display: flex;
  margin: 20rpx;
  padding-bottom: 20rpx;
  justify-content: flex-start;
  border-bottom: 1px solid #ccc;
  align-items: center;
}
.scroll{
  height: 90vh
}
.order{
  color: #a0a0bb;
  padding-right: 20rpx;
}
.logo{
  width: 100rpx;
  height: 100rpx;
  border-radius: 20rpx;
}
.right{
  display: flex;
  flex-direction: column;
  margin-left: 20rpx;
}
.name{
  font-size: 20px;
  font-weight: bold;
}
.record{
  font-size: 15px;
}
  1. 打开record.js,添加如下代码:
// pages/record/record.js
const AV = require('../../utils/av-weapp-min.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentTab:0,
    list:[],
    isshow:true,
    isshowTime:false
  },
  switchNav:function(e){
    console.log(e);
    if(e.target.dataset.current==1){
      this.loadAllOrder();
      this.setData({
        isshow:false,
        isshowTime:true
      })
    } else if (e.target.dataset.current == 0 ){
      this.loadPersonOrder();
      this.setData({
        isshow: true,
        isshowTime: false
      })
    }
    this.setData({
      currentTab: e.target.dataset.current
    })
  },
  loadPersonOrder:function(){
    var that=this;
    var query=new AV.Query('Record');
    query.equalTo('username',getApp().globalData.userInfo.username);
    query.descending('updatedAt');
    query.limit(50);
    query.find().then(function(result){
      console.log(result)
      var lists=[];
      for(var i=0;i<result.length;i++){
        var res=result[i].attributes;
        var outtime = that.formatDateTime(result[i].updatedAt);
        lists.push({
          name: getApp().globalData.userInfo.name,
          url: getApp().globalData.userInfo.url,
          score: res.score,
          count:res.count,
          time: outtime
        })
      }
      that.setData({
        list:lists
      })
    },function(error){
      console.log(error);
    })
  },
  loadAllOrder: function () {
    var that = this;
    var query = new AV.Query('_User');
    query.addDescending('score');
    query.limit(50);
    query.find().then(function (result) {
      console.log(result)
      var lists = [];
      for (var i = 0; i < result.length; i++) {
        var res = result[i].attributes;
        var outtime = that.formatDateTime(result[i].updatedAt);
        lists.push({
          name: res.name,
          url: res.url,
          score: res.score,
          count: res.count,
          time: outtime
        })
      }
      that.setData({
        list: lists
      })
    }, function (error) {
      console.log(error);
    })
  },
  formatDateTime:function(inputTime){
    var date = new Date(inputTime);
    var y=date.getFullYear();
    var m=date.getMonth()+1;
    m=m<10?('0'+m):m;
    var d=date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h=date.getHours();
    h = h < 10 ? ('0' + h) : h;
    var minute=date.getMinutes();
    minute = minute < 10 ? ('0' + minute) : minute;
    var second=date.getSeconds();
    second = second < 10 ? ('0' + second) : second;
    return y+'-'+m+"-"+d+' '+h+':'+minute+':'+second;
  } ,
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.loadPersonOrder();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})
  1. 修改权限.
    打开leancloud控制台,修改_User表权限,选择所有用户选项。
  2. 程序发布
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值