-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathroom.go
110 lines (91 loc) · 2.14 KB
/
room.go
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package main
import (
"errors"
"math/rand"
)
// Room contains the state of a game room.
type Room struct {
ID string
PlayerA, PlayerB *Player
RoleA, RoleB GameRole
Spectators []*Player
Board *Board
}
var roomMap = make(map[string]*Room)
func makeRoom() *Room {
id := UniqIDf()
room := &Room{
ID: id,
}
roomMap[id] = room
return room
}
// Started returns if the game for this room has been started or not.
func (r *Room) Started() bool {
return r.Board != nil
}
// StartGame starts the game of this room.
func (r *Room) StartGame() (started bool) {
if r.Started() {
return true
}
playerReady := func(player *Player) bool {
return player != nil && player.Ready
}
if !playerReady(r.PlayerA) || !playerReady(r.PlayerB) {
return false
}
if rand.Intn(2) == 0 {
r.RoleA = Order
r.RoleB = Chaos
} else {
r.RoleA = Chaos
r.RoleB = Order
}
r.Board = MakeBoard(Order)
r.SendAll("startgame", r.RoleA.String(), r.RoleB.String())
return true
}
// StopGame stops the game of this room.
func (r *Room) StopGame() bool {
if !r.Started() {
return true
}
r.Board = nil
r.SendAll("stopgame")
return true
}
// AddPlayer adds the given player to the current game.
func (r *Room) AddPlayer(player *Player) (playerA bool, err error) {
if r.PlayerA == nil {
r.PlayerA = player
playerA = true
} else if r.PlayerB == nil {
r.PlayerB = player
playerA = false
} else {
return false, errors.New("room-full")
}
return playerA, nil
}
// AddSpectator adds the given player to the game as a spectator.
func (r *Room) AddSpectator(player *Player) {
r.Spectators = append(r.Spectators, player)
}
// SendAll sends the given type and args to every player and spectator in the
// room.
func (r *Room) SendAll(typ string, args ...string) {
if r.PlayerA != nil {
r.PlayerA.Conn.Send(typ, args...)
}
if r.PlayerB != nil {
r.PlayerB.Conn.Send(typ, args...)
}
r.SendSpectators(typ, args...)
}
// SendSpectators sends the given type and args to every specator in the room.
func (r *Room) SendSpectators(typ string, args ...string) {
for _, spec := range r.Spectators {
spec.Conn.Send(typ, args...)
}
}