tunnelMacth.js 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. const util = require('./util.js')
  2. function match(page, app, opt) {
  3. const that = page
  4. if (app.appData.tunnelStatus !== 'close') {
  5. app.tunnel.close()
  6. }
  7. app.tunnelCreate()//新建信道,并监听相关变化
  8. const tunnel = app.tunnel
  9. function getCurrentTunnelId() {
  10. return app.tunnel.socketUrl.slice(app.tunnel.socketUrl.indexOf('tunnelId=') + 9, app.tunnel.socketUrl.indexOf('&'))
  11. }
  12. app.tunnelConnectCallback = () => {
  13. let userInfo = that.data.userInfo
  14. userInfo.tunnelId = getCurrentTunnelId()
  15. that.setData({
  16. status: '已连接,对手匹配中...',
  17. userInfo,//用户信息存储当前的信道ID
  18. })
  19. tunnel.emit('updateMatchInfo', {//发起匹配
  20. openId: that.data.openId,
  21. sortId: opt.sortId,
  22. friendsFightingRoom: opt.friendsFightingRoom//匹配者含friendsFightingRoom则说明是好友之间的匹配
  23. })
  24. }
  25. app.tunnelCloseCallback = () => {
  26. that.setData({ status: '连接已关闭' })
  27. //util.showSuccess('连接已断开')
  28. }
  29. app.tunnelReconnectCallback = () => {
  30. util.showSuccess('已重新连接')
  31. let userInfo = that.data.userInfo
  32. userInfo.tunnelId = getCurrentTunnelId()
  33. that.setData({
  34. status: '网络已重连,匹配中...',
  35. userInfo,
  36. })
  37. tunnel.emit('updateMatchInfo', {//发起匹配
  38. openId: that.data.openId,
  39. sortId: opt.sortId,
  40. friendsFightingRoom: opt.friendsFightingRoom//匹配者含friendsFightingRoom则说明是好友之间的匹配
  41. })
  42. }
  43. app.tunnelReconnectCallback = () => {
  44. util.showSuccess('已重新连接')
  45. let userInfo = that.data.userInfo
  46. userInfo.tunnelId = getCurrentTunnelId()
  47. that.setData({
  48. status: '网络重连成功,对手匹配中...',
  49. userInfo,
  50. })
  51. }
  52. app.tunnelErrorCallback = (error) => {
  53. that.setData({ status: '信道发生错误:' + error })
  54. util.showSuccess('连接错误')
  55. }
  56. tunnel.on('matchNotice', (res) => {//监听匹配成功
  57. console.log('res', res)
  58. let user_me, user_others
  59. if (res.player1.openId === that.data.openId){
  60. user_me = res.player1
  61. user_others=res.player2
  62. }else{
  63. user_me = res.player2
  64. user_others = res.player1
  65. }
  66. wx.setStorageSync('user_me', user_me)
  67. wx.setStorageSync('user_others', user_others)
  68. that.setData({ status: user_me.nickName + ' VS ' + user_others.nickName })
  69. setTimeout(goto_fighting_room, 2000)//延迟1s跳转到战队页面
  70. function goto_fighting_room() {
  71. wx.redirectTo({ //navigateTo不会会卸载该页面,只是将当前页面隐藏了,redirectTo会销毁当前页面
  72. url: `../fighting_room/fighting_room?roomName=${res.player1.roomName}`
  73. })
  74. }
  75. })
  76. }
  77. module.exports = { match }