当前位置:   article > 正文

微信多人聊天及轮盘小游戏(websocket实现)_微信群聊小游戏 代码

微信群聊小游戏 代码

主要功能

  • socket建立连接成功提醒及反馈。
  • 房间内有人加入时提醒。
  • 房间内有人离开时提醒。
  • 房间内聊天消息的转发。
  • 房间内转盘游戏的状态同步。

概况:用户可选择 【创建房间】、【加入房间】两个选项,每个房间最多容纳8人同时游戏或聊天。

具体实现思路:客户端发起socket连接时路径会带上参数:gameRoomNum_OpenId_type,解释:(gameRoomNum:房间号;OpenId:用户openId,type:用户类型【0房主用户,1房客用户】),此参数会在后台作为session的唯一标识,后台的每个socket对应的session会放在一个Map中,其key为gameRoomNum_OpenId_type,value为socket的session。客户端与服务端定义好会话的code码,根据code码区分会话的类别。服务端主动给客户端发送消息时,遍历map中所有key,与指定客户端的gameRoomNum_OpenId_type一致时,获取该key对应的value,调用其session对应的sendText方法即可向客户端主动发送消息。

截图

下图简述:轮盘为房间内用户的头像及其名称(图片展示的是默认头像及默认提示字符),聊天框内会提示用户进入(不会提示用户离开。可以实现,但个人觉得不必要。实现了用户离开时轮盘会将该用户的头像与提示字符改为默认头像及默认提示字符)、用户在房间内的聊天信息等

代码

