Pārlūkot izejas kodu

开始游戏逻辑整理

chaooo 1 gadu atpakaļ
vecāks
revīzija
fbd10247b5

+ 1 - 1
src/app.json

@@ -5,7 +5,7 @@
     "pages/banner/none/main",
     "pages/banner/joint/main",
     "pages/banner/competition/main",
-    "pages/games/start/main",
+    "pages/games/play/main",
     "pages/games/records/main",
     "pages/games/report/main",
     "pages/user/main",

+ 13 - 8
src/components/connection/index.vue

@@ -32,8 +32,10 @@ export default {
         hex: "",
       },
       // $this.$connection 设置的参数
-      // 连接教具 0:未连接 1:连接中 2:已连接 3:连接失败 4:游戏中
+      // 连接教具 0:未连接 1:连接中 2:已连接 3:连接失败 4:游戏中
       connect_toy: 0,
+      // 游戏状态: 0未开始 1:开始游戏,2:游戏中 3:游戏结束
+      game_status: 0,
       // 设置图标的颜色
       device_bg: false,
       // 脑机电量
@@ -124,15 +126,14 @@ export default {
       }
     },
     /**
-     * 修改教具连接状态 0:未连接 1:连接中 2:已连接 3:连接失败 4:游戏中
+     * 修改教具连接状态 0:未连接 1:连接中 2:已连接 3:连接失败 4:游戏中
      * @param $status
      */
     setToyStatus($status = 0) {
       $this.connect_toy = $status;
     },
