-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
180 lines (149 loc) · 3.68 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
package main
import (
"encoding/json"
"fmt"
"log"
"math/rand"
"net/http"
"strconv"
"time"
"github.com/gorilla/websocket"
)
type Message struct {
Data interface{} `json:"data"`
MsgType int `json:"msgType"`
Room int32 `json:"room"`
}
type ReceivedMessage struct {
Data interface{} `json:"data"`
MsgType int `json:"msgType"`
player int
}
var sessions = map[int32]Session{}
type Session struct {
game *Game
room int32
players map[int]Player
}
type Player struct {
number int
conn *websocket.Conn
}
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
var idCounter Id = 0
func main() {
loadTileSet()
rand.Seed(time.Now().UnixNano())
upgrader.CheckOrigin = func(r *http.Request) bool { return true }
http.HandleFunc("/join", func(w http.ResponseWriter, r *http.Request) {
room, err := strconv.Atoi(r.URL.Query().Get("room"))
if err != nil {
w.Write([]byte("Invalid room"))
return
}
session, ok := sessions[int32(room)]
if !ok {
w.Write([]byte("Room doesn't exist"))
return
}
session.join(w, r)
})
http.HandleFunc("/sessions", func(w http.ResponseWriter, r *http.Request) {
// Normal http-get request for fetching an array of available sessions
fmt.Println("Fetching sessions")
type str struct {
Room int32 `json:"room"`
Players int `json:"players"`
}
// Format sessions into a more json-compatible format
array := []str{}
for room, ses := range sessions {
array = append(array, str{Room: room, Players: len(ses.players)})
}
v, _ := json.Marshal(array)
w.Header().Set("Access-Control-Allow-Origin", "*") // Allow CORS
w.Write(v)
})
http.HandleFunc("/create", func(w http.ResponseWriter, r *http.Request) {
session := createSession()
session.join(w, r)
})
http.Handle("/", http.FileServer(http.Dir("./public")))
log.Fatal(http.ListenAndServe(":8123", nil))
}
func (session Session) join(w http.ResponseWriter, r *http.Request) {
// Websocket logic
conn, err := upgrader.Upgrade(w, r, nil)
if (err != nil) {
fmt.Println(err)
return
}
playerNum := 0
i := 1
for playerNum == 0 {
_, ok := session.players[i]
if !ok {
playerNum = i
}
i++
}
conn.WriteJSON(&Message{playerNum, 2, session.room})
newPlayer := Player{playerNum, conn}
session.players[playerNum] = newPlayer
fmt.Println("New player", newPlayer.number)
conn.WriteJSON(&Message{session.game, 0, session.room})
go func() {
for {
_, p, err := conn.ReadMessage()
// Connection broken; remove player from room
if err != nil {
fmt.Println(err)
conn.Close()
for i := range session.players {
if session.players[i].number == playerNum {
delete(session.players, playerNum)
if len(session.players) == 0 {
delete(sessions, session.room)
}
return
}
}
}
var message ReceivedMessage
message.player = newPlayer.number
json.Unmarshal(p, &message) // Parse message from json
session.game.ReceiveData(message)
}
}()
}
func createSession() (session Session) {
updateChan := make(chan Message)
go func() {
// Read incoming tick updates and them broadcast to all players
for {
message := <-updateChan
for _, p := range session.players {
p.conn.WriteJSON(&message)
}
}
}()
game := MakeGame(getLevel(0), updateChan)
// Generate a random room number, and make sure it's unique
var roomNum int32
ok := true
for ok {
roomNum = rand.Int31()
_, ok = sessions[roomNum]
}
fmt.Println("Created new room with number", roomNum)
sessions[roomNum] = Session{
game: game,
players: map[int]Player{},
room: roomNum,
}
session = sessions[roomNum]
return session
}