-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlobby.go
More file actions
91 lines (72 loc) · 1.79 KB
/
lobby.go
File metadata and controls
91 lines (72 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package rose
import "sync"
import "errors"
import "fmt"
type roomConstructor func(RoomID) Room
// Lobby collection of rooms
type Lobby struct {
server *Server
rooms map[RoomID]*roomInfo
sync.RWMutex
}
type roomInfo struct {
room *RoomFront
userCount int
}
// RoomLobby global lobby instance
var RoomLobby *Lobby
func initializeLobby(server *Server) {
RoomLobby = &Lobby{
server: server,
rooms: make(map[RoomID]*roomInfo),
}
}
// NewRoom Create a new room and save it in the lobby
func (lobby *Lobby) NewRoom(id RoomID, constructor roomConstructor) *RoomFront {
// Lock room list for writing
lobby.Lock()
defer lobby.Unlock()
// Only create a new room if the ID is not yet taken
var front *RoomFront
if _, ok := lobby.rooms[id]; !ok {
// Create the new room
front = newRoomFront(constructor(id))
lobby.rooms[id] = &roomInfo{
room: front,
}
// Start up the goroutine that will handle the room
front.start()
}
return front
}
// JoinRoom Add user to room
func (lobby *Lobby) JoinRoom(id RoomID, user User) (*RoomFront, error) {
lobby.Lock()
defer lobby.Unlock()
roomInfo, ok := lobby.rooms[id]
if !ok {
return nil, errors.New(fmt.Sprint("Lobby is unable to join room", id))
}
roomInfo.userCount++
roomInfo.room.addUser(user)
return roomInfo.room, nil
}
// LeaveRoom Remove user from room and cleanup if required
func (lobby *Lobby) LeaveRoom(id RoomID, user User) error {
lobby.Lock()
defer lobby.Unlock()
roomInfo, ok := lobby.rooms[id]
if !ok {
return errors.New(fmt.Sprint("Lobby is unable to leave room", id))
}
roomInfo.userCount--
roomInfo.room.removeUser(user)
// Destroy room when empty
if roomInfo.userCount == 0 {
delete(lobby.rooms, id)
roomInfo.room.QueueAction(func(room Room) {
room.Base().destroying = true
})
}
return nil
}