房间更改为默认线程不安全,并通过可选项可创建线程安全的房间

This commit is contained in:
kercylan98 2023-05-19 09:37:47 +08:00
parent 5488b3d455
commit 31cb4a2f66
2 changed files with 15 additions and 5 deletions

View File

@ -2,16 +2,16 @@ package builtin
import (
"github.com/kercylan98/minotaur/game"
"github.com/kercylan98/minotaur/utils/asynchronization"
"github.com/kercylan98/minotaur/utils/hash"
"github.com/kercylan98/minotaur/utils/log"
"github.com/kercylan98/minotaur/utils/synchronization"
"go.uber.org/zap"
)
func NewRoom[PlayerID comparable, Player game.Player[PlayerID]](guid int64, options ...RoomOption[PlayerID, Player]) *Room[PlayerID, Player] {
room := &Room[PlayerID, Player]{
guid: guid,
players: synchronization.NewMap[PlayerID, Player](),
players: asynchronization.NewMap[PlayerID, Player](),
}
for _, option := range options {
option(room)
@ -24,7 +24,7 @@ type Room[PlayerID comparable, Player game.Player[PlayerID]] struct {
owner PlayerID
noMaster bool
playerLimit int
players *synchronization.Map[PlayerID, Player]
players hash.Map[PlayerID, Player]
kickCheckHandle func(id, target PlayerID) error
playerJoinRoomEventHandles []game.PlayerJoinRoomEventHandle[PlayerID, Player]
@ -45,7 +45,7 @@ func (slf *Room[PlayerID, Player]) GetPlayer(id PlayerID) Player {
}
func (slf *Room[PlayerID, Player]) GetPlayers() hash.MapReadonly[PlayerID, Player] {
return slf.players
return slf.players.(hash.MapReadonly[PlayerID, Player])
}
func (slf *Room[PlayerID, Player]) GetPlayerCount() int {

View File

@ -1,10 +1,20 @@
package builtin
import "github.com/kercylan98/minotaur/game"
import (
"github.com/kercylan98/minotaur/game"
"github.com/kercylan98/minotaur/utils/synchronization"
)
// RoomOption 房间构建可选项
type RoomOption[PlayerID comparable, Player game.Player[PlayerID]] func(room *Room[PlayerID, Player])
// WithRoomSync 通过线程安全的方式创建房间
func WithRoomSync[PlayerID comparable, Player game.Player[PlayerID]]() RoomOption[PlayerID, Player] {
return func(room *Room[PlayerID, Player]) {
room.players = synchronization.NewMap[PlayerID, Player]()
}
}
// WithRoomPlayerLimit 限制房间的玩家数量上限
func WithRoomPlayerLimit[PlayerID comparable, Player game.Player[PlayerID]](playerLimit int) RoomOption[PlayerID, Player] {
return func(room *Room[PlayerID, Player]) {