-
Notifications
You must be signed in to change notification settings - Fork 4
/
game.go
160 lines (129 loc) · 2.57 KB
/
game.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
package main
import (
"bytes"
"encoding/binary"
"fmt"
"io"
"net"
"sync"
)
const (
STATE_HANDSHAKE = 0
STATE_STATUS = 1
STATE_LOGIN = 2
)
type Game struct {
MaxPlayers int
players map[string]*Player
playersLock sync.Mutex
out chan []byte
}
func NewGame(maxPlayers int) *Game {
return &Game{
MaxPlayers: maxPlayers,
players: make(map[string]*Player),
out: make(chan []byte, 256),
}
}
func (g *Game) Listen(address string) {
ln, err := net.Listen("tcp", address)
if err != nil {
panic(err)
}
go g.send()
for {
conn, err := ln.Accept()
if err != nil {
fmt.Println(err)
} else {
go g.handleConnection(conn)
}
}
}
func (g *Game) AddPlayer(name string, conn net.Conn) {
p := NewPlayer(name, conn, g)
p.Run()
g.playersLock.Lock()
g.players[name] = p
g.playersLock.Unlock()
WriteChatMessage(g, name+" joined the game")
}
func (g *Game) RemovePlayer(name string) {
g.playersLock.Lock()
delete(g.players, name)
g.playersLock.Unlock()
WriteChatMessage(g, name+" left the game")
}
func (g *Game) Broadcast(data []byte) {
g.playersLock.Lock()
for _, player := range g.players {
player.Write(data)
}
g.playersLock.Unlock()
}
func (g *Game) Write(data []byte) (int, error) {
g.out <- data
return len(data), nil
}
func (g *Game) send() {
for {
g.Broadcast(<-g.out)
}
}
func (g *Game) handleConnection(conn net.Conn) {
var state uint64 = STATE_HANDSHAKE
var username string
fmt.Println("New connection")
for {
length, err := ReadVarint(conn)
if err != nil {
fmt.Println("Connection died")
return
}
buf := make([]byte, length)
io.ReadFull(conn, buf)
r := bytes.NewReader(buf)
id, _ := binary.ReadUvarint(r)
switch state {
case STATE_HANDSHAKE:
if id != 0x00 {
continue
}
state = ReadHandshake(r).State
case STATE_STATUS:
switch id {
case 0x00:
g.playersLock.Lock()
playerCount := len(g.players)
g.playersLock.Unlock()
WriteStatus(conn, Status{
Version{
Name: MinecraftVersion,
Protocol: MinecraftProtocol,
},
Players{
Max: g.MaxPlayers,
Online: playerCount,
},
Description{"Awesomeness"},
})
case 0x01:
WriteVarint(conn, uint64(len(buf)))
conn.Write(buf)
}
case STATE_LOGIN:
switch id {
case 0x00:
if (len(g.players)+1 > g.MaxPlayers) {
return
}
uuid := "de305d54-75b4-431b-adb2-eb6b9e546013"
username = ReadString(r)
WriteLoginSuccess(conn, uuid, username)
WriteSetCompression(conn, 65536)
g.AddPlayer(username, conn)
return
}
}
}
}