-
Notifications
You must be signed in to change notification settings - Fork 0
/
player.go
92 lines (68 loc) · 1.9 KB
/
player.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package player
import (
"errors"
"log"
"github.com/aerlaut/go-chess-backend/internal/message"
"github.com/gorilla/websocket"
)
type player struct {
Id string `json:"id"`
Connection *websocket.Conn `json:"-"`
}
var playersList = make(map[string][]player)
func newPlayer(id string, c *websocket.Conn) player {
return player{
Id: id,
Connection: c,
}
}
func Join(ctx *message.Context, m *message.Message) error {
players, prs := playersList[m.GameId]
// Initialize players list if the game doesn't have any player yet
if !prs {
playersList[m.GameId] = []player{}
log.Printf("[GAME] - Game %s initialized", m.GameId)
}
// Check if the player exists
playerExists := false
for _, player := range players {
if player.Id == m.PlayerId {
playerExists = true
break
}
}
if !playerExists {
playersList[m.GameId] = append(players, newPlayer(m.PlayerId, ctx.Conn))
log.Printf("[GAME %s] - New user registered: Player %s added to the game", m.GameId, m.PlayerId)
log.Printf("[GAME %s] - Players in game: %d", m.GameId, len(playersList[m.GameId]))
}
return nil
}
func Leave(ctx *message.Context, m *message.Message) error {
players, prs := playersList[m.GameId]
if !prs {
return errors.New("GAME NOT FOUND")
}
remainingPlayers := []player{}
for _, player := range players {
if player.Id != m.PlayerId {
remainingPlayers = append(remainingPlayers, player)
}
}
playersList[m.GameId] = remainingPlayers
log.Printf("[GAME %s] - Player %s left", m.GameId, m.PlayerId)
return nil
}
func MakeMove(ctx *message.Context, m *message.Message) error {
players, prs := playersList[m.GameId]
if !prs {
return errors.New("GAME NOT FOUND")
}
for _, player := range players {
if player.Id != m.PlayerId {
log.Printf("[GAME %s] - Sending move to player %s", m.GameId, player.Id)
player.Connection.WriteMessage(ctx.MsgType, []byte(m.Data))
}
}
return nil
}