You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
hexmap/server/room/room.go

55 lines
2.0 KiB

package room
import (
"github.com/rs/xid"
"go.uber.org/zap"
"hexmap-server/state"
)
// NewOptions is the set of information used to control what a room starts with.
type NewOptions struct {
// BaseLogger is the logger that the room should attach its data to.
BaseLogger *zap.Logger
// StartingState is a state.Synced that defines the state of the room on creation.
StartingState state.Synced
// StartingClientOptions sets the configuration of the first client to be created, the one that will be returned
// from New.
StartingClientOptions NewClientOptions
}
// room is a room as seen from within - the information needed for the room process to do its duties.
type room struct {
// id is the room's internal ID - not to be confused with the ID of the map it is serving.
id xid.ID
// incomingChannel is the channel the room uses to receive messages. The room itself owns this channel,
// so when the clients map is empty, it can be closed.
incomingChannel chan ClientMessage
// clients contains the map of active clients, each of which is known to have a reference to this room.
clients map[xid.ID]internalClient
// currentState contains the active state being used by actions right now.
currentState state.Synced
// logger is the logger that this room will use. It contains context fields for the room's important fields.
logger *zap.Logger
}
// Creates and starts up a new room, joins a new client to it and returns that client.
func New(opts NewOptions) *Client {
logger := opts.BaseLogger.Named("Room")
id := xid.New()
r := room{
id: id,
incomingChannel: make(chan ClientMessage),
clients: make(map[xid.ID]internalClient),
currentState: opts.StartingState,
logger: logger,
}
go r.act()
return r.newClient(opts.StartingClientOptions)
}
// newClient creates a new client belonging to this room with a random ID.
// The new client will be automatically joined to the channel.
func (r *room) newClient(opts NewClientOptions) *Client {
return newClientForRoom(r.id, r.incomingChannel, opts)
}