-    gameStart() {
-      $this.game_status = 1;
-      $this.connect_toy = 4;
+    gameStart($status = 0) {
+      $this.game_status = $status;
     },
   },
   onShow() {
@@ -142,11 +143,11 @@ export default {
       game_store.setters.setGameStatus(0);
     }
     //判断是否游戏中
-    let $game_status = game_store.getters.getGameStatus();
+    $this.game_status = game_store.getters.getGameStatus()*1;
     // 游戏过程中关闭脑机状态
     let $game_close_status = game_store.getters.getGameCloseStatus();
 
-    if ($game_status === 3) {
+    if ($this.game_status === 3) {
       // getBluetoothLinkStatus
       let $ble_status = ble_store.getters.getBluetoothLinkStatus();
       if ($ble_status === false) {
@@ -178,6 +179,9 @@ export default {
       $this.$forceUpdate();
     }
   },
+  mounted() {
+    $this.game_status = game_store.getters.getGameStatus()*1;
+  }
 };
 </script>
 
@@ -210,6 +214,7 @@ export default {
         <div v-else>
           <div class="connecting_toy">
             <ToySelected :connect_toy="connect_toy"
+                         :game_status="game_status"
                          :toy="toy_item"
                          :toy_sn="toy_sn"
                          :device_bg="device_bg"
@@ -217,7 +222,7 @@ export default {
                          :toy_power="toy_power"
                          @openToys="openToyList"
                          @deviceStatus="setDeviceStatus"
-                         @gameStart="gameStart"
+                         @gameStatus="gameStart"
             ></ToySelected>
           </div>
         </div>

+ 36 - 26
src/components/connection/toys/selected.vue

@@ -8,6 +8,7 @@ export default {
   name: "ToySelected",
   props: [
     "connect_toy",
+    "game_status",
     "toy",
     "device_bg",
     "device_power",
@@ -53,7 +54,10 @@ export default {
     hidePayWindow() {
       $this.pay_window = false;
     },
-    //选择消费的时间或者次数
+    /**
+     * 选择消费的时间或者次数
+     * @param $type 1:次数,2:时间
+     */
     choosePayType($type) {
       if (!$this.device_bg) {
         Toast.fail("请佩戴好脑机开始训练");
@@ -83,12 +87,12 @@ export default {
             game_store.setters.setGameRecordId($res["game_record_id"]);
             //打开脑控
             $this.$connection.sendControl();
-
-            Toast.success($data.errmsg);
             game_store.setters.setPlayTime($res["play_time"]);
             game_store.setters.setOverPlayTime($res["play_time"]);
+
+            Toast.success($data.errmsg);
             setTimeout(() => {
-              $this.pageToPlay();
+              $this.pageToPlay(1);
             }, 800);
           } else {
             $this.is_started = false;
@@ -101,14 +105,19 @@ export default {
         }
       );
     },
-    // 前往正在玩的波动时间界面
-    pageToPlay() {
-      $this.$emit("gameStart", true);
+    /**
+     * 前往开始游戏界面(脑波图表界面)
+     */
+    pageToPlay(status) {
+      $this.$emit("gameStatus", status);
       mpvue.navigateTo({
-        url: "/pages/games/start/main",
+        url: "/pages/games/play/main",
         success() {
-          // 设置游戏状态为游戏中
-          game_store.setters.setGameStatus(1);
+          game_store.setters.setGameStatus(status);
+          if (status === 1) {
+            // 第一次开始游戏初始化游戏时间
+            game_store.setters.setPlayedTime(0);
+          }
         },
       });
     },
@@ -144,7 +153,8 @@ export default {
       </van-col>
       <van-col span="3" offset="1">
         <div class="dot_container flex align-center">
-          <div class="dot_wait"> <img v-if="connect_toy === 1" src="https://img.shuimuai.com/web/dot.png" alt="" class="moving_dot" :class="{ moving: connect_toy === 1 }"/>
+          <div class="dot_wait">
+            <img v-if="connect_toy === 1" src="https://img.shuimuai.com/web/dot.png" alt="" class="moving_dot" :class="{ moving: connect_toy === 1 }"/>
             <img v-if="connect_toy === 2" src="https://img.shuimuai.com/m_sign_gou%402x.png" alt="" class="moving_dot"/>
             <img v-if="connect_toy === 3" src="https://img.shuimuai.com/fail.png" alt="" class="moving_dot"/>
           </div>
@@ -157,7 +167,7 @@ export default {
             <template v-if="connect_toy === 1 || connect_toy === 3">
               {{ toy["name"] }}
             </template>
-            <template v-if="connect_toy === 2 || connect_toy === 4">
+            <template v-if="connect_toy === 2">
               {{ toy_sn }}
             </template>
           </text>
@@ -177,40 +187,40 @@ export default {
           <text class="text-gray text-lg"> 连接中... </text>
         </van-row>
       </van-col>
-      <!-- 已经连接教具 -->
-      <div v-if="connect_toy === 2">
+      <!-- 教具连接失败 -->
+      <div v-if="connect_toy === 3">
         <van-col span="8">
           <button class="cu-btn bg-red lg cu-btn-primary" @click="openToyList">
             <img src="https://img.shuimuai.com/m_xuanzewanju.png" alt="" class="cut_brain_icon"/>
             <text class="cut_text">选择教具</text>
           </button>
         </van-col>
-
         <van-col span="8">
-          <button class="cu-btn bg-red lg cu-btn-primary" @click="openPayWindow" :disabled="is_started">
-            <img src="https://img.shuimuai.com/web/start_game_icon.png" alt="" class="cut_start_game_icon"/>
-            <text class="cut_text" style="padding:0px">开始训练</text>
-          </button>
+          <van-row class="text-center">
+            <text class="text-gray text-lg"> 连接失败 </text>
+          </van-row>
         </van-col>
       </div>
-      <!-- 教具连接失败 -->
-      <div v-if="connect_toy === 3">
+      <!-- 已经连接教具 -->
+      <div v-if="connect_toy === 2 && game_status !== 2">
         <van-col span="8">
           <button class="cu-btn bg-red lg cu-btn-primary" @click="openToyList">
             <img src="https://img.shuimuai.com/m_xuanzewanju.png" alt="" class="cut_brain_icon"/>
             <text class="cut_text">选择教具</text>
           </button>
         </van-col>
+
         <van-col span="8">
-          <van-row class="text-center">
-            <text class="text-gray text-lg"> 连接失败 </text>
-          </van-row>
+          <button class="cu-btn bg-red lg cu-btn-primary" @click="openPayWindow" :disabled="is_started">
+            <img src="https://img.shuimuai.com/web/start_game_icon.png" alt="" class="cut_start_game_icon"/>
+            <text class="cut_text" style="padding:0px">开始训练</text>
+          </button>
         </van-col>
       </div>
       <!-- 游戏中 -->
-      <div v-if="connect_toy === 4">
+      <div v-if="game_status === 2">
         <van-col span="16">
-          <button class="cu-btn bg-green lg" @click="pageToPlay" style="width: 100%">
+          <button class="cu-btn bg-green lg" @click="pageToPlay(2)" style="width: 100%">
             <img src="https://img.shuimuai.com/web/start_game_icon.png" alt="" class="cut_start_game_icon"/>
             <text class="cut_text" style="padding: 0px">游戏中</text>
           </button>

+ 319 - 380
src/pages/games/start/index.vue → src/pages/games/play/index.vue

@@ -4,17 +4,21 @@
     <div class="game_panel padding-top-sm">
       <van-row gutter="16">
         <van-col span="8" offset="2">
-          <view class="text-sm"><text class="title">本次游玩时间</text></view>
+          <view class="text-sm">
+            <text class="title">本次游玩时间</text>
+          </view>
           <view class="text-lg padding-top">
-            <text class="count_down_text">{{ played_time_text }}</text>
+            <text class="count_down_text">{{ countdown_text }}</text>
           </view>
         </van-col>
         <van-col span="10" offset="4">
           <view class="text-sm">
             <text class="title">计费模式</text>
-            <text class="type padding-left-sm">{{ mode_item.name }}</text>
+            <text v-if="mode===1" class="type padding-left-sm">次卡(10分钟)</text>
+            <text v-else-if="mode===2" class="type padding-left-sm">会员时间消费</text>
+            <text v-else class="type padding-left-sm">未选择</text>
           </view>
-          <button class="cu-btn bg-red text-white margin-top-sm" @click="game_finished" :disabled="executed">
+          <button class="cu-btn bg-red text-white margin-top-sm" @click="clickToEnd()" :disabled="end_loading">
             <img src="https://img.shuimuai.com/m_duankainaohuan.png" class="cut_brain_icon" alt=""/>
             <text class="padding-lr cut_text text-sm">结束训练</text>
           </button>
@@ -26,7 +30,7 @@
       <van-row>
         <van-col span="8">
           <div class="flex flex-direction align-center justify-center" v-if="device_bg">
-            <img src="https://img.shuimuai.com/web/touhuanzhuangtai_2.png" alt="" class="device_img" />
+            <img src="https://img.shuimuai.com/web/touhuanzhuangtai_2.png" alt="" class="device_img"/>
             <text class="text-default">已经正确佩戴</text>
           </div>
           <div class="flex flex-direction align-center justify-center" v-else>
@@ -37,7 +41,8 @@
         <van-col span="8">
           <div class="flex flex-direction align-center justify-center">
             <view class="elc_power_container">
-              <img src="https://img.shuimuai.com/web/dianchi_3.png" alt="" :style="{ width: device_power + '%' }" class="device_elc" />
+              <img src="https://img.shuimuai.com/web/dianchi_3.png" alt="" :style="{ width: device_power + '%' }"
+                   class="device_elc"/>
             </view>
             <text class="text-default">脑机电量</text>
           </div>
@@ -45,7 +50,8 @@
         <van-col span="8">
           <div class="flex flex-direction align-center justify-center">
             <view class="elc_power_container">
-              <img src="https://img.shuimuai.com/web/dianchi_3.png" alt="" :style="{ width: toy_power + '%' }" class="device_elc" />
+              <img src="https://img.shuimuai.com/web/dianchi_3.png" alt="" :style="{ width: toy_power + '%' }"
+                   class="device_elc"/>
             </view>
             <text class="text-default">教具电量</text>
           </div>
@@ -208,6 +214,9 @@ export default {
   components: {
     mpvueEcharts,
   },
+  created() {
+    $this = this;
+  },
   data() {
     return {
       // 折线图
@@ -220,64 +229,28 @@ export default {
       device_power: 0,
       // 教具电量
       toy_power: 0,
-      // 使用类型: 1:次数 2:时间 0:未选择
-      mode: 0,
       //  蓝牙信号强度
       RSSI: 0,
-      game_status: 0,
-
       // 监听到的蓝牙数据
-      hexStr:"",
-
-      timeData: {},
-      mode_item: {},
-
-      user_info: {},
-      //设备值
-      deviceId: "",
-      _serviceId: "",
-      _characteristicId: "",
-
-      toy_index: 0,
-      toy_id: 0,
-      toy: {},
-      toy_hex: "",
-
-      play_time: 0,
-
+      hexStr: "",
       //实时的专注值和放松度
       online_att: 0,
       online_att_desc: "",
       online_med: 0,
       online_med_desc: "",
-
       //图标数据集合
       att_list: [],
       med_list: [],
       //和谐度
       amp_list: [],
-
       delta_list: [],
       theta_list: [],
       low_alphas: [],
       high_alphas: [],
       low_betas: [],
       high_betas: [],
-      cates: [],
-
       //保存的数据集合
-      game_datas: [],
-
-      //判断是否结束游戏
-      is_end: false,
-      executed: false,
-      //  消耗的时间
-      played_time: null,
-      played_time_text: "--:--",
-
-      //结束游戏时选择类型的时间
-      over_play_time: 0,
-
+      game_data: [],
       save_index: [
         "att",
         "med",
@@ -297,389 +270,357 @@ export default {
         "high_beta_basic",
         "low_gamma_basic",
         "middle_gamma_basic"
-      ]
+      ],
+      // 计费模式: 1:次数 2:时间 0:未选择
+      mode: 0,
+      // 结束游戏loading
+      end_loading: false,
+      // 判断是否已经结束游戏
+      is_end: false,
+      // 该局总时间:30分钟或10分钟
+      total_time: 0,
+      // 该局游戏剩余可以游玩的时间
+      play_time: 0,
+      // 本次游玩时间倒计时
+      countdown_text: "--:--",
     };
   },
+  onLoad(options) {
+    if (options.end === 1) {
+      $this.is_end = true;
+      $this.executed = true
+    }
+  },
+  // 加载完成后、后台切到前台或重新进入页面时触发
+  onShow() {
+    game_store.setters.setHideStatus(false);
+    $this.countdown_text = "--:--";
+    let game_status = game_store.getters.getGameStatus()*1;
+    if (game_status === 2) {
+      // 获取 拉到后台得时间
+      let $hide_time = game_store.getters.getHideTime()*1;
+      if ($hide_time) {
+        let store_time = game_store.getters.getPlayedTime()*1;
+        // 获取当前时间差
+        let $now = Math.round(new Date() / 1000) - $hide_time;
+        // 实际游玩时间
+        let played_time =  store_time + $now;
+        if (played_time >= $this.total_time) {
+          $this.endTheGame();
+        } else {
+          //重新设置游玩时间
+          game_store.setters.setPlayedTime(played_time);
+          // 可玩时间 (剩余时长)
+          $this.play_time = $this.total_time - played_time;
+          // 重新倒计时
+          $this.countdownInterval($this.play_time);
+        }
+      }
+    }
+  },
+  mounted() {
+    let game_status = game_store.getters.getGameStatus()*1;
+    if (game_status === 1) {
+      $this.is_end = false;
+      $this.end_loading = false;
+      $this.total_time = game_store.getters.getOverPlayTime();
+      // 筛选模式
+      $this.mode = game_store.getters.getMode() * 1;
+      // 可玩时间 (剩余时长)
+      $this.play_time = game_store.getters.getPlayTime();
+      // 开始游戏
+      $this.startTheGame();
+      // 打开蓝牙监听
+      $this.$connection.watchBLEstatus($this);
+    }
+    if (game_status === 3) {
+      $this.endTheGame();
+    }
+  },
+  // // 页面从前台切换到后台或者去别的页面时候触发的
+  // onHide() {
+  //   game_store.setters.setHideStatus(true);
+  //   let game_status = game_store.getters.getGameStatus()*1;
+  //   if (game_status === 2) {
+  //     // 存储时间
+  //     game_store.setters.setPlayedTime($this.total_time - $this.play_time);
+  //     // 四舍五入取整
+  //     game_store.setters.setHideTime(Math.round(new Date() / 1000));
+  //     clearInterval($timeout);
+  //   }
+  // },
+  // 页面卸载时候触发的生命周期
+  onUnload() {
+    LOG_DEBUG("训练页面被卸载!is_end:", $this.is_end, ",end_loading", $this.end_loading);
+    if (!$this.is_end) {
+      // 存储时间
+      game_store.setters.setPlayedTime($this.total_time - $this.play_time);
+      // 设置未结束游戏
+      $this.is_end = false;
+      $this.end_loading = false
+    } else {
+      $this.end_loading = true
+    }
+    game_store.setters.setHideStatus(true);
+    let game_status = game_store.getters.getGameStatus()*1;
+    if (game_status === 2) {
+      // 存储时间
+      game_store.setters.setPlayedTime($this.total_time - $this.play_time);
+      // 四舍五入取整
+      game_store.setters.setHideTime(Math.round(new Date() / 1000));
+    }
+    clearInterval($timeout);
+  },
   methods: {
-    //游戏结束方法
-    game_finished() {
-      if (!$this.executed) {
-        LOG_DEBUG("正在结束游戏");
-        let $code = ble_store.getters.getDeviceSn();
-        // 关闭脑控
-        $this.$connection.sendControlClose();
-
-        $this.$emit("closePop", true);
-
-        //设置游戏状态为 停止游戏
-        game_store.getters.getGameStatus() == 0
-          ? game_store.setters.setGameStatus(0)
-          : game_store.setters.setGameStatus(3);
-        //游戏结束重置游戏时间
-        wx.removeStorageSync("play_time");
-        //删除游戏专注数据
-        game_store.remover.rmGameAttMedDatas();
-        //删除隐藏时间
-        game_store.remover.rmHideTime();
-        //游戏结束重置游戏模式
-        // game_store.setters.setMode(0);
-        //删除游戏得id
-        // game_store.setters.removeToyHex();
-
-        // 结束游戏在提交报告函数里
-        $this.post_data();
-
-        //提交原始数据
-        // addRawData({
-        //   game_record_id: wx.getStorageSync('game_record_id'),
-        //   raw_data: wx.getStorageSync('origin_buffer')
-        // }).then(() => {
-        //   wx.removeStorageSync('origin_buffer')
-        // })
-
-        $this.game_over();
-        LOG_WECHAT($code, "结束训练record_id:", game_store.getters.getGameRecordId());
-
-        Toast.loading({
-          forbidClick: true,
-          mask: true,
-          message: "正在生成报告...",
-          duration: 2000,
-          onClose() {
-            $this.to_report();
-          }
-        });
+    /**
+     * 实时分析游戏数据
+     */
+    analysisGameData: function (hexStr) {
+      let $data = get_big_data(hexStr);
+      this.onlineAttMed($data);
+      this.doChartsData($data);
+    },
+    /**
+     * 实时的专注值和放松度
+     */
+    onlineAttMed: function ($data) {
+      $this.online_att = $data["att"];
+      if ($this.online_att >= 1 && $this.online_att < 40) {
+        $this.online_att_desc = "专注力不足";
+      } else if ($this.online_att < 60) {
+        $this.online_att_desc = "一般专注";
+      } else if ($this.online_att < 80) {
+        $this.online_att_desc = "高度专注";
+      } else if ($this.online_att <= 100) {
+        $this.online_att_desc = "深度专注";
+      }
+      $this.online_med = $data["med"];
+      if ($this.online_med >= 1 && $this.online_med < 40) {
+        $this.online_med_desc = "放松度不足";
+      } else if ($this.online_med < 60) {
+        $this.online_med_desc = "一般放松";
+      } else if ($this.online_med < 80) {
+        $this.online_med_desc = "高度放松";
+      } else if ($this.online_med <= 100) {
+        $this.online_med_desc = "深度放松";
       }
-      $this.executed = true;
     },
-    to_report() {
-      mpvue.redirectTo({
-        url: "/pages/games/report/main?id=" + game_store.getters.getGameRecordId() + "&size=" +game_store.getters.getGameDataLength(),
-        success() {
-          $this.timeData = {};
-          $this.attList = [];
-          $this.medList = [];
-          $this.ampList = [];
-          LOG_DEBUG("生成报告成功")
-        },
-      });
+    /**
+     * 大脑状态数据 与 基本脑波数据
+     */
+    doChartsData: function ($data) {
+      // 显示的数据
+      $this.att_list.push($data["att"]);
+      $this.med_list.push($data["med"]);
+      $this.amp_list.push(100 - Math.abs($data["att"] - $data["med"]));
+      $this.delta_list.push($data['delta']);
+      $this.theta_list.push($data['theta']);
+      $this.low_alphas.push($data['low_alpha']);
+      $this.high_alphas.push($data['high_alpha']);
+      $this.low_betas.push($data['low_beta']);
+      $this.high_betas.push($data['high_beta']);
+      game_store.setters.setGameDataLength($this.att_list.length);
+      if ($this.att_list.length > 15) {
+        // 图表显示数据过长时从第一个开始删除
+        $this.att_list.shift();
+        $this.med_list.shift();
+        $this.amp_list.shift();
+        $this.delta_list.shift();
+        $this.theta_list.shift();
+        $this.low_alphas.shift();
+        $this.high_alphas.shift();
+        $this.low_betas.shift();
+        $this.high_betas.shift();
+      }
+      //判断是否隐藏 隐藏则不绘画
+      let $hide_status = game_store.getters.getHideStatus();
+      if (!$hide_status) {
+        if (att_charts) {
+          // 通过专注放松度 画图
+          let $option = util.getLineOption($this.att_list, $this.med_list, $this.amp_list);
+          att_charts.setOption($option);
+        }
+        if (med_charts) {
+          // 通过基本脑波发送数据
+          let $base_option = util.getBaseOption($this.delta_list, $this.theta_list, $this.low_alphas, $this.high_alphas, $this.low_betas, $this.high_betas);
+          med_charts.setOption($base_option);
+        }
+      }
+      // 保存的数据
+      for (let i = 0; i < $this.save_index.length; i++) {
+        if ($this.game_data[$this.save_index[i]] === undefined) {
+          $this.game_data[$this.save_index[i]] = [];
+        }
+        $this.game_data[$this.save_index[i]].push($data[$this.save_index[i]])
+      }
     },
-    // 开始游戏
-    start_game() {
-      LOG_DEBUG("开始游戏")
+    /**
+     * 开始游戏
+     */
+    startTheGame() {
+      LOG_DEBUG("开始游戏");
+      game_store.setters.setGameStatus(2);
       wx.setKeepScreenOn({
         keepScreenOn: true,
       });
-      $this.$connection.sendAutoConnectRf(true, Math.round($this.played_time / 60));
+      $this.$connection.sendAutoConnectRf(true, Math.round($this.total_time / 60));
       $this.$connection.notifyDatas($this);
-      setTimeout(()=>{
+      setTimeout(() => {
         // 获取LED灯状态并设置
         let led_status = game_store.getters.getLED();
         LOG_DEBUG("开始游戏获取LED灯状态", led_status)
-        if(led_status){
+        if (led_status) {
           $this.$connection.SendLedOrder("01");
-        }else{
+        } else {
           $this.$connection.SendLedOrder("00");
         }
-      },500);
-      setTimeout(()=>{
+      }, 500);
+      setTimeout(() => {
         // 获取教具类型 发送陀螺仪开关指令
         let $toy_sn = ble_store.getters.getToySn().toUpperCase();
-        if($toy_sn.includes("SW") || $toy_sn.includes("KL") || $toy_sn.includes("SC")){
+        if ($toy_sn.includes("SW") || $toy_sn.includes("KL") || $toy_sn.includes("SC")) {
           // 设置教具为无运动状态 AA CC 03 00 00 00 34 CKS
           $this.$connection.SendMotionOrder("01");
         } else {
           $this.$connection.SendMotionOrder("00");
         }
-      },1000);
+      }, 1000);
       // 开始倒计时
+      $this.countdownInterval();
+    },
+    countdownInterval(){
       clearInterval($timeout)
       $timeout = setInterval(() => {
-        if ($this.played_time > 0) {
-          //自定义定时器
-          $this.played_time -= 1;
-          game_store.setters.setPlayedTime($this.played_time)
-          $this.played_time_text = formatPlaySeconds($this.played_time);
-        }
-        if ($this.played_time === 0) {
-          $this.played_time_text = "--:--";
-          $this.post_data();
-          //判断是否隐藏 隐藏则不绘画
-          $this.$connection.sendControlClose();
-          let $hide_status = game_store.getters.getHideStatus();
-          if (!$hide_status) {
-            $this.game_finished();
-          }
-          clearInterval($timeout)
+        if ($this.play_time > 0) {
+          // 自定义定时器
+          $this.play_time -= 1;
+          game_store.setters.setPlayedTime($this.total_time-$this.play_time);
+          $this.countdown_text = formatPlaySeconds($this.play_time);
+        } else {
+          clearInterval($timeout);
+          $this.endTheGame();
         }
-      }, 1000)
+      }, 1000);
     },
-
-    // ArrayBuffer转16进度字符串示例
-    ab2hex(buffer) {
-      var hexArr = Array.prototype.map.call(new Uint8Array(buffer), function (
-        bit
-      ) {
-        return ("00" + bit.toString(16)).slice(-2);
+    /**
+     * 点击结束游戏按钮
+     */
+    clickToEnd() {
+      if (!$this.end_loading && !$this.is_end) {
+        $this.endTheGame();
+      }
+    },
+    /**
+     * 游戏结束
+     */
+    endTheGame() {
+      if($this.end_loading || $this.is_end){
+        return;
+      }
+      $this.end_loading = true;
+      $this.is_end = true;
+      clearInterval($timeout);
+      LOG_DEBUG("正在结束游戏->endTheGame()");
+      // 关闭脑控
+      $this.$connection.sendControlClose();
+      // 结束游戏提交数据
+      $this.postGameData();
+      // 跳转到报告页
+      Toast.loading({
+        forbidClick: true,
+        mask: true,
+        message: "正在生成报告...",
+        duration: 2000,
+        onClose() {
+          $this.toReportPage();
+          $this.end_loading = false;
+        }
       });
-      return hexArr.join("");
+      let $code = ble_store.getters.getDeviceSn();
+      LOG_WECHAT($code, "结束训练record_id:", game_store.getters.getGameRecordId());
     },
-    // 往后端推送一次定时数据
-    post_data() {
-
-      let _game_datas = []
+    /**
+     * 往后端推送一次数据
+     */
+    postGameData() {
+      let post_data = [];
       for (let i = 0; i < this.save_index.length; i++) {
-        _game_datas[this.save_index[i]] = this.game_datas[this.save_index[i]].join(',')
+        post_data[this.save_index[i]] = this.game_data[this.save_index[i]].join(',');
       }
       //判断数据长度大于理想状态 需要对数组进行切割 逐个提交数据
-      let $params = {
+      let $dataParams = {
         game_record_id: game_store.getters.getGameRecordId(),
         //数据段长度小于65 单个提交
-        line: this.game_datas['att'].join(','),
-        line_med: this.game_datas['med'].join(','),
-        ..._game_datas,
+        line: this.game_data['att'].join(','),
+        line_med: this.game_data['med'].join(','),
+        ...post_data,
         sn: ble_store.getters.getDeviceSn()
       };
-      if (!$params.line) {
+      if (!$dataParams.line) {
         return false;
       }
-      gameAddLine($params).then((res) => {
+      gameAddLine($dataParams).then((res) => {
         let $data = res.data;
-        if ($data.code == 0) {
-          $this.game_datas = [];
+        if ($data.code*1 === 0) {
+          $this.game_data = [];
         }
       });
-    },
-    //  结束游戏
-    game_over() {
-      $this.over_play_time = game_store.getters.getOverPlayTime();
-      $this.played_time = $this.played_time >= 0 ? $this.played_time : 0;
       let $params = {
         game_record_id: game_store.getters.getGameRecordId(),
         type: $this.mode,
-        // play_time: $this.play_time - Math.abs($this.played_time),
-        play_time: $this.over_play_time - Math.abs($this.played_time),
+        play_time: $this.total_time - Math.abs($this.play_time),
       };
-      //
-      gameEnd($params).then((res) => {
-        let $data = res.data;
-        $this.played_time = null;
-        $this.played_time_text = "--:--";
-        game_store.setters.setPlayedTime(0);
-        //设置未结束游戏
-        $this.is_end = false;
-        $this.att_list = [];
-        $this.med_list = [];
-        $this.amp_list = [];
-        $this.delta_list = [];
-        $this.theta_list = [];
-        $this.low_alphas = [];
-        $this.high_alphas = [];
-        $this.low_betas = [];
-        $this.high_betas = [];
-        //游戏结束重置游戏卡卷类型时间和卡卷类型
-        wx.removeStorageSync("over_play_time");
-        game_store.setters.setMode(0);
+      gameEnd($params).then(() => {
+        $this.resetGameData();
       });
     },
-    analysisGameData: function(hexStr){
-      let $data = get_big_data(hexStr);
-      this.do_datas($data);
-    },
-    //  处理游戏中数据的方法
-    do_datas: function ($data) {
-      $this.online_att = $data["att"];
-      $this.online_med = $data["med"];
-
-      let $att_msg = "";
-      if ($data["att"] >= 1 && $data['att'] < 40) {
-        $att_msg = "专注力不足";
-      } else if ($data['att'] < 60) {
-        $att_msg = "一般专注";
-      } else if ($data['att'] < 80) {
-        $att_msg = "高度专注";
-      } else if ($data['att'] <= 100) {
-        $att_msg = "深度专注";
+    /**
+     * 重置游戏数据
+     */
+    resetGameData(){
+      //游戏结束重置游戏时间
+      wx.removeStorageSync("play_time");
+      //删除隐藏时间
+      game_store.remover.rmHideTime();
+      //游戏结束重置游戏模式
+      game_store.setters.setMode(0);
+      //设置游戏状态为 停止游戏
+      let game_status = game_store.getters.getGameStatus() * 1;
+      if (game_status === 1 || game_status === 2) {
+        game_store.setters.setGameStatus(3);
       }
-      $this.online_att_desc = $att_msg;
-
-      let $med_msg = "";
-      if ($data["med"] >= 1 && $data['med'] < 40) {
-        $med_msg = "放松度不足";
-      } else if ($data['med'] < 60) {
-        $med_msg = "一般放松";
-      } else if ($data['med'] < 80) {
-        $med_msg = "高度放松";
-      } else if ($data['med'] <= 100) {
-        $med_msg = "深度放松";
-      }
-      $this.online_med_desc = $med_msg;
-
-      //显示的数据
-      $this.att_list.push($data["att"]);
-      $this.med_list.push($data["med"]);
-      $this.amp_list.push(100 - Math.abs($data["att"] - $data["med"]));
-      $this.delta_list.push($data['delta']);
-      $this.theta_list.push($data['theta']);
-      $this.low_alphas.push($data['low_alpha']);
-      $this.high_alphas.push($data['high_alpha']);
-      $this.low_betas.push($data['low_beta']);
-      $this.high_betas.push($data['high_beta']);
-      game_store.setters.setGameDataLength($this.att_list.length);
-      if ($this.att_list.length > 15) {
-        $this.att_list.shift();
-        $this.med_list.shift();
-        $this.amp_list.shift();
-        $this.delta_list.shift();
-        $this.theta_list.shift();
-        $this.low_alphas.shift();
-        $this.high_alphas.shift();
-        $this.low_betas.shift();
-        $this.high_betas.shift();
-      }
-
-      //判断是否隐藏 隐藏则不绘画
-      let $hide_status = game_store.getters.getHideStatus();
-      if (!$hide_status) {
-        //LOG_DEBUG("专注放松度:",$this.att_list, $this.med_list, $this.amp_list)
-        if (att_charts) {
-          //通过专注放松度 画图
-          let $option = util.getLineOption($this.att_list, $this.med_list, $this.amp_list);
-          att_charts.setOption($option);
-        }
-        if (med_charts) {
-          //通过基本脑波发送数据
-          let $base_option = util.getBaseOption(
-            $this.delta_list,
-            $this.theta_list,
-            $this.low_alphas,
-            $this.high_alphas,
-            $this.low_betas,
-            $this.high_betas
-          );
-          med_charts.setOption($base_option);
-        }
-      }
-      //保存的数据
-      for (let i = 0; i < $this.save_index.length; i++) {
-        if (this.game_datas[$this.save_index[i]] == undefined) {
-          this.game_datas[$this.save_index[i]] = [];
-        }
-        this.game_datas[$this.save_index[i]].push($data[$this.save_index[i]])
-      }
-    },
-    //计算游玩时间
-    calThePlayedTime() {
-      //筛选模式
-      $this.mode = game_store.getters.getMode();
-
-      let mode_list = [
-        {
-          id: 1,
-          name: "次卡(10分钟)",
-        },
-        {
-          id: 2,
-          name: "会员时间消费",
-        },
-      ];
-
-      //可玩时间 (剩余时长)
+      // 重置状态
+      $this.is_end = false;
+      $this.att_list = [];
+      $this.med_list = [];
+      $this.amp_list = [];
+      $this.delta_list = [];
+      $this.theta_list = [];
+      $this.low_alphas = [];
+      $this.high_alphas = [];
+      $this.low_betas = [];
+      $this.high_betas = [];
+      //游戏结束重置游戏卡卷类型时间和卡卷类型
       $this.play_time = game_store.getters.getPlayTime();
-
-      //已经玩了多长时间
-      $this.played_time = game_store.getters.getPlayedTime()
-        ? game_store.getters.getPlayedTime()
-        : game_store.getters.getPlayTime();
-
-      $this.mode_item = {};
-      $this.mode_item = mode_list[$this.mode - 1];
+      game_store.setters.setPlayedTime(0);
+      game_store.setters.setOverPlayTime(0);
+      game_store.setters.setMode(0);
+      $this.countdown_text = "--:--";
     },
-    RandDomNum() {
-      $this.online_att = Math.round(Math.random() * 100);
-      $this.online_med = Math.round(Math.random() * 100);
-    }
-  },
-  mounted() {
-    $this.executed = false;
-    // $this.deviceId = "";
-    //$this.toy_UUID = "";
-    $this.deviceId = ble_store.getters.getDeviceId();
-    // setTimeout(() => {
-    $this.game_status = game_store.getters.getGameStatus();
-    // }, 1000)
-    //判断是否结束游戏
-    if ($this.is_end === true) {
-      $this.game_finished();
-    } else {
-      $this.calThePlayedTime();
-      $this.start_game();
-
-      //打开蓝牙监听
-      $this.$connection.watchBLEstatus($this);
-    }
-  },
-  created() {
-    $this = this;
-  },
-  // 加载完成后、后台切到前台或重新进入页面时触发
-  onShow() {
-    // 判断可游玩时间是否小于 0
-    game_store.setters.setHideStatus(false);
-    if ($this.played_time == 0) {
-      $this.game_finished();
-    } else {
-      wx.getSystemInfoAsync({
-        success(res) {
-          if (res.platform != "android") {
-            //获取 拉到后台得时间
-            let $hide_time = game_store.getters.getHideTime();
-            if ($hide_time) {
-              //获取当前时间
-              let $now = Math.round(new Date() / 1000);
-              //获得后台到当前时间差
-              let $residue = $now - $hide_time;
-              //将原来的游玩时间+上 时间差
-              let $played_time = $this.played_time * 1 - $residue * 1;
-
-              //判断时间差
-              if ($residue > $this.played_time) {
-                $this.game_finished();
-              }
-
-              //重新设置游玩时间
-              game_store.setters.setPlayedTime($played_time);
-              $this.calThePlayedTime();
-
-            }
-          }
+    /**
+     * 跳转到报告页
+     */
+    toReportPage() {
+      mpvue.redirectTo({
+        url: "/pages/games/report/main?id=" + game_store.getters.getGameRecordId() + "&size=" + game_store.getters.getGameDataLength(),
+        success() {
+          $this.attList = [];
+          $this.medList = [];
+          $this.ampList = [];
+          LOG_DEBUG("生成报告成功")
         },
       });
-    }
-  },
-  onLoad(options) {
-    if (options.end == 1) {
-      $this.is_end = true;
-      $this.executed = true
-    }
-  },
-  // 页面从前台切换到后台或者去别的页面时候触发的
-  onHide() {
-    game_store.setters.setHideStatus(true);
-    game_store.setters.setHideTime(Math.round(new Date() / 1000));
-  },
-  // 页面卸载时候触发的生命周期
-  onUnload() {
-    LOG_DEBUG("训练页面被卸载!");
-    if (!$this.is_end) {
-      //存储时间
-      game_store.setters.setPlayedTime($this.played_time);
-      //设置未结束游戏
-      $this.is_end = false;
-      $this.executed = false
-    } else {
-      $this.executed = true
-    }
+    },
   },
 };
 </script>
@@ -687,12 +628,11 @@ export default {
 <style scoped>
 #playing_container {
   width: 100%;
-  background: linear-gradient(
+  background: #46425e linear-gradient(
     0deg,
     rgba(40, 157, 206, 0.51),
     rgba(135, 145, 226, 0.26)
   );
-  background-color: #46425e;
   padding: 5px;
   height: 850px;
 }
@@ -907,14 +847,14 @@ export default {
 
 .online_att_txt {
   font-size: 40px;
-  font-family: Arial,serif;
+  font-family: Arial, serif;
   font-weight: bold;
   color: #FAB615;
 }
 
 .online_med_txt {
   font-size: 40px;
-  font-family: Arial,serif;
+  font-family: Arial, serif;
   font-weight: bold;
   color: #40FF31;
 }
@@ -949,4 +889,3 @@ export default {
   background-color: #00AD0E;
 }
 </style>
-

+ 0 - 0
src/pages/games/start/main.js → src/pages/games/play/main.js


+ 0 - 0
src/pages/games/start/main.json → src/pages/games/play/main.json


+ 3 - 13
src/store/game.js

@@ -1,5 +1,5 @@
 const setters = {
-  // 游戏状态: 0未开始 1游戏中 3游戏结束
+  // 游戏状态: 0未开始 1:开始游戏,2:游戏中 3:游戏结束
   setGameStatus(status) {
     wx.setStorageSync('game_status', status)
   },
@@ -17,6 +17,7 @@ const setters = {
   setOverPlayTime(param) {
     wx.setStorageSync('over_play_time', param)
   },
+  // 该局游戏剩余可以游玩的时间
   setPlayTime(param) {
     wx.setStorageSync('play_time', param)
   },
@@ -31,10 +32,6 @@ const setters = {
   setHideTime($param) {
     wx.setStorageSync('hide_time', $param)
   },
-  //记录游戏数据
-  setGameAttMedDatas($param) {
-    wx.setStorageSync('game_data', $param)
-  },
   // 脑机LED灯
   setLED(bool) {
     wx.setStorageSync('led_status', bool)
@@ -61,7 +58,7 @@ const getters = {
   getOverPlayTime() {
     return wx.getStorageSync('over_play_time')
   },
-  //该局游戏剩余可以游玩的时间
+  // 该局游戏剩余可以游玩的时间
   getPlayTime() {
     return wx.getStorageSync('play_time')
   },
@@ -77,10 +74,6 @@ const getters = {
   getHideTime() {
     return wx.getStorageSync('hide_time')
   },
-  //记录游戏数据
-  getGameAttMedDatas() {
-    return wx.getStorageSync('game_data')
-  },
   // 脑机LED灯
   getLED() {
     return wx.getStorageSync('led_status')
@@ -91,9 +84,6 @@ const getters = {
 }
 
 const remover = {
-  rmGameAttMedDatas() {
-    wx.removeStorageSync('game_data')
-  },
   rmHideTime() {
     wx.removeStorageSync('hide_time')
   },

+ 15 - 14
src/utils/connection.js

@@ -38,13 +38,13 @@ function ab2hex(buffer) {
  * todo 解析hex
  * @param hexStr
  * @param count
- * @param len
+ * @param start
  * @returns {string}
  */
-function doAnalysis(hexStr, count, len = 6) {
+function doAnalysis(hexStr, count, start = 6) {
   let $result = "";
-  //byte_count
-  let $str = hexStr.substring(len);
+  //从下标6开始往后截取
+  let $str = hexStr.substring(start);
   let $data = $str.substring(0, count * 2);
   for (let $i = 0; $i < $data.length; $i += 2) {
     let $code = parseInt($data.substring($i, $i+2), 16)
@@ -390,7 +390,7 @@ export default {
               // 不断获取教具电量
               let toy_interval = setInterval(() => {
                 let $game_status = game_store.getters.getGameStatus();
-                if($game_status !== 1){
+                if($game_status === 0 || $game_status === 3){
                   clearInterval(toy_interval);
                 } else{
                   that.SendOrder('8a', "获取教具电量");
@@ -404,7 +404,8 @@ export default {
           let $currentToyId = ble_store.getters.getCurrentToyId();
           let $mHexStr = hexStr.substring(hexStr.toUpperCase().indexOf("AADD87"))
           let $datas = doAnalysis($mHexStr, 10);
-          let $number = $datas.match(/\d+/)
+          let $number = $datas.match(/\d+/);
+          $number = $number ? $number : "00000000";
           let toy_list_pre = {'00': "", '01': "SW", '02': "KL", '04': "SC", '05': "PP", '06': "SU", '09': "UF", '12': "JM", '13': "QM"}
           let $sn = toy_list_pre[$currentToyId] + $number;
           $this.toy_sn = $sn;
@@ -430,8 +431,8 @@ export default {
             success(res) {
               if (res.confirm) {
                 let $game_status = game_store.getters.getGameStatus();
-                if ($game_status === 1) {
-                  $this.game_finished();
+                if ($game_status === 1 || $game_status === 2) {
+                  $this.endTheGame();
                 }
                 $this.connect_toy = 3;
               }
@@ -448,7 +449,7 @@ export default {
           LOG_DEBUG("监听佩戴正确:", hexStr.substring(0, 10), $this.device_bg);
           //游戏中模块
           let $game_status = game_store.getters.getGameStatus();
-          if ($game_status === 1) {
+          if ($game_status === 1 || $game_status === 2) {
             // 获取蓝牙低功耗设备(脑机)的信号强度
             wx.getBLEDeviceRSSI({
               deviceId: deviceId,
@@ -469,7 +470,7 @@ export default {
             message: '智脑机已关机,训练结束',
             onOpened() {
               setTimeout(() => {
-                $this.game_finished();
+                $this.endTheGame();
                 //clearInterval(control_close_intv)
               }, 2000)
             }
@@ -502,8 +503,8 @@ export default {
       if (res.connected === false) {
         //判断游戏是否游戏中
         let $game_status = game_store.getters.getGameStatus();
-        if ($game_status === 1) {
-          // $that.game_finished();
+        if ($game_status === 1 || $game_status === 2) {
+          // $that.endTheGame();
           Notify({
             type: 'danger',
             duration: 0,
@@ -544,7 +545,7 @@ export default {
     let $connect_count = 0;
     let $rec = setInterval(() => {
       let $game_status = game_store.getters.getGameStatus();
-      if ($game_status === 1) {
+      if ($game_status === 1 || $game_status === 2) {
         let $code = ble_store.getters.getDeviceSn();
         wx.createBLEConnection({
           deviceId: $deviceInfo.deviceId,
@@ -568,7 +569,7 @@ export default {
           }
         })
         if ($connect_count >= 3) {
-          $this.game_finished();
+          $this.endTheGame();
           clearInterval($rec)
         }
         $connect_count += 1;

+ 8 - 8
src/utils/game.js

@@ -84,7 +84,7 @@ function to_report() {
       //游戏结束重置游戏时间
       wx.removeStorageSync('play_time')
       //删除游戏专注数据
-      game_store.remover.rmGameAttMedDatas()
+      //game_store.remover.rmGameAttMedDatas()
       //游戏结束重置游戏模式
       game_store.setters.setMode(0)
       // //删除游戏得id
@@ -102,23 +102,23 @@ function to_report() {
  */
 export function formatPlaySeconds(value) {
   // 字符串转数字
-  var secondTime = parseInt(value); // 秒
-  var minuteTime = 0; // 分
+  let secondTime = parseInt(value); // 秒
+  let minuteTime = 0; // 分
   if (secondTime > 60) {
-    //如果秒数大于60,将秒数转换成整数
-    //获取分钟,除以60取整数,得到整数分钟
+    // 如果秒数大于60,将秒数转换成整数
+    // 获取分钟,除以60取整数,得到整数分钟
     minuteTime = parseInt(secondTime / 60);
     //获取秒数,秒数取佘,得到整数秒数
     secondTime = parseInt(secondTime % 60);
     //如果分钟大于60,将分钟转换成小时
   }
-  var result = "" + parseInt(secondTime);
+  let result = "" + parseInt(secondTime);
 
   if (minuteTime > 0) {
-    if (result.length == 1) {
+    if (result.length === 1) {
       result = "0" + result;
     }
-    if (parseInt(minuteTime).toString().length == 1) {
+    if (parseInt(minuteTime).toString().length === 1) {
       minuteTime = "0" + parseInt(minuteTime);
     }
     result = "" + minuteTime + ":" + result;