forked from yodigi7/pentago-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
211 lines (192 loc) · 5.06 KB
/
main.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
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
package main
import (
"encoding/json"
"log"
"net/http"
"sync"
"github.com/gorilla/websocket"
"github.com/yodigi7/pentago"
"github.com/yodigi7/pentago-server/internal/server"
"github.com/yodigi7/pentago-server/pkg/jsondefs"
)
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
// You can add checks here to allow only specific origins (like your frontend)
return true
},
}
var games sync.Map
func handleRead(conn *websocket.Conn, ch chan *jsondefs.Turn) {
defer close(ch)
for {
var turn jsondefs.Turn
if err := conn.ReadJSON(&turn); err != nil {
log.Println("Error reading message:", err)
break
} else {
ch <- &turn
}
}
log.Println("Exiting handle read")
}
// will wait on the channel and the write to the connection whatever messages come in
func handleWrite(conn *websocket.Conn, gameChange chan []byte, writer chan []byte, done chan bool) {
writerClosed := false
for !writerClosed {
select {
case jsonMsg, ok := <-gameChange:
if !ok {
done <- true
gameChange = nil
} else {
conn.WriteMessage(websocket.TextMessage, jsonMsg)
}
case jsonMsg, ok := <-writer:
if !ok {
writerClosed = true
break
} else {
conn.WriteMessage(websocket.TextMessage, jsonMsg)
}
}
}
log.Println("Exiting handle write")
}
func writeRespToChan(ch chan []byte, errResp jsondefs.GeneralResponse) error {
log.Printf("Sending message to channel: %s", errResp.Message)
bytes, err := json.Marshal(errResp)
// To prevent infinite recursion
if err != nil && errResp.Code != 500 {
log.Println("Error marshalling to bytes:", err)
writeRespToChan(ch, jsondefs.GeneralResponse{
Code: 500,
Message: "Error marshalling to bytes",
})
return err
}
ch <- bytes
return nil
}
func handleConnection(w http.ResponseWriter, r *http.Request) {
log.Println("New client connected!")
// Upgrade the HTTP connection to a WebSocket connection
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println("Upgrade error:", err)
return
}
defer conn.Close()
var (
color pentago.Space
gameChange chan []byte
game *server.Game
payload jsondefs.InitialConnection
)
if err = conn.ReadJSON(&payload); err != nil {
log.Println("Error reading initial json payload")
conn.WriteJSON(jsondefs.To400Response(err.Error()))
return
}
color, gameChange, game, err = server.SetupNewClient(payload.GameId, &games)
defer cleanupGame(game)
if err != nil {
log.Println("Error when setting up new client:", err)
conn.WriteJSON(jsondefs.To400Response(err.Error()))
return
}
conn.WriteJSON(jsondefs.InitialConnectionResponse{ColorNumber: color})
bytes, err := json.Marshal(jsondefs.To200Response("All players connected"))
if err != nil {
log.Println("Error marshalling response when all players are connected:", err)
return
}
if len(game.Channels) > 1 {
for _, ch := range game.Channels {
ch <- bytes
}
}
writeChan := make(chan []byte)
defer close(writeChan)
readChan := make(chan *jsondefs.Turn)
done := make(chan bool, 1)
// Start go routing to send updates to client when the other player makes a move
go handleWrite(conn, gameChange, writeChan, done)
go handleRead(conn, readChan)
// Start reading turns from the WebSocket
loop:
for {
select {
case val, ok := <-done:
{
if !ok || val {
break loop
}
}
case turn, ok := <-readChan:
{
if !ok {
break loop
}
if len(game.Channels) < 2 {
err = writeRespToChan(writeChan, jsondefs.To400Response("Invalid move, not everyone is connected yet"))
if err != nil {
break loop
}
continue
}
if game.Turn != color {
err = writeRespToChan(writeChan, jsondefs.To400Response("Invalid move, it's not your turn"))
if err != nil {
break loop
}
continue
}
err = game.PlaceMarble(turn.MarblePlacement.Row, turn.MarblePlacement.Col)
if err != nil {
err = writeRespToChan(writeChan, jsondefs.To400Response("Invalid move, unable to place marble there"))
if err != nil {
break loop
}
continue
}
err = game.RotateQuadrant(turn.Rotation.Quadrant, turn.Rotation.Direction)
if err != nil {
err = writeRespToChan(writeChan, jsondefs.To400Response("Invalid move, unable to rotate that way"))
if err != nil {
break loop
}
continue
}
game.UpdateChannels()
if game.IsDraw {
break loop
}
//TODO: remove when done debug
log.Printf("Inner Game: %+v\n", *game.Game)
log.Printf("Game: %+v\n", game)
}
}
}
if game != nil {
if game.Winner == pentago.Empty && !game.IsDraw {
writeRespToChan(writeChan, jsondefs.To200Response("YOU WIN"))
}
}
conn.Close()
log.Println("Exiting main handler")
}
func cleanupGame(g *server.Game) {
g.CloseChannels()
games.Delete(g.Id)
}
func main() {
log.SetFlags(log.LstdFlags | log.Lshortfile)
// Serve the WebSocket at the /ws route
http.HandleFunc("/ws", handleConnection)
// Start the server
log.Println("Server started on :8080")
err := http.ListenAndServe(":8080", nil)
if err != nil {
log.Fatal("ListenAndServe failed:", err)
}
}