~whereswaldon/pointstar

ref: 6ce31da671c411c5894943afae14404c660f8e4f pointstar/server/main.go -rw-r--r-- 5.2 KiB
6ce31da6Chris Waldon feat: UI connects to server and can play 1 year, 9 months ago
                                                                                
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"sync"
	"time"

	"git.sr.ht/~whereswaldon/pointstar/gamestate"
	. "git.sr.ht/~whereswaldon/pointstar/server/protocol"
	"nhooyr.io/websocket"
)

type GameServer struct {
	sync.Mutex
	PlayerConns []*PlayerConn
	gamestate.GameState
}

func (g *GameServer) AddPlayer(p *PlayerConn, name string) error {
	return g.whileLocked(func() error {
		playerNum := len(g.PlayerConns)
		g.PlayerConns = append(g.PlayerConns, p)
		if err := p.Send(AssignPlayerNumber{Number: playerNum}); err != nil {
			return fmt.Errorf("failed to assign player number: %w", err)
		}
		g.GameState.AddPlayer(name)
		go func() {
			for {
				msgs, err := p.Recv()
				if err != nil {
					log.Println(err)
					return
				}
				log.Printf("Got message %v", msgs)
				for _, msg := range msgs {
					if err := g.HandleMessage(playerNum, msg); err != nil {
						log.Println(err)
						return
					}
				}
			}
		}()
		return g.pushGameState()
	})
}

func (g *GameServer) StartGame(playerNum int, msg StartGame) error {
	if playerNum != 0 {
		return fmt.Errorf("Only player 0 can initiate the game")
	}
	return g.whileLocked(func() error {
		if g.GameState.Phase != gamestate.Lobby {
			return fmt.Errorf("Game already started")
		}
		g.GameState.Setup()

		return g.advanceGame()
	})
}

// advanceGame advances the game state and notifies all players of the new state. It
// should only be called from a context that has locked the game state
func (g *GameServer) advanceGame() error {
	g.Advance()
	if err := g.pushGameState(); err != nil {
		return fmt.Errorf("failed updating players: %w", err)
	}
	return nil
}

// pushGameState updates all players about the current game state. It must be called
// while the GameServer is locked, but does not perform locking itself.
func (g *GameServer) pushGameState() error {
	for i, player := range g.PlayerConns {
		if err := player.Send(g.GameState); err != nil {
			return fmt.Errorf("failed notifying player %d about new game state: %w", i, err)
		}
	}
	return nil
}

func (g *GameServer) whileLocked(f func() error) error {
	g.Lock()
	defer g.Unlock()

	return f()
}

func (g *GameServer) PassTurn(playerNum int, msg PassTurn) error {
	return g.whileLocked(func() error {
		g.GameState.Pass(playerNum)
		return g.advanceGame()
	})
}

func (g *GameServer) PlayCard(playerNum int, msg PlayCard) error {
	return g.whileLocked(func() error {
		g.GameState.TakeTurn(playerNum, msg.Index)
		return g.advanceGame()
	})
}

func (g *GameServer) HandleMessage(playerNum int, msg interface{}) error {
	switch message := msg.(type) {
	case StartGame:
		return g.StartGame(playerNum, message)
	case PlayCard:
		return g.PlayCard(playerNum, message)
	case PassTurn:
		return g.PassTurn(playerNum, message)
	default:
		return fmt.Errorf("unknown message %v", msg)
	}
}

func main() {
	log.SetFlags(log.Lshortfile | log.LstdFlags)
	game := gamestate.GameState{}
	game.SetupWithPlayers(4)
	gs := GameServer{}
	Register()

	fn := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		c, err := websocket.Accept(w, r, nil)
		if err != nil {
			log.Println(err)
			return
		}
		p := &PlayerConn{Conn: c, Context: context.Background()}
		msgs, err := p.Recv()
		if err != nil {
			log.Println(err)
		}
		log.Println("Accepted websocket connection")
		if msg, ok := msgs[0].(SetPlayerName); ok {
			if err := gs.AddPlayer(p, msg.Name); err != nil {
				log.Println(err)
			}
		} else {
			defer c.Close(http.StatusExpectationFailed, "missing SetPlayerName message")
			if err := p.Send(ErrorMessage{}); err != nil {
				log.Printf("Failed to notify client that they didn't send a SetPlayerName message: %v", err)
			}
		}
	})

	for i := 0; i < 3; i++ {
		go LaunchAIPlayer(fmt.Sprintf("Player %d", i))
	}

	err := http.ListenAndServe("localhost:8080", fn)
	log.Fatal(err)
}

func LaunchAIPlayer(name string) {
	time.Sleep(time.Second * 10)
	ctx := context.Background()
	logPrint := func(format string, args ...interface{}) {
		log.Printf("%s:"+format, append([]interface{}{name}, args...)...)
	}
	socket, _, err := websocket.Dial(ctx, "ws://localhost:8080", nil)
	if err != nil {
		logPrint("websocket error: %v", err)
	}
	p := &PlayerConn{Conn: socket, Context: ctx}
	if err := p.Send(SetPlayerName{Name: name}); err != nil {
		logPrint("error setting player name: %v", err)
	}
	playerNum := 0
	if msgs, err := p.Recv(); err != nil {
		logPrint("error recving player num assignment: %v", err)
	} else {
		for _, msg := range msgs {
			if assignment, ok := msg.(AssignPlayerNumber); ok {
				playerNum = assignment.Number
				break
			} else {
				logPrint("got unexpected message (type %T): %v", msg, msg)
			}
		}
	}
	if playerNum == 0 {
		time.Sleep(time.Second)
		if err := p.Send(StartGame{}); err != nil {
			logPrint("failed starting game: %v", err)
		}
	}
	for {
		if msgs, err := p.Recv(); err != nil {
			log.Println(err)
		} else {
			for _, msg := range msgs {
				logPrint("%v", msg)
				switch message := msg.(type) {
				case *gamestate.GameState:
					gs := message
					if gs.Phase == gamestate.WaitingOnPlayer && gs.Turn == playerNum {
						time.Sleep(time.Second)
						if err := p.TakeTurn(playerNum, gs); err != nil {
							logPrint("error taking turn: %v", err)
						}
					}
				default:
					logPrint("unexpected message from server (type %T): %v", msg, msg)
				}
			}
		}
	}

}