Преглед на файлове

roomstore进一步简化

wuzj преди 1 ден
родител
ревизия
bc0e774f12
променени са 6 файла, в които са добавени 135 реда и са изтрити 238 реда
  1. 6 6
      src/components/room/RoomCode.vue
  2. 2 2
      src/pages/room/create/index.vue
  3. 15 11
      src/pages/room/waiting/index.vue
  4. 69 145
      src/services/room.ts
  5. 43 63
      src/stores/room.ts
  6. 0 11
      src/types/room.ts

+ 6 - 6
src/components/room/RoomCode.vue

@@ -1,7 +1,7 @@
 <template>
   <view class="room-code">
     <view class="room-code__title">房间码</view>
-    <view class="room-code__value">{{ code }}</view>
+    <view class="room-code__value">{{ roomId }}</view>
     <view class="room-code__actions">
       <nut-button size="small" color="#FFB11B" @click="handleShare">邀请好友</nut-button>
       <nut-button size="small" plain @click="handleCopy">复制房间码</nut-button>
@@ -20,7 +20,7 @@
             <canvas canvas-id="qrcode" id="qrcode" class="qrcode-canvas" />
           </view>
           <view class="room-info">
-            <view class="room-id">房间号: {{ code }}</view>
+            <view class="room-id">房间号: {{ roomId }}</view>
             <view class="room-password" v-if="password">
               密码: {{ password }}
             </view>
@@ -37,7 +37,7 @@ import Taro from '@tarojs/taro';
 import drawQrcode from 'weapp-qrcode';
 
 const props = defineProps({
-  code: { type: String, required: true },
+  roomId: { type: String, required: true },
   password: { type: String, default: '' }
 });
 
