Files
zt-online-game-backend/internal/hall/matcher.go
T

279 lines
10 KiB
Go

// Package hall 提供大厅能力:按「游戏 + 桌人数」分队列匹配,凑满人数后建房间并通知玩家。
// 排队过久仍未凑满时,自动用 AI 补齐空位,且对外完全不可感知。
package hall
import (
"context" // 标准库:Run 的生命周期控制
"errors" // 标准库:重复排队、已在房间等错误
"fmt" // 标准库:队列键拼接与人数越界提示
"log/slog" // 标准库:记录入队、成局、超时
"sync" // 标准库:保护队列表
"time" // 标准库:排队时刻、tick 周期、超时判定
"git.lzcwy.cn/zhengchiliu/zt-online-game-backend/global"
"git.lzcwy.cn/zhengchiliu/zt-online-game-backend/internal/dto"
"git.lzcwy.cn/zhengchiliu/zt-online-game-backend/internal/game"
"git.lzcwy.cn/zhengchiliu/zt-online-game-backend/internal/room"
"git.lzcwy.cn/zhengchiliu/zt-online-game-backend/internal/wsgateway"
)
// item 是队列中的一个排队者。
type item struct {
uid int64 // 用户 ID
gameID string // 游戏 ID(超时通知时要用)
seats int // 该排队者要开的桌人数(决定补几个 AI)
enqueueAt time.Time // 入队时刻,用于排队超时与补 AI 判定
}
// queue 是「某个游戏 + 某个桌人数」的一条匹配队列(如 snake|4 表示四人场)。
type queue struct {
key string // 队列键:gameID|seats
gameID string // 游戏 ID
seats int // 凑满几人开局(客户端指定,已校验在玩法人数范围内)
items []*item // 排队者,先进先出
}
// Matcher 管理全部队列,按 tick 扫描凑人成局。
type Matcher struct {
mu sync.Mutex // 保护下面两张表
queues map[string]*queue // key -> 队列
waiting map[int64]string // uid -> key,便于快速判断是否已在排队
manager *room.Manager // 成局后创建房间
hub *wsgateway.Hub // 下发匹配结果
}
// NewMatcher 创建匹配器。
func NewMatcher(hub *wsgateway.Hub, manager *room.Manager) *Matcher {
return &Matcher{
queues: make(map[string]*queue), // 初始化队列表
waiting: make(map[int64]string), // 初始化排队索引
manager: manager, // 房间管理器
hub: hub, // 下发通道
}
}
// Enqueue 把用户放入「游戏 + 人数」对应的队列(如贪吃蛇四人场)。
// seats 为 0 时按玩法最少人数处理;超出玩法人数范围直接拒绝。
func (m *Matcher) Enqueue(uid int64, gameID string, seats int) error {
meta, err := game.LookupMeta(gameID) // 校验玩法已注册,并取人数范围
if err != nil { // 未注册的游戏
return err
}
if seats <= 0 { // 未指定人数:按最少人数
seats = meta.MinSeats
}
if seats < meta.MinSeats || (meta.MaxSeats > 0 && seats > meta.MaxSeats) { // 人数越界
return fmt.Errorf("该玩法只支持 %d~%d 人,收到 %d", meta.MinSeats, meta.MaxSeats, seats)
}
if _, ok := m.manager.RoomOf(uid); ok { // 已在房间内:不允许同时排队
return errors.New("已在房间内,请先离开")
}
key := fmt.Sprintf("%s|%d", gameID, seats) // 队列键:游戏 + 人数
m.mu.Lock() // 加锁
defer m.mu.Unlock() // 返回时解锁
if _, ok := m.waiting[uid]; ok { // 已在排队中
return errors.New("已在匹配队列中")
}
q, ok := m.queues[key] // 取队列
if !ok { // 首次出现:建队列
q = &queue{key: key, gameID: gameID, seats: seats}
m.queues[key] = q
}
q.items = append(q.items, &item{uid: uid, gameID: gameID, seats: seats, enqueueAt: time.Now()}) // 入队
m.waiting[uid] = key // 记录索引
slog.Info("match enqueue", "user_id", uid, "game_id", gameID, "seats", seats, "size", len(q.items))
return nil
}
// Cancel 取消排队:gameID 为空表示取消该用户的全部排队。
func (m *Matcher) Cancel(uid int64, gameID string) {
m.mu.Lock() // 加锁
var cancelled []*item // 收集被取消者,解锁后再通知
for key, q := range m.queues { // 遍历所有队列
if gameID != "" && q.gameID != gameID { // 只处理指定游戏
continue
}
for i, it := range q.items { // 查找该用户
if it.uid == uid {
cancelled = append(cancelled, it) // 记录
q.items = append(q.items[:i], q.items[i+1:]...) // 移除
delete(m.waiting, uid) // 清除索引
break
}
}
if len(q.items) == 0 { // 队列空了
delete(m.queues, key) // 删除队列
}
}
m.mu.Unlock() // 解锁
for _, it := range cancelled { // 锁外通知,避免回调内再操作锁
m.notifyCancelled(it.uid, it.gameID, "user")
}
}
// Run 启动匹配扫描循环,ctx 取消即退出。
func (m *Matcher) Run(ctx context.Context) {
ticker := time.NewTicker(queueTick()) // 按配置周期扫描
defer ticker.Stop() // 退出时停止
for { // 持续扫描
select {
case <-ctx.Done(): // 上下文取消(优雅退出)
return
case <-ticker.C: // 到点扫描
m.scan(time.Now())
}
}
}
// scan 扫描全部队列:清超时 → 凑人成局 → 等待过久的用 AI 补齐。
func (m *Matcher) scan(now time.Time) {
m.mu.Lock() // 加锁
// 1) 清理排队超时(未开启补 AI 时才会真的发生)
var timeout []*item
for key, q := range m.queues { // 遍历队列
kept := q.items[:0] // 原地过滤,复用底层数组
for _, it := range q.items { // 逐个判断
if now.Sub(it.enqueueAt) > matchTimeout() && !aiEnabled() { // 超时且未开启补 AI
delete(m.waiting, it.uid) // 清除索引
timeout = append(timeout, it)
continue
}
kept = append(kept, it) // 保留
}
q.items = kept // 写回
if len(q.items) == 0 { // 队列已空
delete(m.queues, key) // 删除
}
}
// 2) 凑满人的分组:真人成局
var groups [][]*item
for _, q := range m.queues { // 遍历队列凑人
for len(q.items) >= q.seats { // 人数足够
group := append([]*item(nil), q.items[:q.seats]...) // 取前 seats 个
q.items = q.items[q.seats:] // 剩余继续排队
for _, it := range group { // 清除索引
delete(m.waiting, it.uid)
}
groups = append(groups, group) // 记录分组
}
}
// 3) 等待过久仍未凑满:用 AI 补齐空位(对外不可感知)
var aiGroups [][]*item
if aiEnabled() {
for key, q := range m.queues { // 遍历未满队列
if len(q.items) == 0 { // 空队列跳过
continue
}
if now.Sub(q.items[0].enqueueAt) < aiWait() { // 队首等待时长还不够
continue
}
take := len(q.items) // 取出当前全部排队者(最多一桌)
if take > q.seats {
take = q.seats
}
group := append([]*item(nil), q.items[:take]...) // 取走
q.items = q.items[take:] // 剩余继续排队
for _, it := range group { // 清除索引
delete(m.waiting, it.uid)
}
if len(q.items) == 0 { // 队列已空
delete(m.queues, key) // 删除
}
aiGroups = append(aiGroups, group) // 记录需补 AI 的分组
}
}
m.mu.Unlock() // 解锁
for _, it := range timeout { // 通知排队超时(锁外)
m.notifyCancelled(it.uid, it.gameID, "timeout")
}
for _, g := range groups { // 真人成局(锁外,建房间较慢)
m.createRoom(g, 0)
}
for _, g := range aiGroups { // AI 补位成局(锁外)
m.createRoom(g, g[0].seats-len(g))
}
}
// createRoom 为一组成员创建房间并通知;aiCount 为需要补位的 AI 数量。
func (m *Matcher) createRoom(g []*item, aiCount int) {
if len(g) == 0 { // 空分组
return
}
uids := make([]int64, 0, len(g)) // 收集真人用户 ID
for _, it := range g {
uids = append(uids, it.uid)
}
if aiCount < 0 { // 防御:人数不会为负
aiCount = 0
}
r, err := m.manager.Create(g[0].gameID, uids, aiCount) // 创建房间(真人 + AI 一起入座)
if err != nil { // 创建失败(如玩法不支持 AI、房间数超限)
slog.Error("match create room failed", "game_id", g[0].gameID, "ai", aiCount, "error", err)
return
}
data, err := wsgateway.Encode(wsgateway.TypeHallMatched, 0, dto.WSHallMatchedPayload{ // 编码匹配成功通知
RoomID: r.ID(),
GameID: r.GameID(),
Seats: len(uids) + aiCount,
Users: r.UserIDs(),
Players: r.Roster(),
})
if err != nil { // 编码失败
slog.Error("match encode hall.matched failed", "error", err)
return
}
m.hub.Broadcast(uids, data) // 只广播给真人(AI 无连接,Hub 会自然跳过)
slog.Info("match room created", "room_id", r.ID(), "game_id", g[0].gameID,
"users", uids, "ai", aiCount)
}
// notifyCancelled 下发取消通知。
func (m *Matcher) notifyCancelled(uid int64, gameID, reason string) {
data, err := wsgateway.Encode(wsgateway.TypeHallCancelled, 0,
dto.WSHallCancelledPayload{GameID: gameID, Reason: reason})
if err != nil { // 编码失败
slog.Error("match encode hall.cancelled failed", "error", err)
return
}
m.hub.SendTo(uid, data) // 单独通知
}
// queueTick 返回队列扫描间隔。
func queueTick() time.Duration {
if global.WSSetting != nil && global.WSSetting.QueueTickMs > 0 { // 配置了
return time.Duration(global.WSSetting.QueueTickMs) * time.Millisecond
}
return time.Second // 兜底 1 秒
}
// matchTimeout 返回排队超时时长。
func matchTimeout() time.Duration {
if global.WSSetting != nil && global.WSSetting.MatchTimeoutSec > 0 { // 配置了
return time.Duration(global.WSSetting.MatchTimeoutSec) * time.Second
}
return 60 * time.Second // 兜底 60 秒
}
// aiEnabled 是否开启「匹配超时补 AI」。
func aiEnabled() bool {
return global.WSSetting != nil && global.WSSetting.AIEnabled
}
// aiWait 排队超过多久开始补 AI。
func aiWait() time.Duration {
if global.WSSetting != nil && global.WSSetting.AIWaitSec > 0 { // 配置了
return time.Duration(global.WSSetting.AIWaitSec) * time.Second
}
return 30 * time.Second // 兜底 30 秒
}