-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmultiplayer.go
More file actions
311 lines (267 loc) · 6.83 KB
/
multiplayer.go
File metadata and controls
311 lines (267 loc) · 6.83 KB
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
package main
import (
"context"
"fmt"
"sync"
"time"
"github.com/charmbracelet/ssh"
)
// Player represents a connected player
type Player struct {
ID string
Session ssh.Session
Color Color
Name string
GameID string
Connected bool
UpdateChan chan GameUpdate // Channel for sending updates to the player's model
}
// GameUpdate represents an update to broadcast to players
type GameUpdate struct {
Type string // "move", "cursor", "select", "gamestate"
Data interface{} // The actual update data
FromPlayer string // Which player sent the update
}
// GameSession manages a single game between two players
type GameSession struct {
ID string
Game *Game
White *Player
Black *Player
Updates chan GameUpdate
ctx context.Context
cancel context.CancelFunc
mu sync.RWMutex
}
func NewGameSession(id string, white, black *Player) *GameSession {
ctx, cancel := context.WithCancel(context.Background())
session := &GameSession{
ID: id,
Game: NewGame(),
White: white,
Black: black,
Updates: make(chan GameUpdate, 10),
ctx: ctx,
cancel: cancel,
}
// Assign colors and game ID to players
white.Color = White
white.GameID = id
black.Color = Black
black.GameID = id
// Start the update broadcaster
go session.handleUpdates()
return session
}
func (gs *GameSession) handleUpdates() {
for {
select {
case <-gs.ctx.Done():
return
case update := <-gs.Updates:
gs.broadcastUpdate(update)
}
}
}
func (gs *GameSession) broadcastUpdate(update GameUpdate) {
gs.mu.RLock()
defer gs.mu.RUnlock()
// Send update to both players (if connected) via their update channels
if gs.White != nil && gs.White.Connected && gs.White.UpdateChan != nil {
select {
case gs.White.UpdateChan <- update:
default:
// Channel full, drop update
}
}
if gs.Black != nil && gs.Black.Connected && gs.Black.UpdateChan != nil {
select {
case gs.Black.UpdateChan <- update:
default:
// Channel full, drop update
}
}
}
func (gs *GameSession) GetPlayer(playerID string) *Player {
gs.mu.RLock()
defer gs.mu.RUnlock()
if gs.White != nil && gs.White.ID == playerID {
return gs.White
}
if gs.Black != nil && gs.Black.ID == playerID {
return gs.Black
}
return nil
}
func (gs *GameSession) GetOpponent(playerID string) *Player {
gs.mu.RLock()
defer gs.mu.RUnlock()
if gs.White != nil && gs.White.ID == playerID {
return gs.Black
}
if gs.Black != nil && gs.Black.ID == playerID {
return gs.White
}
return nil
}
func (gs *GameSession) IsPlayerTurn(playerID string) bool {
player := gs.GetPlayer(playerID)
if player == nil {
return false
}
return gs.Game.CurrentTurn == player.Color
}
func (gs *GameSession) Disconnect(playerID string) {
gs.mu.Lock()
defer gs.mu.Unlock()
var disconnectedPlayer, remainingPlayer *Player
if gs.White != nil && gs.White.ID == playerID {
gs.White.Connected = false
disconnectedPlayer = gs.White
remainingPlayer = gs.Black
}
if gs.Black != nil && gs.Black.ID == playerID {
gs.Black.Connected = false
disconnectedPlayer = gs.Black
remainingPlayer = gs.White
}
// Notify remaining player of opponent disconnect
if remainingPlayer != nil && remainingPlayer.Connected && remainingPlayer.UpdateChan != nil {
disconnectUpdate := GameUpdate{
Type: "opponent_disconnected",
Data: map[string]any{
"disconnectedPlayer": disconnectedPlayer.Name,
},
}
select {
case remainingPlayer.UpdateChan <- disconnectUpdate:
default:
}
}
// If both players disconnected, cleanup
if (gs.White == nil || !gs.White.Connected) && (gs.Black == nil || !gs.Black.Connected) {
gs.cleanup()
}
}
func (gs *GameSession) cleanup() {
gs.cancel()
close(gs.Updates)
}
// GameManager handles matchmaking and game coordination
type GameManager struct {
playerQueue []*Player
activeGames map[string]*GameSession
playerToGame map[string]string // playerID -> gameID
mu sync.RWMutex
gameCounter int
}
var gameManager *GameManager
var gameManagerOnce sync.Once
func GetGameManager() *GameManager {
gameManagerOnce.Do(func() {
gameManager = &GameManager{
playerQueue: make([]*Player, 0),
activeGames: make(map[string]*GameSession),
playerToGame: make(map[string]string),
}
})
return gameManager
}
func (gm *GameManager) AddPlayer(player *Player) {
gm.mu.Lock()
defer gm.mu.Unlock()
// Add to queue
gm.playerQueue = append(gm.playerQueue, player)
// Try to match with another player
if len(gm.playerQueue) >= 2 {
white := gm.playerQueue[0]
black := gm.playerQueue[1]
// Remove from queue
gm.playerQueue = gm.playerQueue[2:]
// Create game
gm.gameCounter++
gameID := fmt.Sprintf("game_%d", gm.gameCounter)
session := NewGameSession(gameID, white, black)
gm.activeGames[gameID] = session
gm.playerToGame[white.ID] = gameID
gm.playerToGame[black.ID] = gameID
// Notify players they've been matched
matchUpdate := GameUpdate{
Type: "matched",
Data: map[string]any{
"gameID": gameID,
"opponent": map[string]string{
"white_opponent": black.Name,
"black_opponent": white.Name,
},
},
}
// Send match update to both players via their channels
if white.UpdateChan != nil {
select {
case white.UpdateChan <- matchUpdate:
default:
}
}
if black.UpdateChan != nil {
select {
case black.UpdateChan <- matchUpdate:
default:
}
}
}
}
func (gm *GameManager) RemovePlayer(playerID string) {
gm.mu.Lock()
defer gm.mu.Unlock()
// Remove from queue if present
for i, player := range gm.playerQueue {
if player.ID == playerID {
gm.playerQueue = append(gm.playerQueue[:i], gm.playerQueue[i+1:]...)
break
}
}
// Handle active game disconnection
if gameID, exists := gm.playerToGame[playerID]; exists {
if session, gameExists := gm.activeGames[gameID]; gameExists {
session.Disconnect(playerID)
// Clean up if game is over
if (session.White == nil || !session.White.Connected) &&
(session.Black == nil || !session.Black.Connected) {
delete(gm.activeGames, gameID)
delete(gm.playerToGame, session.White.ID)
delete(gm.playerToGame, session.Black.ID)
}
}
delete(gm.playerToGame, playerID)
}
}
func (gm *GameManager) GetGameSession(playerID string) *GameSession {
gm.mu.RLock()
defer gm.mu.RUnlock()
if gameID, exists := gm.playerToGame[playerID]; exists {
return gm.activeGames[gameID]
}
return nil
}
func (gm *GameManager) BroadcastUpdate(playerID string, update GameUpdate) {
session := gm.GetGameSession(playerID)
if session != nil {
update.FromPlayer = playerID
select {
case session.Updates <- update:
case <-time.After(100 * time.Millisecond):
// Drop update if channel is full
}
}
}
func (gm *GameManager) GetQueuePosition(playerID string) int {
gm.mu.RLock()
defer gm.mu.RUnlock()
for i, player := range gm.playerQueue {
if player.ID == playerID {
return i + 1
}
}
return -1
}