@@ -45,10 +45,10 @@ const showDialog = ref(false);
 
 // 生成二维码
 const generateQRCode = () => {
-  if (!props.code) return;
+  if (!props.roomId) return;
 
   // 构建房间链接数据
-  let roomData = `room?id=${props.code}`;
+  let roomData = `room?id=${props.roomId}`;
   if (props.password) {
     roomData += `&pwd=${props.password}`;
   }
@@ -85,7 +85,7 @@ const handleShare = () => {
 
 const handleCopy = () => {
   Taro.setClipboardData({
-    data: props.code,
+    data: props.roomId,
     success: () => {
       Taro.showToast({
         title: '房间码已复制',

+ 2 - 2
src/pages/room/create/index.vue

@@ -60,7 +60,7 @@
     
     <view class="action-buttons">
       <nut-button block color="#3C92FB" class="create-button" @click="createRoom">
-        创建并开始
+        创建房间
       </nut-button>
     </view>
   </view>
@@ -198,7 +198,7 @@ export default {
         
         const result = await roomStore.createRoom(roomData)
         
-        if (result.success && result.roomId) {
+        if (result.success) {
           tabbarStore.switchToRoomTab('/pages/room/waiting/index', {
           params: {
             roomId: roomData.roomId,

+ 15 - 11
src/pages/room/waiting/index.vue

@@ -11,7 +11,8 @@
 
     <!-- 房间码展示和分享 -->
     <RoomCode
-      :code="currentRoom?.id || ''"
+      :gameId="currentRoom?.gameId || ''"
+      :roomId="currentRoom?.roomId || ''"
       :password="currentRoom?.password"
       @share="handleShare"
       @copy="handleCopy"
@@ -77,6 +78,8 @@ export default {
     const tabbarStore = useTabBarStore()
     const turtleSoupStore = useTurtleSoupStore()
     
+    // 游戏ID
+    const gameId = ref('')
     // 房间ID
     const roomId = ref('')
     
@@ -144,11 +147,11 @@ export default {
       const currentPage = pages[pages.length - 1]
       const routeParams = currentPage.$taroParams
       
-      if (routeParams && routeParams.roomId) {
+      if (routeParams && routeParams.gameId && routeParams.roomId) {
         roomId.value = routeParams.roomId
-        
+        gameId.value = routeParams.gameId
         // 加载房间信息
-        await loadRoomInfo(roomId.value)
+        await loadRoomInfo(gameId.value,roomId.value)
         
         // 开始监听房间变化
         startRoomListener()
@@ -166,9 +169,9 @@ export default {
     }
     
     // 加载房间信息
-    const loadRoomInfo = async (id: string) => {
+    const loadRoomInfo = async (gameId: string, roomId: string) => {
       try {
-        const result = await roomStore.loadRoomInfo(id)
+        const result = await roomStore.loadRoomInfo(gameId, roomId)
         if (!result.success) {
           throw new Error(result.message || '加载房间信息失败')
         }
@@ -229,13 +232,13 @@ export default {
         
         if (result.success && result.gameId) {
           // 更新房间状态为游戏中
-          await roomStore.updateRoomStatus(RoomStatus.PLAYING)
+          await roomStore.updateRoomStatus(gameId.value, roomId.value, RoomStatus.PLAYING)
           
           // 导航到游戏页面
           tabbarStore.switchToRoomTab('/pages/room/play/index', {
             params: {
-              roomId: currentRoom.value.id,
-              gameId: result.gameId
+              roomId: roomId.value,
+              gameId: gameId.value
             }
           })
         } else {
@@ -260,7 +263,7 @@ export default {
       // 定期刷新房间状态
       roomInterval = setInterval(async () => {
         if (roomId.value) {
-          await loadRoomInfo(roomId.value)
+          await loadRoomInfo(gameId.value, roomId.value)
           
           // 检查房间状态,如果变为"游戏中",需要跳转到游戏页面
           if (currentRoom.value && currentRoom.value.status === RoomStatus.PLAYING) {
@@ -269,7 +272,8 @@ export default {
             // 跳转到游戏页面
             tabbarStore.switchToRoomTab('/pages/room/play/index', {
               params: {
-                roomId: roomId.value
+                roomId: roomId.value,
+                gameId: gameId.value
               }
             })
           }

+ 69 - 145
src/services/room.ts

@@ -1,7 +1,6 @@
 // services/room.ts
 import Taro from '@tarojs/taro'
 import { 
-  type RecentRoom, 
   type Room, 
   type RoomUserInfo, 
   RoomRole, 
@@ -60,7 +59,7 @@ const mockRooms: Record<string, Room> = {
 // 房间API - 适配新数据结构
 export const roomService = {
   // 获取最近房间
-  async getRecentRooms(): Promise<RecentRoom[]> {
+  async getRecentRooms(): Promise<Room[]> {
     try {
       // 从缓存获取
       const cachedRooms = Taro.getStorageSync('recentRooms')
@@ -74,19 +73,26 @@ export const roomService = {
           roomId: 'room_001', 
           name: '海龟汤房间', 
           gameTitle: '海龟汤', 
-          lastVisitTime: Date.now() - 3600000, 
-          hasPassword: false, 
+          gameId: '1',
+          maxPlayers: 10,
+          visibility: RoomVisibility.PUBLIC,
+          hosterId: 'host_123',
+          createTime: Date.now() - 3600000,
           status: RoomStatus.WAITING,
-          playerCount: 1
+          users: []
         },
         { 
           roomId: 'room_002', 
           name: '狼人杀小队', 
-          gameTitle: '狼人杀', 
-          lastVisitTime: Date.now() - 86400000, 
-          hasPassword: true, 
-          status: RoomStatus.PLAYING,
-          playerCount: 1
+          gameTitle: '狼人杀',  
+          gameId: '2',
+          maxPlayers: 8,
+          visibility: RoomVisibility.PRIVATE,
+          password: '1234',
+          hosterId: 'host_456',
+          createTime: Date.now() - 86400000,
+          status: RoomStatus.WAITING,
+          users: []
         }
       ]
     } catch (error) {
@@ -96,20 +102,20 @@ export const roomService = {
   },
   
   // 检查房间是否存在
-  async checkRoomExist(roomId: string): Promise<{exists: boolean, needPassword: boolean}> {
+  async checkRoomExist(gameId: string, roomId: string): Promise<{exists: boolean, needPassword: boolean}> {
     try {
       // 先查询本地存储
       const recentRooms = Taro.getStorageSync('recentRooms')
       if (recentRooms) {
         const rooms = JSON.parse(recentRooms)
-        const room = rooms.find((r: RecentRoom) => r.roomId === roomId)
+        const room = rooms.find((r: Room) => r.roomId === `${gameId}-${roomId}`)
         if (room) {
-          return { exists: true, needPassword: room.hasPassword }
+          return { exists: true, needPassword: room.visibility === RoomVisibility.PRIVATE }
         }
       }
       
       // 如果本地没有,检查mock数据
-      const mockRoom = mockRooms[roomId]
+      const mockRoom = mockRooms[`${gameId}-${roomId}`]
       if (mockRoom) {
         return { 
           exists: true, 
@@ -125,10 +131,10 @@ export const roomService = {
   },
   
   // 验证房间密码
-  async verifyRoomPassword(roomId: string, password: string): Promise<{valid: boolean}> {
+  async verifyRoomPassword(gameId: string, roomId: string, password: string): Promise<{valid: boolean}> {
     try {
       // 简化实现:仅检查mock数据中的密码
-      const mockRoom = mockRooms[roomId]
+      const mockRoom = mockRooms[`${gameId}-${roomId}`]
       if (mockRoom && mockRoom.visibility === RoomVisibility.PRIVATE) {
         return { valid: mockRoom.password === password }
       }
@@ -141,28 +147,17 @@ export const roomService = {
   },
   
   // 创建新房间 - 适配新数据结构
-  async createRoom(roomData: Room, userInfo: UserInfo): Promise<{roomId: string | null, success: boolean, message?: string}> {
+  async createRoom(roomData: Room, userInfo: UserInfo): Promise<{success: boolean, message?: string}> {
     try {
       if (!userInfo.openid) {
-        return { roomId: null, success: false, message: '用户未登录' }
+        return { success: false, message: '用户未登录' }
       }
       
       // 本地存储一份房间信息
       const recentRooms = Taro.getStorageSync('recentRooms') || '[]'
       const rooms = JSON.parse(recentRooms)
       
-      // 添加到最近房间
-      const roomInfo: RecentRoom = {
-        roomId: roomData.roomId,
-        name: roomData.name,
-        gameTitle: roomData.gameTitle,
-        lastVisitTime: roomData.createTime,
-        hasPassword: roomData.visibility === RoomVisibility.PRIVATE,
-        status: roomData.status,
-        playerCount: roomData.users.length
-      }
-      
-      rooms.unshift(roomInfo)
+      rooms.unshift(roomData)
       // 只保留最近10个房间
       if (rooms.length > 10) {
         rooms.pop()
@@ -173,18 +168,19 @@ export const roomService = {
       // 简化实现:仅存储在本地缓存
       const allRooms = Taro.getStorageSync('allRooms') || '{}'
       const roomsObj = JSON.parse(allRooms)
-      roomsObj[roomData.roomId] = roomData
+      const roomKey = `${roomData.gameId}-${roomData.roomId}`
+      roomsObj[roomKey] = roomData
       Taro.setStorageSync('allRooms', JSON.stringify(roomsObj))
       
-      return { roomId: roomData.roomId, success: true }
+      return { success: true }
     } catch (error) {
       console.error('创建房间失败:', error)
-      return { roomId: null, success: false, message: '创建房间失败' }
+      return { success: false, message: '创建房间失败' }
     }
   },
   
   // 加入房间 - 适配新数据结构
-  async joinRoom(roomId: string, userData: RoomUserInfo): Promise<{success: boolean, roomData?: Room, message?: string}> {
+  async joinRoom(gameId: string, roomId: string, userData: RoomUserInfo): Promise<{success: boolean, roomData?: Room, message?: string}> {
     try {
       // 查找房间 - 先从本地缓存查询
       let room: Room | null = null
@@ -192,12 +188,12 @@ export const roomService = {
       // 检查本地缓存中是否有该房间
       const allRooms = Taro.getStorageSync('allRooms') || '{}'
       const roomsObj = JSON.parse(allRooms)
-      
-      if (roomsObj[roomId]) {
-        room = roomsObj[roomId]
-      } else if (mockRooms[roomId]) {
+      const roomKey = `${gameId}-${roomId}`
+      if (roomsObj[roomKey]) {
+        room = roomsObj[roomKey]
+      } else if (mockRooms[roomKey]) {
         // 使用mock数据
-        room = mockRooms[roomId]
+        room = mockRooms[roomKey]
       }
       
       if (!room) {
@@ -216,19 +212,24 @@ export const roomService = {
         room.users.push(userData)
         
         // 更新本地缓存
-        roomsObj[roomId] = room
+        roomsObj[roomKey] = room
         Taro.setStorageSync('allRooms', JSON.stringify(roomsObj))
       }
       
       // 保存到最近加入的房间
-      const roomInfo: RecentRoom = {
+      const roomInfo: Room = {
         roomId: room.roomId,
         name: room.name,
+        gameId: room.gameId,
         gameTitle: room.gameTitle,
-        lastVisitTime: Date.now(),
-        hasPassword: room.visibility === RoomVisibility.PRIVATE,
+        maxPlayers: room.maxPlayers,
+        visibility: room.visibility,
+        hosterId: room.hosterId,
+        createTime: room.createTime,
+        startTime: room.startTime,
+        endTime: room.endTime,
         status: room.status,
-        playerCount: room.users.length
+        users: room.users
       }
       
       // 更新最近房间列表
@@ -242,13 +243,13 @@ export const roomService = {
   },
   
   // 保存到最近加入的房间
-  async saveToRecentRooms(roomInfo: RecentRoom): Promise<void> {
+  async saveToRecentRooms(roomInfo: Room): Promise<void> {
     try {
       const recentRooms = Taro.getStorageSync('recentRooms') || '[]'
       const rooms = JSON.parse(recentRooms)
       
       // 检查是否已存在
-      const existingIndex = rooms.findIndex((r: RecentRoom) => r.roomId === roomInfo.roomId)
+      const existingIndex = rooms.findIndex((r: Room) => r.roomId === roomInfo.roomId)
       if (existingIndex !== -1) {
         // 移除已存在的
         rooms.splice(existingIndex, 1)
@@ -269,20 +270,21 @@ export const roomService = {
   },
   
   // 退出房间
-  async leaveRoom(roomId: string, userId: string): Promise<{success: boolean, message?: string}> {
+  async leaveRoom(gameId: string, roomId: string, userId: string): Promise<{success: boolean, message?: string}> {
     try {
       // 从本地缓存找到房间
       const allRooms = Taro.getStorageSync('allRooms') || '{}'
       const roomsObj = JSON.parse(allRooms)
+      const roomKey = `${gameId}-${roomId}`
       
-      if (roomsObj[roomId]) {
-        const room = roomsObj[roomId]
+      if (roomsObj[roomKey]) {
+        const room = roomsObj[roomKey]
         
         // 过滤掉当前用户
         room.users = room.users.filter(u => u.openid !== userId)
         
         // 更新本地缓存
-        roomsObj[roomId] = room
+        roomsObj[roomKey] = room
         Taro.setStorageSync('allRooms', JSON.stringify(roomsObj))
       }
       
@@ -294,19 +296,20 @@ export const roomService = {
   },
   
   // 获取房间信息
-  async getRoomInfo(roomId: string): Promise<Room | null> {
+  async getRoomInfo(gameId: string, roomId: string): Promise<Room | null> {
     try {
       // 检查本地缓存中是否有该房间
       const allRooms = Taro.getStorageSync('allRooms') || '{}'
       const roomsObj = JSON.parse(allRooms)
+      const roomKey = `${gameId}-${roomId}`
       
-      if (roomsObj[roomId]) {
-        return roomsObj[roomId]
+      if (roomsObj[roomKey]) {
+        return roomsObj[roomKey]
       }
       
       // 如果本地没有,使用mock数据
-      if (mockRooms[roomId]) {
-        return mockRooms[roomId]
+      if (mockRooms[roomKey]) {
+        return mockRooms[roomKey]
       }
       
       return null
@@ -388,96 +391,16 @@ export const roomService = {
     }
   },
 
-  // 获取我创建的房间/游戏
-  async getCreatedRooms(userId: string): Promise<any[]> {
-    try {
-      // 合并进行中和已结束的,筛选出我创建的
-      const activeRooms = await this.getActiveRooms(userId)
-      const endedGames = await this.getEndedGames(userId)
-      
-      const createdRooms = activeRooms.filter((room: Room) => room.hosterId === userId)
-      const createdGames = endedGames.filter((game: any) => game.hosterId === userId)
-      
-      // 合并结果并按时间排序
-      const result = [
-        ...createdRooms.map((room: Room) => ({
-          ...room,
-          isActive: true,
-          time: room.createTime
-        })),
-        ...createdGames.map((game: any) => ({
-          ...game,
-          isActive: false,
-          time: game.endTime
-        }))
-      ].sort((a, b) => b.time - a.time)
-      
-      return result
-    } catch (error) {
-      console.error('获取我创建的房间/游戏失败:', error)
-      return []
-    }
-  },
-
-  // 获取我参与的房间/游戏
-  async getJoinedRooms(userId: string): Promise<any[]> {
-    try {
-      // 合并进行中和已结束的,筛选出我参与但不是我创建的
-      const activeRooms = await this.getActiveRooms(userId)
-      const endedGames = await this.getEndedGames(userId)
-      
-      const joinedRooms = activeRooms.filter((room: Room) => 
-        room.hosterId !== userId &&
-        room.users && 
-        room.users.some((u) => u.openid === userId)
-      )
-      
-      const joinedGames = endedGames.filter((game: any) => 
-        game.hosterId !== userId &&
-        game.users && 
-        game.users.some((u: any) => u.openid === userId)
-      )
-      
-      // 合并结果并按时间排序
-      const result = [
-        ...joinedRooms.map((room: Room) => ({
-          ...room,
-          isActive: true,
-          time: room.createTime
-        })),
-        ...joinedGames.map((game: any) => ({
-          ...game,
-          isActive: false,
-          time: game.endTime
-        }))
-      ].sort((a, b) => b.time - a.time)
-      
-      return result
-    } catch (error) {
-      console.error('获取我参与的房间/游戏失败:', error)
-      return []
-    }
-  },
-
-  // 创建房间用户信息
-  createRoomUserInfo(userInfo: UserInfo, isHoster: boolean = false): RoomUserInfo {
-    return {
-      ...userInfo,
-      roomRole: isHoster ? RoomRole.HOSTER : RoomRole.PLAYER,
-      joinTime: Date.now(),
-      isReady: isHoster
-    }
-  },
-
   // 更新房间中的用户信息
-  async updateUserInRoom(roomId: string, userId: string, userData: Partial<RoomUserInfo>): Promise<{success: boolean, message?: string}> {
+  async updateUserInRoom(gameId: string, roomId: string, userId: string, userData: Partial<RoomUserInfo>): Promise<{success: boolean, message?: string}> {
     try {
       // 从本地缓存找到房间
       const allRooms = Taro.getStorageSync('allRooms') || '{}'
       const roomsObj = JSON.parse(allRooms)
+      const roomKey = `${gameId}-${roomId}`
       
-      if (roomsObj[roomId]) {
-        const room = roomsObj[roomId]
+      if (roomsObj[roomKey]) {
+        const room = roomsObj[roomKey]
         
         // 找到对应用户
         const userIndex = room.users.findIndex(u => u.openid === userId)
@@ -489,7 +412,7 @@ export const roomService = {
           }
           
           // 更新本地缓存
-          roomsObj[roomId] = room
+          roomsObj[roomKey] = room
           Taro.setStorageSync('allRooms', JSON.stringify(roomsObj))
           
           return { success: true }
@@ -520,26 +443,27 @@ export const roomService = {
   },
 
   // 更新房间状态
-  async updateRoomStatus(roomId: string, status: RoomStatus): Promise<{success: boolean, message?: string}> {
+  async updateRoomStatus(gameId: string, roomId: string, status: RoomStatus): Promise<{success: boolean, message?: string}> {
     try {
       // 从本地缓存找到房间
       const allRooms = Taro.getStorageSync('allRooms') || '{}'
       const roomsObj = JSON.parse(allRooms)
+      const roomKey = `${gameId}-${roomId}`
       
-      if (roomsObj[roomId]) {
-        const room = roomsObj[roomId]
+      if (roomsObj[roomKey]) {
+        const room = roomsObj[roomKey]
         
         // 更新状态
         room.status = status
         
         // 更新本地缓存
-        roomsObj[roomId] = room
+        roomsObj[roomKey] = room
         Taro.setStorageSync('allRooms', JSON.stringify(roomsObj))
         
         // 同时更新最近房间列表中的状态
         const recentRooms = Taro.getStorageSync('recentRooms') || '[]'
         const rooms = JSON.parse(recentRooms)
-        const roomIndex = rooms.findIndex((r: RecentRoom) => r.roomId === roomId)
+        const roomIndex = rooms.findIndex((r: Room) => r.roomId === roomId)
         
         if (roomIndex !== -1) {
           rooms[roomIndex].status = status

+ 43 - 63
src/stores/room.ts

@@ -5,10 +5,8 @@ import { roomService } from '@/services/room'
 import { 
   type Room, 
   type RoomUserInfo, 
-  type RecentRoom, 
   RoomRole, 
   RoomStatus, 
-  RoomVisibility 
 } from '@/types/room'
 import { useUserStore } from '@/stores/user'
 
@@ -20,7 +18,7 @@ export const useRoomStore = defineStore('room', () => {
   const currentRoom = ref<Room | null>(null)
   
   // 最近加入的房间
-  const recentRooms = ref<RecentRoom[]>([])
+  const recentRooms = ref<Room[]>([])
   
   // 历史记录状态
   const historyState = reactive({
@@ -42,32 +40,42 @@ export const useRoomStore = defineStore('room', () => {
     }
     
     // 从已加载的活跃房间和历史记录构建最近房间列表
-    const recentList: RecentRoom[] = [
+    const recentList: Room[] = [
       // 活跃房间
       ...historyState.activeRooms.map(room => ({
         roomId: room.roomId,
         name: room.name,
+        gameId: room.gameId,
         gameTitle: room.gameTitle,
-        lastVisitTime: room.createTime,
-        hasPassword: room.visibility === RoomVisibility.PRIVATE,
+        maxPlayers: room.maxPlayers,
+        visibility: room.visibility,
+        hosterId: room.hosterId,
+        createTime: room.createTime,
+        startTime: room.startTime,
+        endTime: room.endTime,
         status: room.status,
-        playerCount: room.users.length
+        users: room.users
       })),
       // 已结束游戏
       ...historyState.endedGames.filter((game, index) => index < 5).map(game => ({
         roomId: game.roomId || game.roomId,
-        name: game.roomName,
+        name: game.roomName, 
+        gameId: game.gameId,
         gameTitle: game.gameTitle,
-        lastVisitTime: game.endTime,
+        maxPlayers: game.maxPlayers,
+        visibility: game.visibility,
+        hosterId: game.hosterId,
+        createTime: game.createTime,
+        startTime: game.startTime,
+        endTime: game.endTime,
         status: RoomStatus.ENDED,
-        hasPassword: false,
-        playerCount: game.users?.length || 0
+        users: game.users
       }))
     ]
     
     // 按时间排序并只保留最近的条目
     recentRooms.value = recentList
-      .sort((a, b) => b.lastVisitTime - a.lastVisitTime)
+      .sort((a, b) => b.createTime - a.createTime)
       .slice(0, 10)
     
     return recentRooms.value
@@ -96,9 +104,9 @@ export const useRoomStore = defineStore('room', () => {
   }
 
   // 检查房间是否存在
-  async function checkRoomExist(roomId: string) {
+  async function checkRoomExist(gameId: string, roomId: string) {
     try {
-      return await roomService.checkRoomExist(roomId)
+      return await roomService.checkRoomExist(gameId, roomId)
     } catch (error) {
       console.error('检查房间存在失败:', error)
       return { exists: false, needPassword: false }
@@ -106,9 +114,9 @@ export const useRoomStore = defineStore('room', () => {
   }
 
   // 验证房间密码
-  async function verifyRoomPassword(roomId: string, password: string) {
+  async function verifyRoomPassword(gameId: string, roomId: string, password: string) {
     try {
-      return await roomService.verifyRoomPassword(roomId, password)
+      return await roomService.verifyRoomPassword(gameId, roomId, password)
     } catch (error) {
       console.error('验证房间密码失败:', error)
       return { valid: false }
@@ -144,18 +152,17 @@ export const useRoomStore = defineStore('room', () => {
     
     const result = await roomService.createRoom(roomData, userStore)
     
-    if (result.success && result.roomId) {
+    if (result.success) {
       // 获取完整房间信息
-      const room = await roomService.getRoomInfo(result.roomId)
+      const room = await roomService.getRoomInfo(roomData.gameId, roomData.roomId)
       if (room) {
         setCurrentRoom(room)
         
-        // 设置当前房间ID
-        userStore.setCurrentRoom(result.roomId)
-        
         // 设置当前游戏ID
         if (room.gameId) {
           userStore.setCurrentGame(room.gameId)
+          // 设置当前房间ID
+          userStore.setCurrentRoom(room.roomId)
         }
         
         // 更新最近房间列表
@@ -171,7 +178,7 @@ export const useRoomStore = defineStore('room', () => {
   }
   
   // 加入房间 - 调用API并更新store
-  async function joinRoom(roomId: string) {
+  async function joinRoom(gameId: string, roomId: string) {
     try {
       // 检查用户是否已注册
       const userCheck = await checkUserRegistered()
@@ -190,7 +197,7 @@ export const useRoomStore = defineStore('room', () => {
     }
       
       // 调用API加入房间
-      const result = await roomService.joinRoom(roomId, userData)
+      const result = await roomService.joinRoom(gameId, roomId, userData)
       
       if (result.success && result.roomData) {
         // 更新当前房间
@@ -217,9 +224,9 @@ export const useRoomStore = defineStore('room', () => {
   }
   
   // 退出房间 - 调用API并更新store
-  async function leaveRoom(roomId: string) {
+  async function leaveRoom(gameId: string, roomId: string) {
     try {
-      const result = await roomService.leaveRoom(roomId, userStore.openid)
+      const result = await roomService.leaveRoom(gameId, roomId, userStore.openid)
       
       if (result.success) {
         // 清除当前房间信息
@@ -237,9 +244,9 @@ export const useRoomStore = defineStore('room', () => {
   }
   
   // 加载房间信息 - 通过API获取
-  async function loadRoomInfo(roomId: string) {
+  async function loadRoomInfo(gameId: string, roomId: string) {
     try {
-      const room = await roomService.getRoomInfo(roomId)
+      const room = await roomService.getRoomInfo(gameId, roomId)
       
       if (room) {
         setCurrentRoom(room)
@@ -253,38 +260,13 @@ export const useRoomStore = defineStore('room', () => {
     }
   }
   
-  // 添加用户到当前房间
-  function addUserToRoom(user: RoomUserInfo) {
-    if (currentRoom.value) {
-      // 检查是否已存在
-      const existingUserIndex = currentRoom.value.users.findIndex(u => u.openid === user.openid)
-      if (existingUserIndex !== -1) {
-        // 更新现有用户信息
-        currentRoom.value.users[existingUserIndex] = {
-          ...currentRoom.value.users[existingUserIndex],
-          ...user
-        }
-      } else {
-        // 添加新用户
-        currentRoom.value.users.push(user)
-      }
-    }
-  }
-  
-  // 从当前房间移除用户
-  function removeUserFromRoom(userId: string) {
-    if (currentRoom.value) {
-      currentRoom.value.users = currentRoom.value.users.filter(u => u.openid !== userId)
-    }
-  }
-  
   // 更新用户信息
   async function updateUserInRoom(userId: string, data: Partial<RoomUserInfo>) {
     if (!currentRoom.value) return { success: false, message: '当前没有加入房间' }
     
     try {
       // 调用API更新用户信息
-      const result = await roomService.updateUserInRoom(currentRoom.value.roomId, userId, data)
+      const result = await roomService.updateUserInRoom(currentRoom.value.gameId, currentRoom.value.roomId, userId, data)
       
       if (result.success) {
         // 更新本地状态
@@ -306,12 +288,12 @@ export const useRoomStore = defineStore('room', () => {
   }
   
   // 更新房间状态
-  async function updateRoomStatus(status: RoomStatus) {
+  async function updateRoomStatus(gameId: string, roomId: string, status: RoomStatus) {
     if (!currentRoom.value) return { success: false, message: '当前没有加入房间' }
     
     try {
       // 调用API更新房间状态
-      const result = await roomService.updateRoomStatus(currentRoom.value.roomId, status)
+      const result = await roomService.updateRoomStatus(gameId, roomId, status)
       
       if (result.success) {
         // 更新本地状态
@@ -430,7 +412,7 @@ export const useRoomStore = defineStore('room', () => {
   })
   
   // 修改 joinRoomById 方法,确保返回房间数据
-  async function joinRoomById(roomId: string, password?: string): Promise<{
+  async function joinRoomById(gameId: string, roomId: string, password?: string): Promise<{
     success: boolean, 
     message?: string, 
     needPassword?: boolean,
@@ -444,7 +426,7 @@ export const useRoomStore = defineStore('room', () => {
       }
       
       // 2. 验证房间
-      const checkResult = await roomService.checkRoomExist(roomId)
+      const checkResult = await roomService.checkRoomExist(gameId, roomId)
       if (!checkResult || !checkResult.exists) {
         return { success: false, message: '房间不存在' }
       }
@@ -455,14 +437,14 @@ export const useRoomStore = defineStore('room', () => {
       }
       
       if (checkResult.needPassword && password) {
-        const pwdResult = await roomService.verifyRoomPassword(roomId, password)
+        const pwdResult = await roomService.verifyRoomPassword(gameId, roomId, password)
         if (!pwdResult || !pwdResult.valid) {
           return { success: false, message: '房间密码错误' }
         }
       }
       
       // 4. 加入房间
-      const joinResult = await joinRoom(roomId)
+      const joinResult = await joinRoom(gameId, roomId)
       
       // 返回结果时同时包含房间数据
       return joinResult
@@ -487,6 +469,7 @@ export const useRoomStore = defineStore('room', () => {
     verifyRoomPassword,
     createRoom,
     joinRoom,
+    joinRoomById,
     leaveRoom,
     loadRoomInfo,
     loadRecentRooms,
@@ -494,8 +477,6 @@ export const useRoomStore = defineStore('room', () => {
     clearRoom,
     
     // 用户管理方法
-    addUserToRoom,
-    removeUserFromRoom,
     updateUserInRoom,
     isUserInRoom,
     getUserRole,
@@ -511,7 +492,6 @@ export const useRoomStore = defineStore('room', () => {
     getPlayers,
     
     // 历史记录方法
-    loadHistoryByTab,
-    joinRoomById
+    loadHistoryByTab
   }
 })

+ 0 - 11
src/types/room.ts

@@ -41,15 +41,4 @@ export interface Room {
   endTime?: number;      // 结束时间
   status: RoomStatus;    // 房间状态
   users: RoomUserInfo[];     // 房间内用户列表
-}
-
-// 最近房间记录
-export interface RecentRoom {
-  roomId: string;            // 房间ID
-  name: string;          // 房间名称
-  gameTitle: string;     // 游戏标题
-  lastVisitTime: number; // 最后访问时间
-  hasPassword: boolean;  // 是否有密码
-  status: RoomStatus;    // 房间状态
-  playerCount: number;   // 玩家数量
 }