实现游戏大厅与房间模块:玩法插件化、匹配与房间生命周期管理
This commit is contained in:
@@ -0,0 +1,47 @@
|
||||
// Package boot 负责 WebSocket 各模块的接线:注册玩法、创建房间管理器与匹配器、注册消息处理器。
|
||||
package boot
|
||||
|
||||
import (
|
||||
"context" // 标准库:匹配循环的生命周期上下文
|
||||
"log/slog" // 标准库:记录初始化完成
|
||||
|
||||
"git.lzcwy.cn/zhengchiliu/zt-online-game-backend/internal/game"
|
||||
"git.lzcwy.cn/zhengchiliu/zt-online-game-backend/internal/game/gobang"
|
||||
"git.lzcwy.cn/zhengchiliu/zt-online-game-backend/internal/game/snake"
|
||||
"git.lzcwy.cn/zhengchiliu/zt-online-game-backend/internal/game/tictactoe"
|
||||
"git.lzcwy.cn/zhengchiliu/zt-online-game-backend/internal/hall"
|
||||
"git.lzcwy.cn/zhengchiliu/zt-online-game-backend/internal/room"
|
||||
"git.lzcwy.cn/zhengchiliu/zt-online-game-backend/internal/wsgateway"
|
||||
)
|
||||
|
||||
// 模块句柄:便于后续 HTTP 接口或运维命令查询在线数、房间数。
|
||||
var (
|
||||
Hub *wsgateway.Hub // 连接注册表
|
||||
Rooms *room.Manager // 房间管理器
|
||||
Matcher *hall.Matcher // 匹配器
|
||||
)
|
||||
|
||||
// InitWS 完成 WS 模块初始化与接线,应在配置加载之后、服务启动之前调用。
|
||||
func InitWS() {
|
||||
// 注册玩法:每新增一个玩法就在此加一行,网关 / 大厅 / 房间代码无需改动。
|
||||
game.Register("gobang", func() game.Game { return gobang.New() }) // 五子棋:1v1 回合制
|
||||
game.Register("snake", func() game.Game { return snake.New() }) // 双人贪吃蛇:1v1 实时(200ms 一步)
|
||||
game.Register("tictactoe", func() game.Game { return tictactoe.New() }) // 井字棋:1v1 回合制(示例)
|
||||
|
||||
Hub = wsgateway.DefaultHub // 使用网关默认 Hub
|
||||
Rooms = room.NewManager(Hub) // 创建房间管理器
|
||||
room.RegisterHandlers(Hub, Rooms) // 注册 room.* 消息处理器
|
||||
|
||||
Matcher = hall.NewMatcher(Hub, Rooms) // 创建匹配器(成局后委托 Rooms 建房间)
|
||||
hall.RegisterHandlers(Hub, Matcher, Rooms) // 注册 hall.* 消息处理器
|
||||
|
||||
// 断连回调:连接断开时通知房间,进入掉线宽限,重连逻辑因此生效。
|
||||
Hub.OnDisconnect(func(userID int64) { Rooms.OnUserDisconnected(userID) })
|
||||
|
||||
slog.Info("ws modules initialized")
|
||||
}
|
||||
|
||||
// Start 启动 WS 后台任务(匹配队列扫描)。
|
||||
func Start(ctx context.Context) {
|
||||
go Matcher.Run(ctx) // 后台扫描,ctx 取消即退出
|
||||
}
|
||||
Reference in New Issue
Block a user