-
Notifications
You must be signed in to change notification settings - Fork 15
/
worker.go
71 lines (61 loc) · 1.45 KB
/
worker.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
package main
import (
"github.com/Edouard127/redditplacebot/board"
"github.com/Edouard127/redditplacebot/client"
"sync"
"time"
)
type Worker struct {
waitList map[*client.Client]time.Time
clients []*client.Client
ticker *time.Ticker
board *board.Board
clientLock sync.Mutex
}
func NewWorker(b *board.Board) (k *Worker) {
return &Worker{
waitList: make(map[*client.Client]time.Time, 0),
clients: make([]*client.Client, 0),
ticker: time.NewTicker(time.Second),
board: b,
}
}
func (k *Worker) ClientJoin(client ...*client.Client) {
k.clientLock.Lock()
defer k.clientLock.Unlock()
k.board.SetController(client[0])
k.clients = append(k.clients, client...)
}
func (k *Worker) Run() {
for {
select {
case <-k.ticker.C:
changed := k.board.GetDifferentData()
if len(changed) > 0 {
split := splitMap(changed, len(k.clients))
for i, c := range k.clients {
c.Assign(split[i])
if t, ok := k.waitList[c]; ok {
if !t.After(time.Now()) {
c.Logger.Info("Placing c after wait")
k.waitList[c] = c.Place(k.board)
}
} else {
c.Logger.Info("Placing c")
k.waitList[c] = c.Place(k.board)
}
}
}
}
}
}
func splitMap(data map[board2.Point]board2.Color, n int) []map[board2.Point]board2.Color {
split := make([]map[board2.Point]board2.Color, n)
i := 0
for k, v := range data {
split[i%n] = make(map[board2.Point]board2.Color)
split[i%n][k] = v
i++
}
return split
}