aboutsummaryrefslogtreecommitdiff
path: root/go/activities/session.go
blob: f910c67c32c3a918ea840ddad59ced159896eb9f (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
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
package activities

import (
	"muhq.space/muhqs-game/go/game"
	"muhq.space/muhqs-game/go/ui"
)

type Session struct {
	ui.Collection
	playerList         *ui.Buffer
	ctrl               game.PlayerControl
	handleNotification func(game.PlayerNotification)
}

func (s *Session) AddPlayer(name string) {
	// TODO: remove a AI
	s.playerList.AddLine(name)
}

func (s *Session) ReadyPlayer(name string) {
	i := 0
	for l := range s.playerList.LinesSeq() {
		if l == name {
			s.playerList.PrefixLine(i, "!")
			return
		}
		i = i + 1
	}
}

func (s *Session) Update() error {
	n, err := s.ctrl.RecvNotification()
	if err != nil {
		// FIXME
	}

	if n.Valid() {
		switch n.Notification {
		case game.JoinedPlayerNotification:
			s.AddPlayer(n.Context.(string))
		case game.ReadyPlayerNotification:
			s.ReadyPlayer(n.Context.(string))
		default:
			s.handleNotification(n)
		}
	}

	if err := ui.Update(); err != nil {
		return err
	}

	return s.Collection.Update()
}

func (s *Session) Layout(int, int) (int, int) {
	return s.Collection.Layout()
}

func NewSession(wdth, hght int, title string, ctrl game.PlayerControl, startFunc func(), handleNotificataion func(game.PlayerNotification)) *Session {
	s := &Session{
		Collection:         ui.Collection{Width: wdth, Height: hght},
		ctrl:               ctrl,
		handleNotification: handleNotificataion,
	}

	titleTextBox := ui.NewAutoTextBox(
		s.Width/2-50,
		50,
		title)
	s.AddWidget(titleTextBox)

	s.playerList = ui.NewBuffer(
		0,
		70,
		s.Width,
		s.Height-70-40)

	s.AddWidget(ui.NewSimpleButton(
		s.Width/2-200,
		s.Height-40,
		200,
		40,
		"ready",
		func(*ui.SimpleButton) {
			ctrl.SendNotification(game.NewReadyPlayerNotification(ctrl.Player()))
		}))

	s.AddWidget(ui.NewSimpleButton(
		s.Width/2+200,
		s.Height-40,
		200,
		40,
		"start",
		func(*ui.SimpleButton) {
			startFunc()
		}))

	return s
}