Compare commits
40 Commits
new-race-m
...
a885ce0dce
| Author | SHA1 | Date | |
|---|---|---|---|
| a885ce0dce | |||
| de7b44aa34 | |||
| 7cbdfdceab | |||
| 1ade861aae | |||
| 3293356668 | |||
| fefdb3527d | |||
| 076769c4d8 | |||
| 7d503c09e0 | |||
| 15a3e4120d | |||
| 192db06ac5 | |||
| 162a6820e9 | |||
| 852b2ce799 | |||
| 2b14274453 | |||
| 33d28c6a45 | |||
| 301fc4ee42 | |||
| 6596ea977d | |||
| f272df912b | |||
| cbb7bce746 | |||
| a5c6afe647 | |||
| 0b93d99688 | |||
| 3bc2e6c14b | |||
| ff64fab323 | |||
| 43123df18f | |||
| 860b01d5eb | |||
| 9c554a9366 | |||
| 8d918b008e | |||
| a66d8a03c6 | |||
| b168fd54a4 | |||
| da023c60f5 | |||
| cb4027418d | |||
| 96cc69f041 | |||
| 860cdbe332 | |||
| 8b9c862b96 | |||
| 19391808ef | |||
| 9cc6ef4b88 | |||
| fc14489ab3 | |||
| aba2da56d7 | |||
| 24314e5ec8 | |||
| 4dcfdeda68 | |||
| a6becf67ff |
23
src/App.vue
23
src/App.vue
@@ -21,7 +21,10 @@
|
|||||||
} = storeToRefs(store);
|
} = storeToRefs(store);
|
||||||
const {
|
const {
|
||||||
updateUser,
|
updateUser,
|
||||||
updateOnline
|
updateOnline,
|
||||||
|
updateDevice,
|
||||||
|
updateGame,
|
||||||
|
updateRoomNumber
|
||||||
} = store;
|
} = store;
|
||||||
|
|
||||||
watch(
|
watch(
|
||||||
@@ -46,6 +49,22 @@
|
|||||||
updateUser(value);
|
updateUser(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function onSessionKickedOut() {
|
||||||
|
uni.removeStorageSync(
|
||||||
|
`${uni.getAccountInfoSync().miniProgram.envVersion}_token`
|
||||||
|
);
|
||||||
|
updateUser();
|
||||||
|
updateDevice("", "");
|
||||||
|
updateOnline(false);
|
||||||
|
updateGame(false, "");
|
||||||
|
updateRoomNumber("");
|
||||||
|
uni.showModal({
|
||||||
|
title: "提示",
|
||||||
|
content: "账号已在其他设备登录",
|
||||||
|
showCancel: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
async function emitUpdateOnline() {
|
async function emitUpdateOnline() {
|
||||||
const data = await getDeviceBatteryAPI();
|
const data = await getDeviceBatteryAPI();
|
||||||
updateOnline(data.online);
|
updateOnline(data.online);
|
||||||
@@ -65,6 +84,7 @@
|
|||||||
onShow(() => {
|
onShow(() => {
|
||||||
uni.$on("update-user", emitUpdateUser);
|
uni.$on("update-user", emitUpdateUser);
|
||||||
uni.$on("update-online", emitUpdateOnline);
|
uni.$on("update-online", emitUpdateOnline);
|
||||||
|
uni.$on("session-kicked-out", onSessionKickedOut);
|
||||||
const token = uni.getStorageSync(
|
const token = uni.getStorageSync(
|
||||||
`${uni.getAccountInfoSync().miniProgram.envVersion}_token`
|
`${uni.getAccountInfoSync().miniProgram.envVersion}_token`
|
||||||
);
|
);
|
||||||
@@ -77,6 +97,7 @@
|
|||||||
onHide(() => {
|
onHide(() => {
|
||||||
uni.$off("update-user", emitUpdateUser);
|
uni.$off("update-user", emitUpdateUser);
|
||||||
uni.$off("update-online", emitUpdateOnline);
|
uni.$off("update-online", emitUpdateOnline);
|
||||||
|
uni.$off("session-kicked-out", onSessionKickedOut);
|
||||||
websocket.closeWebSocket();
|
websocket.closeWebSocket();
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
@@ -46,6 +46,8 @@ function request(method, url, data = {}) {
|
|||||||
`${uni.getAccountInfoSync().miniProgram.envVersion}_token`
|
`${uni.getAccountInfoSync().miniProgram.envVersion}_token`
|
||||||
);
|
);
|
||||||
uni.$emit("update-user");
|
uni.$emit("update-user");
|
||||||
|
reject({ type: "AUTH_INVALID", message });
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
if (message === "ROOM_FULL") {
|
if (message === "ROOM_FULL") {
|
||||||
resolve({full: true});
|
resolve({full: true});
|
||||||
|
|||||||
@@ -1,6 +1,4 @@
|
|||||||
export const audioFils = {
|
export const audioFils = {
|
||||||
tententen: "https://static.shelingxingqiu.com/shootmini/static/audio/tententen.mp3",
|
|
||||||
点击按钮: "https://static.shelingxingqiu.com/shootmini/static/audio/%E7%82%B9%E5%87%BB%E6%8C%89%E9%92%AE.mp3",
|
|
||||||
"20CM全环靶": "https://static.shelingxingqiu.com/shootmini/static/audio/20CM%E5%85%A8%E7%8E%AF%E9%9D%B6-%E6%97%A0%E6%95%88.mp3",
|
"20CM全环靶": "https://static.shelingxingqiu.com/shootmini/static/audio/20CM%E5%85%A8%E7%8E%AF%E9%9D%B6-%E6%97%A0%E6%95%88.mp3",
|
||||||
"40CM全环靶": "https://static.shelingxingqiu.com/shootmini/static/audio/40CM%E5%85%A8%E7%8E%AF%E9%9D%B6-%E6%97%A0%E6%95%88.mp3",
|
"40CM全环靶": "https://static.shelingxingqiu.com/shootmini/static/audio/40CM%E5%85%A8%E7%8E%AF%E9%9D%B6-%E6%97%A0%E6%95%88.mp3",
|
||||||
// 激光已校准:
|
// 激光已校准:
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ function handleTabClick(index) {
|
|||||||
v-for="(tab, index) in tabs"
|
v-for="(tab, index) in tabs"
|
||||||
:key="index"
|
:key="index"
|
||||||
class="tab-item"
|
class="tab-item"
|
||||||
@click="$clickSound(() => handleTabClick(index))"
|
@click="handleTabClick(index)"
|
||||||
:style="{
|
:style="{
|
||||||
width: index === 1 ? '36%' : '20%',
|
width: index === 1 ? '36%' : '20%',
|
||||||
}"
|
}"
|
||||||
|
|||||||
@@ -206,7 +206,7 @@ const goCalibration = async () => {
|
|||||||
<button hover-class="none" @click="() => (showHint = false)">
|
<button hover-class="none" @click="() => (showHint = false)">
|
||||||
取消
|
取消
|
||||||
</button>
|
</button>
|
||||||
<button hover-class="none" @click="$clickSound(cancelMatching)">确认</button>
|
<button hover-class="none" @click="cancelMatching">确认</button>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
<view v-if="hintType === 4" class="tip-content">
|
<view v-if="hintType === 4" class="tip-content">
|
||||||
|
|||||||
@@ -112,7 +112,7 @@ const createRoom = debounce(async () => {
|
|||||||
<text>40厘米全环靶</text>
|
<text>40厘米全环靶</text>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
<SButton :onClick="() => $clickSound(createRoom)">创建房间</SButton>
|
<SButton :onClick="createRoom">创建房间</SButton>
|
||||||
</view>
|
</view>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
|
|||||||
@@ -123,7 +123,7 @@ onBeforeUnmount(() => {
|
|||||||
</text>
|
</text>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
<button hover-class="none" @click="$clickSound(stopMatch)">取消匹配</button>
|
<button hover-class="none" @click="stopMatch">取消匹配</button>
|
||||||
</view>
|
</view>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
|
|||||||
13
src/main.js
13
src/main.js
@@ -2,25 +2,12 @@ import { createSSRApp } from 'vue'
|
|||||||
import { createPinia } from 'pinia'
|
import { createPinia } from 'pinia'
|
||||||
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
|
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
|
||||||
import App from './App.vue'
|
import App from './App.vue'
|
||||||
import audioManager from './audioManager'
|
|
||||||
|
|
||||||
export function createApp() {
|
export function createApp() {
|
||||||
const app = createSSRApp(App)
|
const app = createSSRApp(App)
|
||||||
const pinia = createPinia()
|
const pinia = createPinia()
|
||||||
pinia.use(piniaPluginPersistedstate)
|
pinia.use(piniaPluginPersistedstate)
|
||||||
app.use(pinia)
|
app.use(pinia)
|
||||||
|
|
||||||
/**
|
|
||||||
* 全局点击音效工具函数,用于在任意按钮/元素点击时自动播放音效。
|
|
||||||
* 用法:@click="$clickSound(handler)" 或 @click="$clickSound(() => doSomething())"
|
|
||||||
* @param {Function} handler - 原始点击回调函数(可选,点击时直接调用)
|
|
||||||
* @param {string} [soundKey='点击按钮'] - audioManager 中的音效 key
|
|
||||||
*/
|
|
||||||
app.config.globalProperties.$clickSound = (handler, soundKey = '点击按钮') => {
|
|
||||||
audioManager.play(soundKey);
|
|
||||||
if (typeof handler === 'function') handler();
|
|
||||||
};
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
app
|
app
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -443,7 +443,7 @@ onBeforeUnmount(() => {
|
|||||||
<PlayerSeats v-if="room.battleType === 2" :total="room.count || 10" :players="players"
|
<PlayerSeats v-if="room.battleType === 2" :total="room.count || 10" :players="players"
|
||||||
:removePlayer="removePlayer" :isOwner="owner.id === user.id" />
|
:removePlayer="removePlayer" :isOwner="owner.id === user.id" />
|
||||||
<view>
|
<view>
|
||||||
<SButton :disabled="!canClick" :onClick="() => $clickSound(getReady)">
|
<SButton :disabled="!canClick" :onClick="getReady">
|
||||||
{{
|
{{
|
||||||
allReady.value
|
allReady.value
|
||||||
? "即将进入对局..."
|
? "即将进入对局..."
|
||||||
|
|||||||
@@ -141,7 +141,7 @@ onLoad(async (options) => {
|
|||||||
<image src="../static/founded-room.png" mode="widthFix" />
|
<image src="../static/founded-room.png" mode="widthFix" />
|
||||||
<view>
|
<view>
|
||||||
<input placeholder="输入房间号" v-model="roomNumber" placeholder-style="color: #ccc" />
|
<input placeholder="输入房间号" v-model="roomNumber" placeholder-style="color: #ccc" />
|
||||||
<view @click="$clickSound(() => enterRoom(roomNumber))">进入房间</view>
|
<view @click="enterRoom(roomNumber)">进入房间</view>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
<view class="create-room">
|
<view class="create-room">
|
||||||
@@ -155,7 +155,7 @@ onLoad(async (options) => {
|
|||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
<view>
|
<view>
|
||||||
<SButton width="80%" :rounded="30" :onClick="() => $clickSound(onCreateRoom)">
|
<SButton width="80%" :rounded="30" :onClick="onCreateRoom">
|
||||||
创建约战房
|
创建约战房
|
||||||
</SButton>
|
</SButton>
|
||||||
</view>
|
</view>
|
||||||
|
|||||||
@@ -68,28 +68,29 @@ onShow(async () => {
|
|||||||
const token = uni.getStorageSync(`${env}_token`);
|
const token = uni.getStorageSync(`${env}_token`);
|
||||||
|
|
||||||
if (!user.value.id && !token) {
|
if (!user.value.id && !token) {
|
||||||
try {
|
// showModal.value = true;
|
||||||
const wxResult = await uni.login({provider: "weixin"});
|
// try {
|
||||||
const bindResult = await checkUserBindAPI(wxResult.code);
|
// const wxResult = await uni.login({provider: "weixin"});
|
||||||
if (bindResult.binded) {
|
// const bindResult = await checkUserBindAPI(wxResult.code);
|
||||||
const newResult = await uni.login({provider: "weixin"});
|
// if (bindResult.binded) {
|
||||||
const silentResult = await silentLoginAPI(newResult.code);
|
// const newResult = await uni.login({provider: "weixin"});
|
||||||
if (silentResult.user) updateUser(silentResult.user);
|
// const silentResult = await silentLoginAPI(newResult.code);
|
||||||
const devices = await getMyDevicesAPI();
|
// if (silentResult.user) updateUser(silentResult.user);
|
||||||
if (devices.bindings && devices.bindings.length) {
|
// const devices = await getMyDevicesAPI();
|
||||||
updateDevice(
|
// if (devices.bindings && devices.bindings.length) {
|
||||||
devices.bindings[0].deviceId,
|
// updateDevice(
|
||||||
devices.bindings[0].deviceName
|
// devices.bindings[0].deviceId,
|
||||||
);
|
// devices.bindings[0].deviceName
|
||||||
const data = await getDeviceBatteryAPI();
|
// );
|
||||||
updateOnline(data.online);
|
// const data = await getDeviceBatteryAPI();
|
||||||
}
|
// updateOnline(data.online);
|
||||||
} else {
|
// }
|
||||||
showModal.value = true;
|
// } else {
|
||||||
}
|
// showModal.value = true;
|
||||||
} catch (e) {
|
// }
|
||||||
console.log("检查绑定状态失败", e);
|
// } catch (e) {
|
||||||
}
|
// console.log("检查绑定状态失败", e);
|
||||||
|
// }
|
||||||
}
|
}
|
||||||
|
|
||||||
const promises = [getScoreRankList(undefined, 1, 10)];
|
const promises = [getScoreRankList(undefined, 1, 10)];
|
||||||
@@ -178,7 +179,7 @@ onShareTimeline(() => {
|
|||||||
v-else
|
v-else
|
||||||
src="https://static.shelingxingqiu.com/attachment/2026-01-04/dffohwtk1gwh0xfa6h.png"
|
src="https://static.shelingxingqiu.com/attachment/2026-01-04/dffohwtk1gwh0xfa6h.png"
|
||||||
mode="widthFix"
|
mode="widthFix"
|
||||||
@click="$clickSound(() => toPage('/pages/my-device'))"
|
@click="() => toPage('/pages/my-device')"
|
||||||
/>
|
/>
|
||||||
<block v-if="user.id">
|
<block v-if="user.id">
|
||||||
<text v-if="!device.deviceId">绑定我的智能弓</text>
|
<text v-if="!device.deviceId">绑定我的智能弓</text>
|
||||||
@@ -196,10 +197,10 @@ onShareTimeline(() => {
|
|||||||
</BubbleTip>
|
</BubbleTip>
|
||||||
</view>
|
</view>
|
||||||
<view class="play-card">
|
<view class="play-card">
|
||||||
<view @click="$clickSound(() => toPage('/pages/practise'))">
|
<view @click="() => toPage('/pages/practise')">
|
||||||
<image src="../static/my-practise.png" mode="widthFix"/>
|
<image src="../static/my-practise.png" mode="widthFix"/>
|
||||||
</view>
|
</view>
|
||||||
<view @click="$clickSound(() => toPage('/pages/friend-battle'))">
|
<view @click="() => toPage('/pages/friend-battle')">
|
||||||
<image src="../static/friend-battle.png" mode="widthFix"/>
|
<image src="../static/friend-battle.png" mode="widthFix"/>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
@@ -211,7 +212,7 @@ onShareTimeline(() => {
|
|||||||
/>
|
/>
|
||||||
<button
|
<button
|
||||||
class="into-btn"
|
class="into-btn"
|
||||||
@click="$clickSound(() => toPage('/pages/ranking'))"
|
@click="() => toPage('/pages/ranking')"
|
||||||
hover-class="none"
|
hover-class="none"
|
||||||
></button>
|
></button>
|
||||||
<view class="ranking-players" @click="toRankListPage">
|
<view class="ranking-players" @click="toRankListPage">
|
||||||
@@ -475,7 +476,7 @@ onShareTimeline(() => {
|
|||||||
|
|
||||||
.top-theme {
|
.top-theme {
|
||||||
position: absolute;
|
position: absolute;
|
||||||
display: flex;
|
display: none;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
<script setup>
|
<script setup>
|
||||||
import { ref, onMounted, onBeforeUnmount, watch, nextTick } from "vue";
|
import { ref, onMounted, onBeforeUnmount, watch } from "vue";
|
||||||
import { onLoad, onShow, onHide } from "@dcloudio/uni-app";
|
import { onLoad, onShow, onHide } from "@dcloudio/uni-app";
|
||||||
import Container from "@/components/Container.vue";
|
import Container from "@/components/Container.vue";
|
||||||
import BowTarget from "@/components/BowTarget.vue";
|
import BowTarget from "@/components/BowTarget.vue";
|
||||||
@@ -32,8 +32,6 @@ const halfTimeTip = ref(false);
|
|||||||
const halfRest = ref(false);
|
const halfRest = ref(false);
|
||||||
/** 控制设备离线提示弹窗的显示状态 */
|
/** 控制设备离线提示弹窗的显示状态 */
|
||||||
const showOfflineModal = ref(false);
|
const showOfflineModal = ref(false);
|
||||||
/** 记录每位玩家当前半场连续 X 环数,key 为 playerId,用于触发 tententen 音效 */
|
|
||||||
const xRingStreaks = ref({});
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 监听设备在线状态,大乱斗比赛进行中设备离线时弹窗提示用户
|
* 监听设备在线状态,大乱斗比赛进行中设备离线时弹窗提示用户
|
||||||
@@ -122,28 +120,6 @@ onLoad(async (options) => {
|
|||||||
// });
|
// });
|
||||||
});
|
});
|
||||||
|
|
||||||
/**
|
|
||||||
* 检测指定玩家连续 X 环是否达到 3 箭,达到则在环数播报入队后追加 tententen 音效
|
|
||||||
* @param {number|string} playerId - 本次射手的 ID(大乱斗中 ShootResult 保留 playerId)
|
|
||||||
* @param {boolean} isXRing - 本次射击是否为 X 环
|
|
||||||
*/
|
|
||||||
function checkAndPlayTententen(playerId, isXRing) {
|
|
||||||
if (!playerId) return;
|
|
||||||
const id = parseInt(playerId);
|
|
||||||
if (isXRing) {
|
|
||||||
xRingStreaks.value[id] = (xRingStreaks.value[id] || 0) + 1;
|
|
||||||
// 同一玩家连续 3 箭均为 X 环,追加到环数音效队列尾部播放
|
|
||||||
if (xRingStreaks.value[id] >= 3) {
|
|
||||||
xRingStreaks.value[id] = 0;
|
|
||||||
// nextTick 确保 HeaderProgress 的环数播报已入队后再追加 tententen,避免播放顺序颠倒
|
|
||||||
nextTick(() => audioManager.play("tententen", false));
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// 非 X 环则重置该玩家的连续计数
|
|
||||||
xRingStreaks.value[id] = 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function onReceiveMessage(msg) {
|
async function onReceiveMessage(msg) {
|
||||||
if (Array.isArray(msg)) return;
|
if (Array.isArray(msg)) return;
|
||||||
if (msg.type === MESSAGETYPESV2.BattleStart) {
|
if (msg.type === MESSAGETYPESV2.BattleStart) {
|
||||||
@@ -151,28 +127,7 @@ async function onReceiveMessage(msg) {
|
|||||||
halfRest.value = false;
|
halfRest.value = false;
|
||||||
recoverData(msg);
|
recoverData(msg);
|
||||||
} else if (msg.type === MESSAGETYPESV2.ShootResult) {
|
} else if (msg.type === MESSAGETYPESV2.ShootResult) {
|
||||||
// 更新前快照各玩家本轮已射箭数,用于事后识别本次射手
|
|
||||||
const curRound = playersScores.value[playersScores.value.length - 1] || {};
|
|
||||||
const prevCounts = {};
|
|
||||||
for (const pid of Object.keys(curRound)) {
|
|
||||||
prevCounts[pid] = (curRound[pid] || []).length;
|
|
||||||
}
|
|
||||||
recoverData(msg);
|
recoverData(msg);
|
||||||
// 对比更新后数据找出箭数增加的玩家(即本次射手),并读取其最新箭的 ring 数据
|
|
||||||
const newRound = playersScores.value[playersScores.value.length - 1] || {};
|
|
||||||
let shooterId = null;
|
|
||||||
let isXRing = false;
|
|
||||||
for (const pid of Object.keys(newRound)) {
|
|
||||||
const newLen = (newRound[pid] || []).length;
|
|
||||||
if (newLen > (prevCounts[pid] || 0)) {
|
|
||||||
shooterId = parseInt(pid);
|
|
||||||
const shot = newRound[pid][newLen - 1];
|
|
||||||
isXRing = !!(shot?.ringX && shot?.ring);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// 检测同一玩家三箭全 X 环,触发 tententen 音效
|
|
||||||
checkAndPlayTententen(shooterId, isXRing);
|
|
||||||
} else if (msg.type === MESSAGETYPESV2.HalfRest) {
|
} else if (msg.type === MESSAGETYPESV2.HalfRest) {
|
||||||
halfTimeTip.value = true;
|
halfTimeTip.value = true;
|
||||||
halfRest.value = true;
|
halfRest.value = true;
|
||||||
|
|||||||
@@ -130,7 +130,7 @@ onShow(() => {
|
|||||||
<template>
|
<template>
|
||||||
<Container title="弓箭绑定">
|
<Container title="弓箭绑定">
|
||||||
<view v-if="!device.deviceId" class="scan-code">
|
<view v-if="!device.deviceId" class="scan-code">
|
||||||
<button hover-class="none" @click="$clickSound(handleScan)">
|
<button hover-class="none" @click="handleScan">
|
||||||
<image src="../static/scan.png" mode="widthFix" />
|
<image src="../static/scan.png" mode="widthFix" />
|
||||||
</button>
|
</button>
|
||||||
<button hover-class="none" @click="showTip = true">
|
<button hover-class="none" @click="showTip = true">
|
||||||
@@ -269,7 +269,7 @@ onShow(() => {
|
|||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
<view :style="{ marginTop: '240rpx' }">
|
<view :style="{ marginTop: '240rpx' }">
|
||||||
<SButton :onClick="() => $clickSound(unbindDevice)" width="80vw" :rounded="40"
|
<SButton :onClick="unbindDevice" width="80vw" :rounded="40"
|
||||||
>解绑</SButton
|
>解绑</SButton
|
||||||
>
|
>
|
||||||
</view>
|
</view>
|
||||||
|
|||||||
@@ -114,7 +114,7 @@ onMounted(async () => {
|
|||||||
/>
|
/>
|
||||||
</view>
|
</view>
|
||||||
<template #bottom>
|
<template #bottom>
|
||||||
<SButton :rounded="50" :onClick="() => $clickSound(toEditPage)">下一步</SButton>
|
<SButton :rounded="50" :onClick="toEditPage">下一步</SButton>
|
||||||
</template>
|
</template>
|
||||||
</Container>
|
</Container>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
@@ -198,7 +198,7 @@ onLoad((options) => {
|
|||||||
</ScreenHint2>
|
</ScreenHint2>
|
||||||
</view>
|
</view>
|
||||||
<template #bottom>
|
<template #bottom>
|
||||||
<SButton :rounded="50" :onClick="() => $clickSound(onSubmit)">
|
<SButton :rounded="50" :onClick="onSubmit">
|
||||||
{{ currentGroup === groups ? "保存并查看分析" : "下一组" }}
|
{{ currentGroup === groups ? "保存并查看分析" : "下一组" }}
|
||||||
</SButton>
|
</SButton>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
@@ -329,10 +329,10 @@ onShareTimeline(() => {
|
|||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
<view>
|
<view>
|
||||||
<button hover-class="none" @click="$clickSound(toRecordPage)" class="image-btn">
|
<button hover-class="none" @click="toRecordPage" class="image-btn">
|
||||||
<image src="../static/record-btn.png" mode="widthFix" />
|
<image src="../static/record-btn.png" mode="widthFix" />
|
||||||
</button>
|
</button>
|
||||||
<button hover-class="none" @click="$clickSound(startScoring)" class="image-btn">
|
<button hover-class="none" @click="startScoring" class="image-btn">
|
||||||
<image src="../static/start-scoring.png" mode="widthFix" />
|
<image src="../static/start-scoring.png" mode="widthFix" />
|
||||||
</button>
|
</button>
|
||||||
</view>
|
</view>
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
<script setup>
|
<script setup>
|
||||||
import { ref, onMounted, onBeforeUnmount, nextTick } from "vue";
|
import { ref, onMounted, onBeforeUnmount } from "vue";
|
||||||
import { onLoad } from "@dcloudio/uni-app";
|
import { onLoad } from "@dcloudio/uni-app";
|
||||||
import Container from "@/components/Container.vue";
|
import Container from "@/components/Container.vue";
|
||||||
import ShootProgress from "@/components/ShootProgress.vue";
|
import ShootProgress from "@/components/ShootProgress.vue";
|
||||||
@@ -31,8 +31,6 @@ const { user } = storeToRefs(store);
|
|||||||
const start = ref(false);
|
const start = ref(false);
|
||||||
const scores = ref([]);
|
const scores = ref([]);
|
||||||
const total = 12;
|
const total = 12;
|
||||||
/** 当前练习中连续 X 环计数,用于触发 tententen 音效 */
|
|
||||||
const xRingStreak = ref(0);
|
|
||||||
const practiseResult = ref({});
|
const practiseResult = ref({});
|
||||||
const practiseId = ref("");
|
const practiseId = ref("");
|
||||||
const showGuide = ref(false);
|
const showGuide = ref(false);
|
||||||
@@ -48,7 +46,6 @@ onLoad((options) => {
|
|||||||
const onReady = async () => {
|
const onReady = async () => {
|
||||||
await startPractiseAPI();
|
await startPractiseAPI();
|
||||||
scores.value = [];
|
scores.value = [];
|
||||||
xRingStreak.value = 0; // 新一局开始,重置 X 环连续计数
|
|
||||||
start.value = true;
|
start.value = true;
|
||||||
audioManager.play("练习开始");
|
audioManager.play("练习开始");
|
||||||
};
|
};
|
||||||
@@ -58,33 +55,9 @@ const onOver = async () => {
|
|||||||
start.value = false;
|
start.value = false;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
|
||||||
* 检测连续 X 环是否达到 3 箭,达到则播放 tententen 音效
|
|
||||||
* @param {boolean} isXRing - 本次射击是否为 X 环
|
|
||||||
*/
|
|
||||||
function checkAndPlayTententen(isXRing) {
|
|
||||||
if (isXRing) {
|
|
||||||
xRingStreak.value += 1;
|
|
||||||
// 连续 3 箭均为 X 环,在环数播报入队后追加 tententen,避免播放顺序颠倒
|
|
||||||
if (xRingStreak.value >= 3) {
|
|
||||||
xRingStreak.value = 0;
|
|
||||||
nextTick(() => audioManager.play("tententen", false));
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// 非 X 环则重置连续计数
|
|
||||||
xRingStreak.value = 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function onReceiveMessage(msg) {
|
async function onReceiveMessage(msg) {
|
||||||
if (msg.type === MESSAGETYPESV2.ShootResult) {
|
if (msg.type === MESSAGETYPESV2.ShootResult) {
|
||||||
const prevLen = scores.value.length;
|
|
||||||
scores.value = msg.details;
|
scores.value = msg.details;
|
||||||
// 有新箭时取最后一箭判断是否 X 环并检测连续计数
|
|
||||||
if (scores.value.length > prevLen) {
|
|
||||||
const latestArrow = scores.value[scores.value.length - 1];
|
|
||||||
checkAndPlayTententen(!!(latestArrow?.ringX && latestArrow?.ring));
|
|
||||||
}
|
|
||||||
} else if (msg.type === MESSAGETYPESV2.BattleEnd) {
|
} else if (msg.type === MESSAGETYPESV2.BattleEnd) {
|
||||||
// setTimeout(onOver, 1500);
|
// setTimeout(onOver, 1500);
|
||||||
}
|
}
|
||||||
@@ -101,7 +74,6 @@ async function onComplete() {
|
|||||||
practiseResult.value = {};
|
practiseResult.value = {};
|
||||||
start.value = false;
|
start.value = false;
|
||||||
scores.value = [];
|
scores.value = [];
|
||||||
xRingStreak.value = 0; // 重新开始练习,重置 X 环连续计数
|
|
||||||
const result = await createPractiseAPI(total, 120);
|
const result = await createPractiseAPI(total, 120);
|
||||||
if (result) practiseId.value = result.id;
|
if (result) practiseId.value = result.id;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
<script setup>
|
<script setup>
|
||||||
import { ref, onMounted, onBeforeUnmount, nextTick } from "vue";
|
import { ref, onMounted, onBeforeUnmount } from "vue";
|
||||||
import Container from "@/components/Container.vue";
|
import Container from "@/components/Container.vue";
|
||||||
import ShootProgress from "@/components/ShootProgress.vue";
|
import ShootProgress from "@/components/ShootProgress.vue";
|
||||||
import BowTarget from "@/components/BowTarget.vue";
|
import BowTarget from "@/components/BowTarget.vue";
|
||||||
@@ -31,8 +31,6 @@ const { user } = storeToRefs(store);
|
|||||||
const start = ref(false);
|
const start = ref(false);
|
||||||
const scores = ref([]);
|
const scores = ref([]);
|
||||||
const total = 36;
|
const total = 36;
|
||||||
/** 当前练习中连续 X 环计数,用于触发 tententen 音效 */
|
|
||||||
const xRingStreak = ref(0);
|
|
||||||
const practiseResult = ref({});
|
const practiseResult = ref({});
|
||||||
const practiseId = ref("");
|
const practiseId = ref("");
|
||||||
const showGuide = ref(false);
|
const showGuide = ref(false);
|
||||||
@@ -47,7 +45,6 @@ onLoad((options) => {
|
|||||||
const onReady = async () => {
|
const onReady = async () => {
|
||||||
await startPractiseAPI();
|
await startPractiseAPI();
|
||||||
scores.value = [];
|
scores.value = [];
|
||||||
xRingStreak.value = 0; // 新一局开始,重置 X 环连续计数
|
|
||||||
start.value = true;
|
start.value = true;
|
||||||
audioManager.play("练习开始");
|
audioManager.play("练习开始");
|
||||||
};
|
};
|
||||||
@@ -57,33 +54,9 @@ const onOver = async () => {
|
|||||||
start.value = false;
|
start.value = false;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
|
||||||
* 检测连续 X 环是否达到 3 箭,达到则播放 tententen 音效
|
|
||||||
* @param {boolean} isXRing - 本次射击是否为 X 环
|
|
||||||
*/
|
|
||||||
function checkAndPlayTententen(isXRing) {
|
|
||||||
if (isXRing) {
|
|
||||||
xRingStreak.value += 1;
|
|
||||||
// 连续 3 箭均为 X 环,在环数播报入队后追加 tententen,避免播放顺序颠倒
|
|
||||||
if (xRingStreak.value >= 3) {
|
|
||||||
xRingStreak.value = 0;
|
|
||||||
nextTick(() => audioManager.play("tententen", false));
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// 非 X 环则重置连续计数
|
|
||||||
xRingStreak.value = 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function onReceiveMessage(msg) {
|
async function onReceiveMessage(msg) {
|
||||||
if (msg.type === MESSAGETYPESV2.ShootResult) {
|
if (msg.type === MESSAGETYPESV2.ShootResult) {
|
||||||
const prevLen = scores.value.length;
|
|
||||||
scores.value = msg.details;
|
scores.value = msg.details;
|
||||||
// 有新箭时取最后一箭判断是否 X 环并检测连续计数
|
|
||||||
if (scores.value.length > prevLen) {
|
|
||||||
const latestArrow = scores.value[scores.value.length - 1];
|
|
||||||
checkAndPlayTententen(!!(latestArrow?.ringX && latestArrow?.ring));
|
|
||||||
}
|
|
||||||
} else if (msg.type === MESSAGETYPESV2.BattleEnd) {
|
} else if (msg.type === MESSAGETYPESV2.BattleEnd) {
|
||||||
setTimeout(onOver, 1500);
|
setTimeout(onOver, 1500);
|
||||||
}
|
}
|
||||||
@@ -116,8 +89,7 @@ async function onComplete() {
|
|||||||
practiseResult.value = {};
|
practiseResult.value = {};
|
||||||
start.value = false;
|
start.value = false;
|
||||||
scores.value = [];
|
scores.value = [];
|
||||||
xRingStreak.value = 0; // 重新开始练习,重置 X 环连续计数
|
const result = await createPractiseAPI(total, 3600);
|
||||||
const result = await createPractiseAPI(total, 360);
|
|
||||||
if (result) practiseId.value = result.id;
|
if (result) practiseId.value = result.id;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -133,7 +105,7 @@ onMounted(async () => {
|
|||||||
});
|
});
|
||||||
uni.$on("socket-inbox", onReceiveMessage);
|
uni.$on("socket-inbox", onReceiveMessage);
|
||||||
uni.$on("share-image", onClickShare);
|
uni.$on("share-image", onClickShare);
|
||||||
const result = await createPractiseAPI(total, 360, targetType.value);
|
const result = await createPractiseAPI(total, 3600, targetType.value);
|
||||||
if (result) practiseId.value = result.id;
|
if (result) practiseId.value = result.id;
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -160,7 +132,7 @@ onBeforeUnmount(() => {
|
|||||||
<ShootProgress
|
<ShootProgress
|
||||||
:tips="`请连续射${total}支箭`"
|
:tips="`请连续射${total}支箭`"
|
||||||
:start="start"
|
:start="start"
|
||||||
:total="360"
|
:total="3600"
|
||||||
:onStop="onOver"
|
:onStop="onOver"
|
||||||
/>
|
/>
|
||||||
<view class="user-row">
|
<view class="user-row">
|
||||||
|
|||||||
@@ -281,27 +281,27 @@ onShow(async () => {
|
|||||||
<image
|
<image
|
||||||
src="../static/rank/battle1v1.svg"
|
src="../static/rank/battle1v1.svg"
|
||||||
mode="widthFix"
|
mode="widthFix"
|
||||||
@click.stop="$clickSound(() => toMatchPage(1, 2))"
|
@click.stop="() => toMatchPage(1, 2)"
|
||||||
/>
|
/>
|
||||||
<image
|
<image
|
||||||
src="../static/rank/battle2v2.svg"
|
src="../static/rank/battle2v2.svg"
|
||||||
mode="widthFix"
|
mode="widthFix"
|
||||||
@click.stop="$clickSound(() => toMatchPage(2, 4))"
|
@click.stop="() => toMatchPage(2, 4)"
|
||||||
/>
|
/>
|
||||||
<image
|
<image
|
||||||
src="../static/rank/battle3v3.svg"
|
src="../static/rank/battle3v3.svg"
|
||||||
mode="widthFix"
|
mode="widthFix"
|
||||||
@click.stop="$clickSound(() => toMatchPage(3, 6))"
|
@click.stop="() => toMatchPage(3, 6)"
|
||||||
/>
|
/>
|
||||||
<image
|
<image
|
||||||
src="../static/rank/battle5.svg"
|
src="../static/rank/battle5.svg"
|
||||||
mode="widthFix"
|
mode="widthFix"
|
||||||
@click.stop="$clickSound(() => toMatchPage(4, 5))"
|
@click.stop="() => toMatchPage(4, 5)"
|
||||||
/>
|
/>
|
||||||
<image
|
<image
|
||||||
src="../static/rank/battle10.svg"
|
src="../static/rank/battle10.svg"
|
||||||
mode="widthFix"
|
mode="widthFix"
|
||||||
@click.stop="$clickSound(() => toMatchPage(5, 10))"
|
@click.stop="() => toMatchPage(5, 10)"
|
||||||
/>
|
/>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
@@ -323,6 +323,7 @@ onShow(async () => {
|
|||||||
>
|
>
|
||||||
<text>{{ seasonName }}</text>
|
<text>{{ seasonName }}</text>
|
||||||
<image
|
<image
|
||||||
|
class="triangle-icon"
|
||||||
v-show="seasonData.length > 1"
|
v-show="seasonData.length > 1"
|
||||||
src="../static/rank/triangle.png"
|
src="../static/rank/triangle.png"
|
||||||
mode="widthFix"
|
mode="widthFix"
|
||||||
@@ -592,6 +593,7 @@ onShow(async () => {
|
|||||||
.ranking-season > image {
|
.ranking-season > image {
|
||||||
width: 12px;
|
width: 12px;
|
||||||
height: 12px;
|
height: 12px;
|
||||||
|
transform: rotateX(180deg);
|
||||||
}
|
}
|
||||||
|
|
||||||
.ranking-season > text {
|
.ranking-season > text {
|
||||||
@@ -807,18 +809,18 @@ onShow(async () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.season-list {
|
.season-list {
|
||||||
background-color: #000c;
|
background-color: rgba(0, 0, 0, 0.8);
|
||||||
border-radius: 15px;
|
border-radius: 15px;
|
||||||
color: #fff;
|
color: #fff;
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
padding: 5px 0;
|
padding: 12px 0;
|
||||||
position: absolute;
|
position: absolute;
|
||||||
width: 220rpx;
|
width: 220rpx;
|
||||||
height: auto;
|
height: auto;
|
||||||
max-height: 400rpx;
|
max-height: 400rpx;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
overflow-y: auto;
|
overflow-y: auto;
|
||||||
top: -44rpx;
|
top: -42rpx;
|
||||||
right: -30rpx;
|
right: -30rpx;
|
||||||
letter-spacing: 2px;
|
letter-spacing: 2px;
|
||||||
z-index: 10;
|
z-index: 10;
|
||||||
@@ -829,7 +831,7 @@ onShow(async () => {
|
|||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
word-break: keep-all;
|
word-break: keep-all;
|
||||||
padding: 20rpx 0;
|
padding: 20rpx 10rpx;
|
||||||
}
|
}
|
||||||
|
|
||||||
.season-list > view > text {
|
.season-list > view > text {
|
||||||
|
|||||||
@@ -49,8 +49,6 @@ const battleWay = ref(0);
|
|||||||
const lastToSomeoneShootKey = ref("");
|
const lastToSomeoneShootKey = ref("");
|
||||||
/** 控制设备离线提示弹窗的显示状态 */
|
/** 控制设备离线提示弹窗的显示状态 */
|
||||||
const showOfflineModal = ref(false);
|
const showOfflineModal = ref(false);
|
||||||
/** 记录每位玩家当前轮连续 X 环数,key 为 playerId,用于触发 tententen 音效 */
|
|
||||||
const xRingStreaks = ref({});
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 监听设备在线状态,比赛进行中设备离线时弹窗提示用户
|
* 监听设备在线状态,比赛进行中设备离线时弹窗提示用户
|
||||||
@@ -104,7 +102,8 @@ const recoverData = (battleInfo, {force = false, arrowOnly = false} = {}) => {
|
|||||||
let nextTips = redPlayer ? "请红队射箭" : "请蓝队射箭";
|
let nextTips = redPlayer ? "请红队射箭" : "请蓝队射箭";
|
||||||
if (force) nextTips += "重回";
|
if (force) nextTips += "重回";
|
||||||
if (
|
if (
|
||||||
battleInfo.current.playerId === user.value.id
|
battleInfo.current.playerId === user.value.id &&
|
||||||
|
redTeam.value.length > 1
|
||||||
) {
|
) {
|
||||||
nextTips += "你";
|
nextTips += "你";
|
||||||
}
|
}
|
||||||
@@ -233,27 +232,6 @@ function onNewRound(msg, prevRound) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 检测指定射手连续 X 环是否达到 3 箭,达到则在环数播报入队后追加 tententen 音效
|
|
||||||
* @param {number} shooterId - 本次射手的 ID(取自 currentShooterId.value)
|
|
||||||
* @param {boolean} isXRing - 本次射击是否为 X 环
|
|
||||||
*/
|
|
||||||
function checkAndPlayTententen(shooterId, isXRing) {
|
|
||||||
if (!shooterId) return;
|
|
||||||
if (isXRing) {
|
|
||||||
xRingStreaks.value[shooterId] = (xRingStreaks.value[shooterId] || 0) + 1;
|
|
||||||
// 同一玩家连续 3 箭均为 X 环,追加到环数音效队列尾部播放
|
|
||||||
if (xRingStreaks.value[shooterId] >= 3) {
|
|
||||||
xRingStreaks.value[shooterId] = 0;
|
|
||||||
// nextTick 确保 HeaderProgress 的环数播报已入队后再追加 tententen,避免播放顺序颠倒
|
|
||||||
nextTick(() => audioManager.play("tententen", false));
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// 非 X 环则重置该玩家的连续计数
|
|
||||||
xRingStreaks.value[shooterId] = 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function onReceiveMessage(msg) {
|
async function onReceiveMessage(msg) {
|
||||||
if (Array.isArray(msg)) return;
|
if (Array.isArray(msg)) return;
|
||||||
if (msg.type === MESSAGETYPESV2.BattleStart) {
|
if (msg.type === MESSAGETYPESV2.BattleStart) {
|
||||||
@@ -268,9 +246,6 @@ async function onReceiveMessage(msg) {
|
|||||||
} else if (msg.type === MESSAGETYPESV2.ShootResult) {
|
} else if (msg.type === MESSAGETYPESV2.ShootResult) {
|
||||||
showRoundTip.value = false;
|
showRoundTip.value = false;
|
||||||
recoverData(msg, {arrowOnly: true});
|
recoverData(msg, {arrowOnly: true});
|
||||||
// 检测同一玩家三箭全 X 环,触发 tententen 音效
|
|
||||||
// currentShooterId 在 ToSomeoneShoot 时写入,ShootResult 不会覆盖,可靠识别本次射手
|
|
||||||
checkAndPlayTententen(currentShooterId.value, !!(msg.shootData?.ringX && msg.shootData?.ring));
|
|
||||||
} else if (msg.type === MESSAGETYPESV2.NewRound) {
|
} else if (msg.type === MESSAGETYPESV2.NewRound) {
|
||||||
// 在进入延迟前先捕获当前轮次,供 onNewRound 使用,防止 800ms 内 ToSomeoneShoot 提前更新 currentRound 造成 Tip 展示错轮
|
// 在进入延迟前先捕获当前轮次,供 onNewRound 使用,防止 800ms 内 ToSomeoneShoot 提前更新 currentRound 造成 Tip 展示错轮
|
||||||
const prevRound = currentRound.value;
|
const prevRound = currentRound.value;
|
||||||
@@ -322,8 +297,6 @@ onBeforeUnmount(() => {
|
|||||||
const refreshTimer = ref(null);
|
const refreshTimer = ref(null);
|
||||||
onShow(async () => {
|
onShow(async () => {
|
||||||
if (battleId.value) {
|
if (battleId.value) {
|
||||||
// 延迟 300ms 等待网络恢复,避免小程序从后台切回时网络尚未就绪导致请求失败报错
|
|
||||||
await new Promise(resolve => setTimeout(resolve, 300));
|
|
||||||
const result = await getBattleAPI(battleId.value);
|
const result = await getBattleAPI(battleId.value);
|
||||||
if (!result) return;
|
if (!result) return;
|
||||||
if (result.status === 2) {
|
if (result.status === 2) {
|
||||||
|
|||||||
158
src/websocket.js
158
src/websocket.js
@@ -1,12 +1,22 @@
|
|||||||
import { MESSAGETYPES, getMessageTypeName } from "@/constants";
|
import { MESSAGETYPES, getMessageTypeName } from "@/constants";
|
||||||
|
import { getUserGameState } from "@/apis";
|
||||||
|
|
||||||
let socket = null;
|
let socket = null;
|
||||||
let heartbeatInterval = null;
|
let heartbeatInterval = null;
|
||||||
let reconnectTimer = null;
|
let reconnectTimer = null;
|
||||||
|
let manualClose = false;
|
||||||
|
let checkingSession = false;
|
||||||
|
let kickedOut = false;
|
||||||
|
let isConnecting = false;
|
||||||
|
|
||||||
/**
|
|
||||||
* 建立 WebSocket 连接
|
|
||||||
*/
|
|
||||||
function createWebSocket(token, onMessage) {
|
function createWebSocket(token, onMessage) {
|
||||||
|
if (!token) return;
|
||||||
|
if (kickedOut) kickedOut = false;
|
||||||
|
if (socket || isConnecting) return;
|
||||||
|
|
||||||
|
manualClose = false;
|
||||||
|
isConnecting = true;
|
||||||
|
|
||||||
let url = "wss://api.shelingxingqiu.com/socket";
|
let url = "wss://api.shelingxingqiu.com/socket";
|
||||||
try {
|
try {
|
||||||
const accountInfo = uni.getAccountInfoSync();
|
const accountInfo = uni.getAccountInfoSync();
|
||||||
@@ -20,42 +30,65 @@ function createWebSocket(token, onMessage) {
|
|||||||
case "trial": // 体验版
|
case "trial": // 体验版
|
||||||
url = "wss://apitest.shelingxingqiu.com/socket";
|
url = "wss://apitest.shelingxingqiu.com/socket";
|
||||||
break;
|
break;
|
||||||
case "release": // 正式版
|
case "trial":
|
||||||
|
url = "wss://apitest.shelingxingqiu.com/socket";
|
||||||
|
break;
|
||||||
|
case "release":
|
||||||
url = "wss://api.shelingxingqiu.com/socket";
|
url = "wss://api.shelingxingqiu.com/socket";
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
// 保持默认值
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error("获取环境信息失败,使用默认正式环境", e);
|
console.error("获取 WebSocket 环境信息失败,使用默认正式环境", e);
|
||||||
}
|
}
|
||||||
|
|
||||||
url += `?authorization=${token}`;
|
url += `?authorization=${token}`;
|
||||||
socket = uni.connectSocket({
|
const socketTask = uni.connectSocket({
|
||||||
url,
|
url,
|
||||||
success: () => {
|
success: () => {
|
||||||
console.log("websocket 连接成功");
|
console.log("WebSocket 已发起连接");
|
||||||
// 启动心跳
|
|
||||||
startHeartbeat(onMessage);
|
|
||||||
},
|
},
|
||||||
fail: () => {
|
fail: (err) => {
|
||||||
|
if (socket !== socketTask) return;
|
||||||
|
console.error("WebSocket 连接失败", err);
|
||||||
|
socket = null;
|
||||||
|
isConnecting = false;
|
||||||
reconnect(onMessage);
|
reconnect(onMessage);
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
// 接收消息
|
socket = socketTask;
|
||||||
uni.onSocketMessage((res) => {
|
|
||||||
|
socketTask.onOpen(() => {
|
||||||
|
if (socket !== socketTask) return;
|
||||||
|
console.log("WebSocket 连接成功");
|
||||||
|
isConnecting = false;
|
||||||
|
startHeartbeat(onMessage);
|
||||||
|
});
|
||||||
|
|
||||||
|
socketTask.onMessage((res) => {
|
||||||
|
if (socket !== socketTask) return;
|
||||||
|
|
||||||
const { data, event } = JSON.parse(res.data);
|
const { data, event } = JSON.parse(res.data);
|
||||||
if (event === "pong") return;
|
if (event === "pong") return;
|
||||||
if (data.type) {
|
if (data.type) {
|
||||||
console.log("收到消息:", getMessageTypeName(data.type), data.data);
|
console.log(
|
||||||
|
"收到 WebSocket 消息",
|
||||||
|
getMessageTypeName(data.type),
|
||||||
|
data.data
|
||||||
|
);
|
||||||
if (onMessage) onMessage({ ...(data.data || {}), type: data.type });
|
if (onMessage) onMessage({ ...(data.data || {}), type: data.type });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (onMessage && data.updates) onMessage(data.updates);
|
if (onMessage && data.updates) onMessage(data.updates);
|
||||||
const msg = data.updates[0];
|
const msg = data.updates[0];
|
||||||
if (msg) {
|
if (msg) {
|
||||||
console.log("收到消息:", getMessageTypeName(msg.constructor), msg);
|
console.log(
|
||||||
|
"收到 WebSocket 更新",
|
||||||
|
getMessageTypeName(msg.constructor),
|
||||||
|
msg
|
||||||
|
);
|
||||||
if (msg.constructor === MESSAGETYPES.RankUpdate) {
|
if (msg.constructor === MESSAGETYPES.RankUpdate) {
|
||||||
uni.setStorageSync("latestRank", msg.lvl);
|
uni.setStorageSync("latestRank", msg.lvl);
|
||||||
} else if (msg.constructor === MESSAGETYPES.LvlUpdate) {
|
} else if (msg.constructor === MESSAGETYPES.LvlUpdate) {
|
||||||
@@ -68,84 +101,109 @@ function createWebSocket(token, onMessage) {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// 错误处理
|
socketTask.onError((err) => {
|
||||||
uni.onSocketError((err) => {
|
if (socket !== socketTask) return;
|
||||||
console.error("WebSocket 错误", err);
|
console.error("WebSocket 错误", err);
|
||||||
reconnect(onMessage);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
uni.onSocketClose((result) => {
|
socketTask.onClose(async (result) => {
|
||||||
|
if (socket !== socketTask) return;
|
||||||
console.log("WebSocket 已关闭", result);
|
console.log("WebSocket 已关闭", result);
|
||||||
stopHeartbeat();
|
stopHeartbeat();
|
||||||
reconnect(onMessage);
|
socket = null;
|
||||||
|
isConnecting = false;
|
||||||
|
|
||||||
|
if (manualClose || kickedOut) return;
|
||||||
|
await handleUnexpectedClose(onMessage);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
async function handleUnexpectedClose(onMessage) {
|
||||||
* 重连机制
|
if (checkingSession || manualClose || kickedOut) return;
|
||||||
*/
|
|
||||||
function reconnect(onMessage) {
|
|
||||||
reconnectTimer && clearTimeout(reconnectTimer);
|
|
||||||
closeWebSocket(); // 确保关闭旧连接
|
|
||||||
|
|
||||||
const token = uni.getStorageSync(
|
const token = uni.getStorageSync(
|
||||||
`${uni.getAccountInfoSync().miniProgram.envVersion}_token`
|
`${uni.getAccountInfoSync().miniProgram.envVersion}_token`
|
||||||
);
|
);
|
||||||
if (!token) return;
|
if (!token) return;
|
||||||
|
|
||||||
|
checkingSession = true;
|
||||||
|
try {
|
||||||
|
await getUserGameState();
|
||||||
|
if (!manualClose && !kickedOut) reconnect(onMessage);
|
||||||
|
} catch (err) {
|
||||||
|
if (err?.type === "AUTH_INVALID") {
|
||||||
|
kickedOut = true;
|
||||||
|
manualClose = true;
|
||||||
|
reconnectTimer && clearTimeout(reconnectTimer);
|
||||||
|
uni.$emit("session-kicked-out");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!manualClose && !kickedOut) reconnect(onMessage);
|
||||||
|
} finally {
|
||||||
|
checkingSession = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function reconnect(onMessage) {
|
||||||
|
reconnectTimer && clearTimeout(reconnectTimer);
|
||||||
|
|
||||||
|
const token = uni.getStorageSync(
|
||||||
|
`${uni.getAccountInfoSync().miniProgram.envVersion}_token`
|
||||||
|
);
|
||||||
|
if (!token || manualClose || kickedOut || socket || isConnecting) return;
|
||||||
|
|
||||||
reconnectTimer = setTimeout(() => {
|
reconnectTimer = setTimeout(() => {
|
||||||
console.log("reconnecting...");
|
if (manualClose || kickedOut || socket || isConnecting) return;
|
||||||
|
console.log("WebSocket 正在重连...");
|
||||||
createWebSocket(token, onMessage);
|
createWebSocket(token, onMessage);
|
||||||
}, 1000);
|
}, 1000);
|
||||||
}
|
}
|
||||||
|
|
||||||
function closeWebSocket() {
|
function closeWebSocket(isManual = true) {
|
||||||
|
manualClose = isManual;
|
||||||
|
reconnectTimer && clearTimeout(reconnectTimer);
|
||||||
|
stopHeartbeat();
|
||||||
|
isConnecting = false;
|
||||||
|
|
||||||
if (socket) {
|
if (socket) {
|
||||||
reconnectTimer && clearTimeout(reconnectTimer);
|
const currentSocket = socket;
|
||||||
stopHeartbeat();
|
socket = null;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
socket.close();
|
currentSocket.close();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error("关闭WebSocket连接失败", err);
|
console.error("关闭 WebSocket 失败", err);
|
||||||
}
|
}
|
||||||
|
|
||||||
socket = null; // 清除socket引用
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function sendHeartbeat(onMessage) {
|
function sendHeartbeat(onMessage) {
|
||||||
uni.sendSocketMessage({
|
if (!socket) return;
|
||||||
|
|
||||||
|
const currentSocket = socket;
|
||||||
|
currentSocket.send({
|
||||||
data: JSON.stringify({ event: "ping", data: {} }),
|
data: JSON.stringify({ event: "ping", data: {} }),
|
||||||
success: () => {
|
success: () => {},
|
||||||
// console.log("发送心跳成功");
|
|
||||||
},
|
|
||||||
fail: (err) => {
|
fail: (err) => {
|
||||||
console.error("发送心跳失败", err);
|
if (socket !== currentSocket) return;
|
||||||
|
console.error("心跳发送失败", err);
|
||||||
stopHeartbeat();
|
stopHeartbeat();
|
||||||
closeWebSocket(); // 关闭失效的连接
|
closeWebSocket(false);
|
||||||
reconnect(onMessage); // 触发重连
|
reconnect(onMessage);
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 启动心跳
|
|
||||||
*/
|
|
||||||
function startHeartbeat(onMessage) {
|
function startHeartbeat(onMessage) {
|
||||||
stopHeartbeat(); // 防止重复启动
|
stopHeartbeat();
|
||||||
|
|
||||||
heartbeatInterval = setInterval(() => {
|
heartbeatInterval = setInterval(() => {
|
||||||
if (socket && socket.readyState === 1) {
|
if (socket) {
|
||||||
// 检查连接状态
|
|
||||||
sendHeartbeat(onMessage);
|
sendHeartbeat(onMessage);
|
||||||
}
|
}
|
||||||
}, 10000);
|
}, 10000);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 停止心跳
|
|
||||||
*/
|
|
||||||
function stopHeartbeat() {
|
function stopHeartbeat() {
|
||||||
if (heartbeatInterval) {
|
if (heartbeatInterval) {
|
||||||
clearInterval(heartbeatInterval);
|
clearInterval(heartbeatInterval);
|
||||||
|
|||||||
Reference in New Issue
Block a user