-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSpaceInvaders.go
More file actions
404 lines (378 loc) · 11.2 KB
/
SpaceInvaders.go
File metadata and controls
404 lines (378 loc) · 11.2 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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
package main
//go get github.com/faiface/pixel
//cd $GOPATH/src/golang.org/x/ && git clone https://github.com/golang/image.git
//go get github.com/faiface/glhf
//go get github.com/go-gl/glfw/v3.2/glfw
import (
"bytes"
"container/list"
"encoding/json"
"fmt"
"image"
_ "image/png"
"math"
"os"
"strconv"
"sync"
"time"
"spaceInvaders/BEBcast"
"spaceInvaders/PP2PLink"
"spaceInvaders/Structs"
"github.com/faiface/pixel"
"github.com/faiface/pixel/pixelgl"
"github.com/faiface/pixel/text"
"golang.org/x/image/colornames"
"golang.org/x/image/font/basicfont"
)
var sprites, err = loadPicture("sprites/sprites.png")
var PortBind = ""
var serverShipAddr = []string{"127.0.0.1:4002"}
var serverMainAddr = []string{"127.0.0.1:4003"}
var monsterMutex = &sync.Mutex{}
var shipMutex = &sync.Mutex{}
var shotMutex = &sync.Mutex{}
var mShotMutex = &sync.Mutex{}
var winW = 400.0
var winH = 300.0
type Spaceship Structs.Spaceship
type Monster Structs.Monster
type Shot Structs.Shot
type ClientData Structs.ClientData
type ServerData Structs.ServerData
func CreateSpaceship() *Spaceship {
ship := Spaceship{}
ship.Shipsprite = pixel.NewSprite(sprites, pixel.R(20, sprites.Bounds().H()-60, 38, sprites.Bounds().H()-47))
ship.X = 0
ship.Y = 0
return &ship
}
func CreateMonster(x float64, y float64, mSprite bool, mMovingRight bool, monstertype float64, id byte) *Monster {
monster := Monster{}
switch monstertype {
case 0:
monster.Monstersprite1 = pixel.NewSprite(sprites, pixel.R(3, sprites.Bounds().H()-41, 17, sprites.Bounds().H()-27))
monster.Monstersprite2 = pixel.NewSprite(sprites, pixel.R(23, sprites.Bounds().H()-41, 37, sprites.Bounds().H()-27))
case 1:
monster.Monstersprite1 = pixel.NewSprite(sprites, pixel.R(1, sprites.Bounds().H()-14, 19, sprites.Bounds().H()))
monster.Monstersprite2 = pixel.NewSprite(sprites, pixel.R(21, sprites.Bounds().H()-14, 39, sprites.Bounds().H()))
case 2:
monster.Monstersprite1 = pixel.NewSprite(sprites, pixel.R(0, sprites.Bounds().H()-27, 20, sprites.Bounds().H()-14))
monster.Monstersprite2 = pixel.NewSprite(sprites, pixel.R(20, sprites.Bounds().H()-27, 40, sprites.Bounds().H()-14))
}
monster.Id = id
monster.X = x
monster.Y = y
monster.Spritebool = mSprite
monster.Movingright = mMovingRight
return &monster
}
func CreateShot(shipX float64, shipY float64, mShot bool) *Shot {
shot := Shot{}
if mShot {
shot.Shotsprite = pixel.NewSprite(sprites, pixel.R(0, sprites.Bounds().H()-79, 5, sprites.Bounds().H()-70))
} else {
shot.Shotsprite = pixel.NewSprite(sprites, pixel.R(20, sprites.Bounds().H()-66, 23, sprites.Bounds().H()-60))
}
shot.MonsterShot = mShot
shot.X = shipX
shot.Y = shipY
return &shot
}
func (ship *Spaceship) Draw(win *pixelgl.Window) {
ship.Shipsprite.Draw(win, pixel.IM.Moved(pixel.V(ship.X, ship.Y)))
}
func (monster *Monster) Draw(win *pixelgl.Window) {
if monster.Spritebool {
monster.Monstersprite1.Draw(win, pixel.IM.Moved(pixel.V(monster.X, monster.Y)))
} else {
monster.Monstersprite2.Draw(win, pixel.IM.Moved(pixel.V(monster.X, monster.Y)))
}
}
func (shot *Shot) Draw(win *pixelgl.Window) {
shot.Shotsprite.Draw(win, pixel.IM.Moved(pixel.V(shot.X, shot.Y)))
if shot.MonsterShot {
shot.Y--
} else {
shot.Y++
}
}
func loadPicture(path string) (pixel.Picture, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
img, _, err := image.Decode(file)
if err != nil {
return nil, err
}
return pixel.PictureDataFromImage(img), nil
}
func (ship *Spaceship) initShip() {
ship.X = winW / 2
ship.Y = ship.Shipsprite.Frame().H() / 2
}
//Auxilia no envio dos dados pro servidor
func sendData(beb *BEBcast.BestEffortBroadcast_Module, data interface{}, datatype string) {
var req BEBcast.BestEffortBroadcast_Req_Message
cData := ClientData{PortBind, datatype, data}
switch datatype {
case "PortHandShake", "Shot", "KillMonster", "KillShip", "CloseConnection":
req = BEBcast.BestEffortBroadcast_Req_Message{
Addresses: serverMainAddr,
Message: cData}
default:
req = BEBcast.BestEffortBroadcast_Req_Message{
Addresses: serverShipAddr,
Message: cData}
}
beb.Req <- req
}
func run() {
cfg := pixelgl.WindowConfig{
Title: "Space Invaders",
Bounds: pixel.R(0, 0, winW, winH),
}
win, err := pixelgl.NewWindow(cfg)
if err != nil {
panic(err)
}
wonStr := "YOU WON!"
gameoverStr := "GAME OVER!"
win.Clear(colornames.Black)
monsters := list.New()
shots := list.New()
mShots := list.New()
port := 0
shipDict := make(map[string]interface{})
ship := CreateSpaceship()
ship.initShip()
dead := false
won := false
gameover := false
gamestarted := false
basicAtlas := text.NewAtlas(basicfont.Face7x13, text.ASCII)
wonTxt := text.New(pixel.V(winW/2, winH/2), basicAtlas)
wonTxt.Dot.X -= math.Round(wonTxt.BoundsOf(wonStr).W() / 2)
gameoverTxt := text.New(pixel.V(winW/2, winH/2), basicAtlas)
gameoverTxt.Dot.X -= math.Round(gameoverTxt.BoundsOf(gameoverStr).W() / 2)
fmt.Fprintln(wonTxt, wonStr)
fmt.Fprintln(gameoverTxt, gameoverStr)
//Procura por uma sequencia de 3 portas disponiveis
for i := 5000; i < 6000; i++ {
if PP2PLink.Check("127.0.0.1:"+strconv.Itoa(i)) &&
PP2PLink.Check("127.0.0.1:"+strconv.Itoa(i+1)) &&
PP2PLink.Check("127.0.0.1:"+strconv.Itoa(i+2)) {
port = i
break
}
}
if port == 0 {
os.Exit(1)
}
PortBind = strconv.Itoa(port)
bebMonsters := BEBcast.BestEffortBroadcast_Module{
Req: make(chan BEBcast.BestEffortBroadcast_Req_Message),
Ind: make(chan BEBcast.BestEffortBroadcast_Ind_Message)}
bebShip := BEBcast.BestEffortBroadcast_Module{
Req: make(chan BEBcast.BestEffortBroadcast_Req_Message),
Ind: make(chan BEBcast.BestEffortBroadcast_Ind_Message)}
bebOthers := BEBcast.BestEffortBroadcast_Module{
Req: make(chan BEBcast.BestEffortBroadcast_Req_Message),
Ind: make(chan BEBcast.BestEffortBroadcast_Ind_Message)}
bebMonsters.Init("127.0.0.1:"+PortBind, 8192)
bebShip.Init("127.0.0.1:"+strconv.Itoa(port+1), 1024)
bebOthers.Init("127.0.0.1:"+strconv.Itoa(port+2), 1024)
//envia os dados(ip e porta) do cliente para o servidor
//Apenas a primeira porta da sequencia é enviada para o servidor
//de forma que o servidor sabe que bebShip recebe pela porta Port+1 e
//bebOthers pela porta Port+2
sendData(&bebOthers, nil, "PortHandShake")
go func() {
for {
in := <-bebOthers.Ind
sData := ServerData{}
reqBodyBytes := new(bytes.Buffer)
json.NewDecoder(reqBodyBytes).Decode(in.Message)
json.Unmarshal([]byte(in.Message.(string)), &sData)
switch sData.Datatype {
//Recebe o tiro efetuado por algum cliente e coloca na lista de tiros
case "ShotDict":
data := sData.Data.(map[string]interface{})
shotMutex.Lock()
shots.PushFront(CreateShot(data["X"].(float64), data["Y"].(float64), false))
shotMutex.Unlock()
}
}
}()
go func() {
for {
in := <-bebShip.Ind
sData := ServerData{}
reqBodyBytes := new(bytes.Buffer)
json.NewDecoder(reqBodyBytes).Decode(in.Message)
json.Unmarshal([]byte(in.Message.(string)), &sData)
switch sData.Datatype {
//Recebe a lista com as naves dos clientes
case "ShipDict":
if !gamestarted {
gamestarted = true
}
data := sData.Data.(map[string]interface{})
shipMutex.Lock()
shipDict = data
shipMutex.Unlock()
}
}
}()
go func() {
for {
in := <-bebMonsters.Ind
sData := ServerData{}
reqBodyBytes := new(bytes.Buffer)
json.NewDecoder(reqBodyBytes).Decode(in.Message)
json.Unmarshal([]byte(in.Message.(string)), &sData)
switch sData.Datatype {
//Recebe a lista de monstros
case "Monsters":
monsterMutex.Lock()
monsters = list.New()
data := sData.Data.(map[string]interface{})
for _, m := range data {
monster := m.(map[string]interface{})
x := monster["X"].(float64)
y := monster["Y"].(float64)
id := monster["Id"].(float64)
mRight := monster["Movingright"].(bool)
sBool := monster["Spritebool"].(bool)
mType := monster["MonsterType"].(float64)
nMonster := CreateMonster(x, y, sBool, mRight, mType, byte(id))
monsters.PushFront(nMonster)
}
if monsters.Len() == 0 {
won = true
}
monsterMutex.Unlock()
//Recebe do servidor um tiro efetuado por um monstro
case "MonsterShot":
data := sData.Data.(map[string]interface{})
mShotMutex.Lock()
mShots.PushFront(CreateShot(data["X"].(float64), data["Y"].(float64), true))
mShotMutex.Unlock()
}
}
}()
fps := time.Tick(time.Second / 480)
for !win.Closed() {
win.Clear(colornames.Black)
if !won && !gameover {
if !dead {
if win.JustPressed(pixelgl.KeyRight) {
if ship.X < winW-5 {
ship.X += 5
sendData(&bebShip, ship, "SpaceShip")
}
}
if win.JustPressed(pixelgl.KeyLeft) {
if ship.X > 5 {
ship.X -= 5
sendData(&bebShip, ship, "SpaceShip")
}
}
if win.JustPressed(pixelgl.KeySpace) {
sendData(&bebOthers, CreateShot(ship.X, ship.Y, false), "Shot")
}
}
shipMutex.Lock()
if len(shipDict) == 0 && gamestarted {
gameover = true
}
for _, v := range shipDict {
vd := v.(map[string]interface{})
rship := CreateSpaceship()
rship.X = vd["X"].(float64)
rship.Y = vd["Y"].(float64)
rship.Draw(win)
}
shipMutex.Unlock()
//Verifica se um tiro atingiu um monstro
monsterMutex.Lock()
for m := monsters.Front(); m != nil; m = m.Next() {
monster := m.Value.(*Monster)
monster.Draw(win)
shotMutex.Lock()
for s := shots.Front(); s != nil; s = s.Next() {
shot := s.Value.(*Shot)
if shot.X >= monster.X-monster.Monstersprite1.Frame().W()/2 &&
shot.X <= monster.X+monster.Monstersprite1.Frame().W()/2 &&
shot.Y >= monster.Y-monster.Monstersprite1.Frame().H()/2 &&
shot.Y <= monster.Y+monster.Monstersprite1.Frame().H()/2 {
sendData(&bebOthers, monster.Id, "KillMonster")
monsters.Remove(m)
shots.Remove(s)
}
}
shotMutex.Unlock()
}
monsterMutex.Unlock()
//Verifica se um tiro atingiu uma nave
mShotMutex.Lock()
for s := mShots.Front(); s != nil; s = s.Next() {
shot := s.Value.(*Shot)
shipMutex.Lock()
for k, v := range shipDict {
vd := v.(map[string]interface{})
rship := CreateSpaceship()
rship.X = vd["X"].(float64)
rship.Y = vd["Y"].(float64)
if shot.X >= rship.X-rship.Shipsprite.Frame().W()/2 &&
shot.X <= rship.X+rship.Shipsprite.Frame().W()/2 &&
shot.Y >= rship.Y-rship.Shipsprite.Frame().H()/2 &&
shot.Y <= rship.Y+rship.Shipsprite.Frame().H()/2 {
mShots.Remove(s)
delete(shipDict, k)
if rship.X == ship.X && rship.Y == ship.Y {
sendData(&bebOthers, nil, "KillShip")
dead = true
}
}
}
shipMutex.Unlock()
}
mShotMutex.Unlock()
shotMutex.Lock()
for s := shots.Front(); s != nil; s = s.Next() {
shot := s.Value.(*Shot)
if shot.Y > winH {
shots.Remove(s)
} else {
shot.Draw(win)
}
}
shotMutex.Unlock()
mShotMutex.Lock()
for s := mShots.Front(); s != nil; s = s.Next() {
shot := s.Value.(*Shot)
if shot.Y < 0 {
mShots.Remove(s)
} else {
shot.Draw(win)
}
}
mShotMutex.Unlock()
} else {
if won {
wonTxt.Draw(win, pixel.IM)
}
if gameover {
gameoverTxt.Draw(win, pixel.IM)
}
}
win.Update()
<-fps
}
sendData(&bebOthers, nil, "CloseConnection")
}
func main() {
pixelgl.Run(run)
}