后台核心代码:

  1. @Slf4j
  2. @Component
  3. @ServerEndpoint(value = "/wsdemo/{gameRoomNum_OpenId_type}")
  4. public class MyWebSocket {
  5. private static int onlineCount = 0;
  6. private static Map<String, MyWebSocket> webSocketClientMap = new ConcurrentHashMap<>();
  7. private Session session;
  8. private String gameRoomNum_OpenId_type = "";
  9. @OnOpen
  10. public void onOpen(@PathParam(value = "gameRoomNum_OpenId_type") String param, Session session) {
  11. System.err.println("参数:" + param);
  12. gameRoomNum_OpenId_type = param;
  13. this.session = session;
  14. webSocketClientMap.put(param, this);
  15. addOnlineCount();
  16. System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
  17. try {
  18. sendMessage(session, "socket建立成功");
  19. } catch (Exception e) {
  20. System.out.println("IO异常");
  21. }
  22. }
  23. @OnClose
  24. public void onClose(Session session) {
  25. GameRoomService gameRoomService = SpringAware.getContext().getBean(GameRoomService.class);
  26. GameRoomFlowService gameRoomFlowService = SpringAware.getContext().getBean(GameRoomFlowService.class);
  27. for (String gameRoomNum_OpenId_type : webSocketClientMap.keySet()) {
  28. if (session.equals(webSocketClientMap.get(gameRoomNum_OpenId_type).getSession())) {
  29. System.err.println(gameRoomNum_OpenId_type + "的session移除");
  30. webSocketClientMap.remove(gameRoomNum_OpenId_type);
  31. subOnlineCount();
  32. System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
  33. }
  34. }
  35. /**
  36. * WQ
  37. * * 转盘游戏相关:
  38. * * 10 创建房间 {code:10,joinGameRoomNum:joinGameRoomNum,openId:roomOwnerOpenId,msg:'创建房间'}
  39. * * 11 加入房间 {code:11,joinGameRoomNum:joinGameRoomNum,openId:roomGuestOpenId,msg:'加入房间'}
  40. * * 12 房主离开房间 {code:12,joinGameRoomNum:joinGameRoomNum,openId:roomOwnerOpenId,msg:'房主离开房间'}
  41. * * 13 游客离开房间 {code:12,joinGameRoomNum:joinGameRoomNum,openId:roomGuestOpenId,msg:'游客离开房间'}
  42. * * 聊天相关:
  43. * * 20 向房间的消息框中发送消息 {code:20,joinGameRoomNum:joinGameRoomNum,openId:sendMsgOpenId,content:'消息内容',msg:'用户向房间内的其他用户发送消息'}
  44. * * 转盘相关:
  45. * * 30 用户点击了轮盘开始按钮 {code:30,joinGameRoomNum:joinGameRoomNum,openId:openId,flag:flag,msg:'房间内的玩家点击了转盘开始按钮'}
  46. */
  47. @OnMessage
  48. public void onMessage(String message, Session session) {
  49. System.out.println("有客户单发送消息:" + message);
  50. }
  51. @OnError
  52. public void onError(Session session, Throwable error) {
  53. System.out.println("发生错误");
  54. error.printStackTrace();
  55. }
  56. /**
  57. * WQ
  58. * 2022-06-19 8:34
  59. * 消息发送方法。
  60. * session:给该客户端发送消息
  61. * message:发送给客户端的消息内容
  62. */
  63. public void sendMessage(Session session, String message) {
  64. try {
  65. session.getBasicRemote().sendText(message);
  66. } catch (Exception e) {
  67. System.err.println("向客户端发送消息出错。" + e.getMessage());
  68. }
  69. }
  70. public static synchronized int getOnlineCount() {
  71. return onlineCount;
  72. }
  73. public static synchronized void addOnlineCount() {
  74. MyWebSocket.onlineCount++;
  75. }
  76. public static synchronized void subOnlineCount() {
  77. MyWebSocket.onlineCount--;
  78. }
  79. public Session getSession() {
  80. return session;
  81. }
  82. public void setSession(Session session) {
  83. this.session = session;
  84. }
  85. public static Map<String, MyWebSocket> getWebSocketClientMap() {
  86. return webSocketClientMap;
  87. }
  88. public static void setWebSocketClientMap(Map<String, MyWebSocket> webSocketClientMap) {
  89. MyWebSocket.webSocketClientMap = webSocketClientMap;
  90. }
  91. }

小程序端核心代码

  1. <template>
  2. <view style="overflow: hidden;">
  3. <!-- 房间创建 -->
  4. <view class='cu-load load-modal' v-if="loadModalCreateGameRoom">
  5. <view class='gray-text'>房间创建中...</view>
  6. </view>
  7. <!-- 房主离开模态框,只允许点击确定,后返回上一界面 -->
  8. <view :class="roomOwnerLeaveModal">
  9. <view class="cu-dialog">
  10. <view class="padding-xl" style="font-size: 32rpx;background-color: #fff;">
  11. <text class="text-bold text-black">房主已离开房间~</text>
  12. </view>
  13. <view class="cu-bar bg-white">
  14. <view class="action margin-0 flex-sub text-grey " @click="submitBackLastPage">
  15. 确定
  16. </view>
  17. </view>
  18. </view>
  19. </view>
  20. <view class="title bg-white text-center text-bold text-lg" style="width: 100%;">房间号: {{joinGameRoomNum}}</view>
  21. <!-- ======================================转盘 start============================================ -->
  22. <view style="position: relative; overflow: hidden;width: 100%;" class="bg-white">
  23. <view class="box bg-gradual-pink" :class="isStart?'start':''" :style="'transform: rotate('+deg+'deg)'">
  24. <view class="box_item" v-for="item in data" :key='item.id'>
  25. <view class="cu-avatar radius margin-left" :style="'background-image:url('+item.avatarImg+');'">
  26. <text style="margin-top: 120rpx;" class="text-sm">{{item.name}}</text>
  27. </view>
  28. </view>
  29. </view>
  30. <view class="active bg-gradual-red" @click="active">
  31. 开始
  32. </view>
  33. </view>
  34. <!-- ======================================转盘 end============================================ -->
  35. <view>
  36. <view class="heng"></view>
  37. </view>
  38. <!-- ======================================聊天相关 start============================================ -->
  39. <scroll-view class=" cu-chat bg-white shadow" scroll-y='true' style="border-radius: 20rpx;height: 400rpx;"
  40. :scroll-top="scrollTop">
  41. <view id="chat-box" class="cu-chat">
  42. <view v-if="contentList.length === 0" style="text-align: center;">
  43. <text style="" class="text-grey">-----暂无消息-----</text>
  44. </view>
  45. <view v-for="(item,index) in contentList" :key='index' v-else>
  46. <view class="cu-item" v-if="item.type === 1">
  47. <view class="cu-avatar radius" :style="'background-image:url('+item.avatarImg+');'">
  48. </view>
  49. <view class="main">
  50. <view class="content shadow">
  51. <text>{{item.content}}</text>
  52. </view>
  53. </view>
  54. <view class="date ">{{item.sendTime}}</view>
  55. </view>
  56. <view style="text-align: center;" v-if="item.type === 2">
  57. <view class="cu-info">
  58. <text>{{item.content}}({{item.sendTime}})</text>
  59. </view>
  60. </view>
  61. <view class="cu-item self" v-if="item.type === 0">
  62. <view class="main">
  63. <view class="content shadow">
  64. {{item.content}}
  65. </view>
  66. </view>
  67. <view class="cu-avatar radius" :style="'background-image:url('+item.avatarImg+');'"></view>
  68. <view class="date">{{item.sendTime}}</view>
  69. </view>
  70. </view>
  71. </view>
  72. </scroll-view>
  73. <view class="cu-bar input margin-sm" style="border-radius: 20rpx;">
  74. <input class="solid-bottom" maxlength="50" cursor-spacing="10" v-model="content"></input>
  75. <button class="cu-btn bg-green shadow" @click="syncRoomContent">发送</button>
  76. </view>
  77. <!-- ======================================聊天相关 end============================================ -->
  78. </view>
  79. </template>
  80. <script>
  81. import {
  82. request,
  83. websocketUrl
  84. } from "../../util/index";
  85. import {
  86. getRandomNum_AB,
  87. GL
  88. } from '../../util/rotaryTable'
  89. export default {
  90. data() {
  91. return {
  92. //=======================聊天 start============================
  93. content: '',
  94. contentList: [], //聊天框的内容集合
  95. scrollTop: 0, //滚动条距离顶部的距离
  96. //=======================聊天 end============================
  97. roomOwnerLeaveModal: 'cu-modal',
  98. loadModalCreateGameRoom: false,
  99. //=======================转盘相关 start============================
  100. deg: 22.5,
  101. isStart: false,
  102. flag: 0,
  103. roomOwnerUserInfo: {}, //当前房间的房主对象信息
  104. roomGuestUserInfoList: [], //当前房间的游客对象集合信息
  105. //=======================转盘相关 end============================
  106. //=======================webSocket相关 start============================
  107. userOpenId: uni.getStorageSync('userOpenId'),
  108. isOpenSocket: false, //已经打开socket
  109. socketTask: null, //socket连接
  110. type: -1, //类型。创建0 or加入1
  111. joinGameRoomNum: '', //房间号
  112. roomOwnerOpenId: '', //房主openId
  113. roomGuestOpenId: '', //房客们openId
  114. //=======================webSocket相关 end============================
  115. /*
  116. * 发送给服务器的消息格式定义:{code:10,joinGameRoomNum:joinGameRoomNum,openId:userOpenId,msg:''}
  117. * 标识:
  118. * 转盘游戏相关:
  119. * 10 创建房间 {code:10,joinGameRoomNum:joinGameRoomNum,openId:roomOwnerOpenId,msg:'创建房间'} 小程序主动发送给服务器
  120. * 11 加入房间 {code:11,joinGameRoomNum:joinGameRoomNum,openId:roomGuestOpenId,msg:'加入房间'} 小程序主动发送给服务器
  121. * 12 房主离开房间 {code:12,joinGameRoomNum:joinGameRoomNum,openId:roomOwnerOpenId,msg:'房主离开房间'} 服务器主动发送给小程序
  122. * 13 游客离开房间 {code:12,joinGameRoomNum:joinGameRoomNum,openId:roomGuestOpenId,msg:'游客离开房间'} 服务器主动发送给小程序
  123. * 聊天相关:
  124. * 20 向房间的消息框中发送消息 {code:20,joinGameRoomNum:joinGameRoomNum,openId:sendMsgOpenId,content:'',msg:'用户向房间内的其他用户发送消息'} 小程序主动发送给服务器
  125. * 转盘相关:
  126. * 30 用户点击了轮盘开始按钮 {code:30,joinGameRoomNum:joinGameRoomNum,openId:openId,flag:flag,msg:'房间内的玩家点击了转盘开始按钮'} 小程序主动发送给服务器
  127. */
  128. //建立连接时所带的参数。例:U594EW2V_oQqIy4z11-KEwSftcaz8GImDWFnQ_1:房间号_openId_房主0/游客1
  129. pathParam: '',
  130. //长连接的请求参数封装
  131. websocketReqParam: {
  132. code: 0,
  133. joinGameRoomNum: '',
  134. openId: '',
  135. msg: ''
  136. },
  137. //响应参数封装
  138. websocketRespParam: {}
  139. }
  140. },
  141. computed: {
  142. data() {
  143. //即将返回的结果集
  144. var itemList = []
  145. if (this.roomOwnerUserInfo.avatarImg !== undefined) {
  146. itemList.push({
  147. id: 1,
  148. name: this.roomOwnerUserInfo.nickName,
  149. avatarImg: this.roomOwnerUserInfo.avatarImg
  150. })
  151. }
  152. if (this.roomGuestUserInfoList.length > 0) {
  153. var itemListLength = itemList.length
  154. for (var i = 0; i < this.roomGuestUserInfoList.length; i++) {
  155. itemList.push({
  156. id: ++itemListLength,
  157. name: this.roomGuestUserInfoList[i].nickName,
  158. avatarImg: this.roomGuestUserInfoList[i].avatarImg
  159. })
  160. }
  161. }
  162. var itemListLength = itemList.length
  163. while (itemList.length < 8) {
  164. itemList.push({
  165. id: ++itemListLength,
  166. name: '谢谢惠顾',
  167. avatarImg: '../../static/svg/icon-no-guest.svg'
  168. })
  169. }
  170. return itemList
  171. }
  172. },
  173. onLoad(options) {
  174. var type = options.type
  175. if (type == 0) { //创建房间
  176. this.loadModalCreateGameRoom = true
  177. this.type = 0
  178. this.roomOwnerOpenId = uni.getStorageSync('userOpenId')
  179. //获取房间号
  180. var vm = this
  181. //此处用户授权小游戏时会给用户创建一个游戏房间,该用户就为该游戏房间的房主
  182. request('/getRoomNumByRoomOwnerOpenId', {
  183. roomOwnerOpenId: vm.roomOwnerOpenId
  184. }).then((data) => {
  185. vm.loadModalCreateGameRoom = false
  186. vm.joinGameRoomNum = data.gameRoomEntity.gameRoomNum
  187. //请求参数赋值
  188. vm.websocketReqParam = {
  189. code: 10,
  190. joinGameRoomNum: vm.joinGameRoomNum,
  191. openId: vm.roomOwnerOpenId,
  192. msg: '创建房间'
  193. }
  194. //建立连接时的路径参数赋值
  195. vm.pathParam = vm.joinGameRoomNum + '_' + uni.getStorageSync('userOpenId') + '_0'
  196. //建立socket连接
  197. vm.connectSocketInit()
  198. })
  199. } else if (type == 1) { //加入房间
  200. var vm = this
  201. vm.type = 1
  202. vm.joinGameRoomNum = options.joinGameRoomNum
  203. vm.roomGuestOpenId = uni.getStorageSync('userOpenId')
  204. //请求参数赋值
  205. this.websocketReqParam = {
  206. code: 11,
  207. joinGameRoomNum: vm.joinGameRoomNum,
  208. openId: vm.roomGuestOpenId,
  209. msg: '加入房间'
  210. }
  211. //建立连接时的路径参数赋值
  212. vm.pathParam = vm.joinGameRoomNum + '_' + uni.getStorageSync('userOpenId') + '_1'
  213. //建立socket连接
  214. this.connectSocketInit()
  215. }
  216. },
  217. onUnload() {
  218. this.closeSocket()
  219. },
  220. methods: {
  221. //房主离开了此房间,点击确定按钮,返回上一界面(相当于点击左上角返回箭头)
  222. submitBackLastPage() {
  223. uni.navigateBack({});
  224. },
  225. //===========================webSocket相关 start==================================
  226. // 进入这个页面的时候创建websocket连接【整个页面随时使用】
  227. connectSocketInit() {
  228. var vm = this
  229. // 创建一个this.socketTask对象【发送、接收、关闭socket都由这个对象操作】
  230. this.socketTask = uni.connectSocket({
  231. // 【非常重要】必须确保你的服务器是成功的,如果是手机测试千万别使用ws://127.0.0.1:9099【特别容易犯的错误】
  232. url: `${websocketUrl}/${vm.pathParam}`,
  233. success(data) {
  234. console.log("websocket连接成功", data);
  235. },
  236. });
  237. // 消息的发送和接收必须在正常连接打开中,才能发送或接收【否则会失败】
  238. this.socketTask.onOpen((res) => {
  239. console.log("WebSocket连接正常打开中...!");
  240. vm.isOpenSocket = true;
  241. // 注:只有连接正常打开中 ,才能正常成功发送消息
  242. this.socketTask.send({
  243. data: JSON.stringify(vm.websocketReqParam),
  244. async success() {
  245. console.log("消息发送成功", vm.type);
  246. },
  247. });
  248. // 注:只有连接正常打开中 ,才能正常收到消息
  249. this.socketTask.onMessage((res) => {
  250. console.log("收到服务器内容:", res.data)
  251. vm.handleServerMsg(res.data)
  252. });
  253. })
  254. // 这里仅是事件监听【如果socket关闭了会执行】
  255. this.socketTask.onClose(() => {
  256. console.log("已经被关闭了")
  257. })
  258. },
  259. // 关闭websocket【离开这个页面的时候执行关闭】
  260. closeSocket() {
  261. var vm = this
  262. if (vm.socketTask) {
  263. vm.socketTask.close({
  264. success(res) {
  265. vm.isOpenSocket = false;
  266. console.log("关闭成功", res)
  267. },
  268. fail(err) {
  269. console.log("关闭失败", err)
  270. }
  271. })
  272. } else {
  273. console.log('vm.socketTask为null,无需关闭');
  274. }
  275. },
  276. //服务器端消息处理
  277. handleServerMsg(serverMsg) {
  278. //转成json对象
  279. var serverMsgJson = JSON.parse(serverMsg)
  280. if (serverMsgJson.code === 0) {
  281. var dataObj = serverMsgJson.data
  282. switch (dataObj.type) {
  283. case '010': //房主创建房间的响应
  284. // console.log('房主创建房间的响应', dataObj);
  285. uni.showToast({
  286. title: '创建房间成功',
  287. })
  288. this.roomOwnerUserInfo = dataObj.roomOwnerUserInfo
  289. break;
  290. case '011': //游客加入房间的响应 聊天框中给出提示信息
  291. this.roomOwnerUserInfo = dataObj.roomOwnerUserInfo
  292. this.roomGuestUserInfoList = dataObj.roomGuestUserInfo
  293. var newGuestNickName = dataObj.newGuestUserInfo.nickName
  294. //聊天框中给出有新人加入的提示信息
  295. this.contentList.push({
  296. type: 2,
  297. content: `欢迎 ${newGuestNickName} 加入房间~`,
  298. sendTime: this.getHms()
  299. })
  300. this.autoToBottom()
  301. break;
  302. case '012': //房主离开房间的响应
  303. //弹出模态框,只允许点击离开按钮
  304. this.roomOwnerLeaveModal = 'cu-modal show'
  305. break;
  306. case '013': //游客离开房间的响应
  307. //将游客集合中的该游客移除
  308. for (var i = 0; i < this.roomGuestUserInfoList.length; i++) {
  309. if (this.roomGuestUserInfoList[i].openId === dataObj.openId) {
  310. this.roomGuestUserInfoList.splice(i, 1);
  311. }
  312. }
  313. break;
  314. case '020': //同步聊天内容 "content":"111222测试333","openId":"oQqIy4z11-KEwSftcaz8GImDWFnQ"
  315. //同步聊天内容
  316. var type = 1 // 用户类型。0 自身发送(在发送按钮触发的方法中涉及),1 他人发送(此处为接收到他人的消息,故都是1)
  317. var avatarImg = '' //用户头像
  318. for (var i = 0; i < this.roomGuestUserInfoList.length; i++) {
  319. if (this.roomGuestUserInfoList[i].openId === dataObj.openId) {
  320. avatarImg = this.roomGuestUserInfoList[i].avatarImg
  321. }
  322. }
  323. if (avatarImg === '') {
  324. avatarImg = this.roomOwnerUserInfo.avatarImg
  325. }
  326. this.contentList.push({
  327. type: type,
  328. content: dataObj.content,
  329. avatarImg: avatarImg,
  330. sendTime: dataObj.sendTime
  331. })
  332. this.autoToBottom()
  333. break;
  334. case '030': //同步转盘状态
  335. //同步玩家转盘状态
  336. this.flag = dataObj.flag
  337. this.activeAuto(this.flag)
  338. var gamingNickName = ''
  339. for (var i = 0; i < this.roomGuestUserInfoList.length; i++) {
  340. if (this.roomGuestUserInfoList[i].openId === dataObj.openId) {
  341. gamingNickName = this.roomGuestUserInfoList[i].nickName
  342. }
  343. }
  344. uni.showToast({
  345. title: `玩家 ${gamingNickName} 已启动转盘~`,
  346. icon: 'none'
  347. })
  348. break;
  349. }
  350. } else {
  351. console.log('服务器向客户端发送的消息出错。', serverMsg);
  352. }
  353. },
  354. //告诉房间内的其他玩家,房间内有玩家点击了 开始 按钮
  355. tellOtherGuestAndOwnerActive() {
  356. var msg = {
  357. code: 30,
  358. joinGameRoomNum: this.joinGameRoomNum,
  359. openId: uni.getStorageSync('userOpenId'),
  360. flag: this.flag,
  361. msg: '房间内的玩家点击了转盘开始按钮'
  362. }
  363. if (this.isOpenSocket) {
  364. // websocket的服务器的原理是:发送一次消息,同时返回一组数据【否则服务器会进去死循环崩溃】
  365. this.socketTask.send({
  366. data: JSON.stringify(msg),
  367. async success() {
  368. console.log("消息发送成功");
  369. },
  370. });
  371. }
  372. },
  373. //聊天框消息发送
  374. syncRoomContent() {
  375. if (this.content === '') {
  376. uni.showToast({
  377. title: '内容不可为空',
  378. icon: 'none'
  379. })
  380. return
  381. }
  382. var msg = {
  383. code: 20,
  384. joinGameRoomNum: this.joinGameRoomNum,
  385. openId: uni.getStorageSync('userOpenId'),
  386. content: this.content,
  387. msg: '房间内的用户发送消息'
  388. }
  389. var avatarImg = '' //用户头像
  390. for (var i = 0; i < this.roomGuestUserInfoList.length; i++) {
  391. if (this.roomGuestUserInfoList[i].openId === msg.openId) {
  392. avatarImg = this.roomGuestUserInfoList[i].avatarImg
  393. }
  394. }
  395. if (avatarImg === '') {
  396. avatarImg = this.roomOwnerUserInfo.avatarImg
  397. }
  398. var vm = this
  399. if (this.isOpenSocket) {
  400. // websocket的服务器的原理是:发送一次消息,同时返回一组数据【否则服务器会进去死循环崩溃】
  401. this.socketTask.send({
  402. data: JSON.stringify(msg),
  403. async success() {
  404. //写入消息框内
  405. vm.contentList.push({
  406. type: 0,
  407. content: vm.content,
  408. avatarImg: avatarImg,
  409. sendTime: vm.getHms()
  410. })
  411. },
  412. complete() {
  413. console.log('消息发送,complete()');
  414. //输入框内容重置
  415. vm.content = ''
  416. }
  417. });
  418. } else {
  419. uni.showToast({
  420. title: '与服务器断连',
  421. icon: 'none'
  422. })
  423. }
  424. this.autoToBottom()
  425. },
  426. //自动滚到最底部
  427. autoToBottom() {
  428. var vm = this
  429. //设置滚动条在最底部
  430. wx.createSelectorQuery().select('#chat-box').boundingClientRect(function(rect) {
  431. //滚动的高度=scroll-view内view的高度
  432. vm.scrollTop = rect.height
  433. }).exec()
  434. },
  435. //获取当前的时分秒
  436. getHms() {
  437. var nowDate = new Date();
  438. var hours = nowDate.getHours(); //获取小时
  439. var minutes = nowDate.getMinutes(); //获取分
  440. return hours + ":" + minutes
  441. },
  442. //===========================webSocket相关 end==================================
  443. //===========================轮盘相关 start==================================
  444. //点击开始按钮触发的方法
  445. active() {
  446. //获取概率 (每个人概率相同)
  447. const map = new Map()
  448. var probability = 1 / (this.roomGuestUserInfoList.length + 1)
  449. map.set(1, probability)
  450. for (var i = 1; i <= this.roomGuestUserInfoList.length; i++) {
  451. map.set(i + 1, probability)
  452. }
  453. //若轮盘正在转,则不可点击,直接返回
  454. if (this.isStart) {
  455. return
  456. }
  457. this.isStart = true
  458. // this.flag=getRandomNum_AB(1,8)
  459. // 随机生成 1 ~ 9 之间的数(不包含9)
  460. let gl = new GL({
  461. min: 1,
  462. max: 9,
  463. fenpei: map
  464. });
  465. this.flag = gl.random()
  466. // 指定奖项
  467. this.start(this.flag)
  468. //通知其他玩家
  469. this.tellOtherGuestAndOwnerActive()
  470. },
  471. //其他玩家点击了,这边需要同步的方法
  472. activeAuto() {
  473. this.isStart = true
  474. // 指定奖项
  475. this.start(this.flag)
  476. },
  477. start(n) {
  478. // 获取旋转角度
  479. let deg = 1080 - (45 * n) + 22.5
  480. this.deg += deg
  481. setTimeout(() => {
  482. this.isStart = false
  483. let title = this.data[this.flag - 1].name
  484. uni.showModal({
  485. title: '提示',
  486. content: title,
  487. success: (res) => {
  488. this.deg = 22.5
  489. // if (res.confirm) {
  490. // console.log('用户点击确定');
  491. // this.deg= 21
  492. // } else if (res.cancel) {
  493. // console.log('用户点击取消');
  494. // }
  495. }
  496. });
  497. }, 3200)
  498. },
  499. //===========================轮盘相关 end==================================
  500. },
  501. }
  502. </script>
  503. <style lang="less" scoped>
  504. .active {
  505. position: absolute;
  506. top: 50%;
  507. left: 50%;
  508. width: 150rpx;
  509. height: 150rpx;
  510. // background-color: #DD524D;
  511. transform: translate(-50%, -50%);
  512. line-height: 150rpx;
  513. text-align: center;
  514. border-radius: 50%;
  515. color: #fff;
  516. &::before {
  517. content: '';
  518. width: 0;
  519. height: 0;
  520. border-left: 30rpx solid transparent;
  521. border-right: 30rpx solid transparent;
  522. border-bottom: 60rpx solid #DD524D;
  523. position: absolute;
  524. top: -40rpx;
  525. left: 50%;
  526. transform: translateX(-50%);
  527. }
  528. }
  529. .start {
  530. transition: all 3.5s cubic-bezier(0.09, 0.99, 0.72, 1);
  531. }
  532. .box {
  533. position: relative;
  534. background-color: #007AFF;
  535. width: 700rpx;
  536. height: 700rpx;
  537. border-radius: 50%;
  538. margin: 50rpx auto;
  539. overflow: hidden;
  540. border: 1px solid #FFFFFF;
  541. .box_item {
  542. &::after {
  543. position: absolute;
  544. content: '';
  545. height: 100%;
  546. width: 2rpx;
  547. right: 0;
  548. // transform: translateX(50%);
  549. background-color: #FFFFFF;
  550. transform-origin: 50% 50%;
  551. transform: rotate(22.5deg) translateX(5%);
  552. }
  553. position: absolute;
  554. top: 0;
  555. left: 275rpx;
  556. width: 150rpx;
  557. height: 350rpx;
  558. transform-origin: 50% 100%;
  559. text-align: center;
  560. line-height: 140rpx;
  561. &:nth-child(2) {
  562. transform: rotate(45deg);
  563. }
  564. &:nth-child(3) {
  565. transform: rotate(90deg);
  566. }
  567. &:nth-child(4) {
  568. transform: rotate(135deg);
  569. }
  570. &:nth-child(5) {
  571. transform: rotate(180deg);
  572. }
  573. &:nth-child(6) {
  574. transform: rotate(225deg);
  575. }
  576. &:nth-child(7) {
  577. transform: rotate(270deg);
  578. }
  579. &:nth-child(8) {
  580. transform: rotate(315deg);
  581. }
  582. }
  583. }
  584. .heng {
  585. background: #E0E3DA;
  586. width: 100%;
  587. height: 5rpx;
  588. }
  589. </style>

转载请注明,源码请联系

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/474804
推荐阅读
相关标签
  

闽ICP备14008679号