summaryrefslogtreecommitdiffstats
path: root/game/game.go
blob: 4a20f61402a0f2992b83452354b870acf9f8cfd5 (plain)
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
package game

import (
	"context"
)

func (ms *MServer) addSubscriber(s *MSub, userUUID string) {
	ms.subscribersMu.Lock()
	ms.Subscribers[s] = userUUID
	ms.Users[userUUID].Subscription = s
	ms.subscribersMu.Unlock()
}

func (ms *MServer) deleteSubscriber(s *MSub) {
	ms.subscribersMu.Lock()
	delete(ms.Users, ms.Subscribers[s])
	delete(ms.Subscribers, s)
	ms.subscribersMu.Unlock()
}

func (ms *MServer) broadcastMsg(msg string) {
	for s := range ms.Subscribers {
		select {
		case s.Msgs <- []byte(msg):
		default:
			go s.CloseSlow()
		}
	}
}

func (ms *MServer) broadcastLog() {
	for {
		l, done := QueuePop(&ms.gameCtx.Turn.Log)
		if done {
			break
		}
		ms.broadcastMsg(l)
	}
}

func (ms *MServer) start() {
	ms.subscribersMu.Lock()
	defer ms.subscribersMu.Unlock()

	ms.publishLimiter.Wait(context.Background())

	var players []Player
	for _, userUUID := range ms.Subscribers {
		players = append(players, InitPlayer(userUUID))
	}

	ms.gameCtxMu.Lock()
	ms.gameCtx = InitCtx(ms.randSeed, players)
	ms.gameCtx.logGameCtx()
	ms.gameCtxMu.Unlock()

	ms.broadcastMsg(MsgStart)
}

func (ms *MServer) roll() {
	ms.gameCtx.RollDice()
	ms.gameCtx.ProcessMovement()

	ms.gameCtx.logGameCtx()
	ms.broadcastLog()
}

func (ms *MServer) buy() {
	ms.gameCtx.Buy()

	ms.gameCtx.logGameCtx()
	ms.broadcastLog()
}