Files
mahjong-web/src/game/actions.ts
wsy182 148e21f3b0 refactor(game): 重构游戏动作处理和WebSocket连接管理
- 重构sendGameAction函数参数结构,添加上下文支持
- 新增sendStartGame和sendLeaveRoom函数统一处理游戏开始和离开房间逻辑
- 移除路由相关依赖,简化ChengduGamePage组件
- 更新WebSocket客户端实现,添加状态变化订阅功能
- 移除requestId生成函数和相关参数,精简消息结构
- 优化座位玩家卡片数据模型,移除在线状态和金钱字段
- 整理游戏阶段常量定义,添加标签映射
- 移除过期的游戏状态字段如needDraw、lastDiscardTile等
- 添加座位类型定义和改进游戏类型文件组织结构
2026-03-25 13:34:47 +08:00

145 lines
2.8 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import type {ActionButtonState} from "./types.ts"
import {wsClient} from "../ws/client.ts"
export function sendGameAction(
params: {
type: ActionButtonState['type']
userID: string
roomId: string
selectedTile?: string | null
},
ctx: {
actionPending: { value: boolean }
logWsSend: (msg: any) => void
pushWsMessage: (msg: string) => void
}
): void {
const {type, userID, roomId, selectedTile} = params
const {actionPending, logWsSend, pushWsMessage} = ctx
// 简单登录判断
if (!userID) {
console.log('当前用户未登录')
return
}
const payload: Record<string, unknown> = {}
// 出牌
if (type === 'discard' && selectedTile) {
payload.tile = selectedTile
payload.discard_tile = selectedTile
payload.code = selectedTile
}
actionPending.value = true
const message = {
type,
sender: userID,
target: 'room',
roomId,
seq: Date.now(),
payload,
}
logWsSend(message)
wsClient.send(message)
pushWsMessage(`[client] 请求${type}`)
}
export function sendStartGame(params: {
userID: string
roomId: string
canStartGame: boolean
startGamePending: { value: boolean }
logWsSend: (msg: any) => void
pushWsMessage: (msg: string) => void
}): void {
const {
userID,
roomId,
canStartGame,
startGamePending,
logWsSend,
pushWsMessage
} = params
if (!canStartGame || startGamePending.value) {
return
}
if (!userID) {
return
}
startGamePending.value = true
const message = {
type: 'start_game',
sender: userID,
target: 'room',
roomId,
seq: Date.now(),
payload: {},
}
logWsSend(message)
wsClient.send(message)
pushWsMessage(`[client] 请求开始游戏`)
}
export function sendLeaveRoom(params: {
userID: string
roomId: string
wsError: { value: string }
leaveRoomPending: { value: boolean }
logWsSend: (msg: any) => void
pushWsMessage: (msg: string) => void
}): boolean {
const {
userID,
roomId,
wsError,
leaveRoomPending,
logWsSend,
pushWsMessage
} = params
if (!userID) {
wsError.value = '缺少当前用户 ID无法退出房间'
return false
}
if (!roomId) {
wsError.value = '缺少房间 ID无法退出房间'
return false
}
leaveRoomPending.value = true
const message = {
type: 'leave_room',
sender: userID,
target: 'room',
roomId: roomId,
seq: Date.now(),
payload: {},
}
logWsSend(message)
wsClient.send(message)
pushWsMessage(`[client] 请求退出房间`)
return true
}