Skip to content

Commit

Permalink
room stream mutex update
Browse files Browse the repository at this point in the history
  • Loading branch information
ferhatbostanci committed Jun 10, 2021
1 parent 1a0a5e0 commit 488e9e0
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 16 deletions.
2 changes: 1 addition & 1 deletion handler/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (

type MultiplayerHandler struct {
pb.UnimplementedMultiplayerServiceServer
rooms map[string]map[string]*pb.Player
rooms map[string][]*pb.Player
roomsMapMutex sync.RWMutex
currentPlayersMutex sync.RWMutex
jwtManager *jwt.Manager
Expand Down
27 changes: 12 additions & 15 deletions handler/room.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ func (h *MultiplayerHandler) RoomConnect(ctx context.Context, request *pb.RoomCo

func (h *MultiplayerHandler) RoomStream(stream pb.MultiplayerService_RoomStreamServer) error {
if h.rooms == nil {
h.rooms = make(map[string]map[string]*pb.Player)
h.rooms = make(map[string][]*pb.Player)
}

var currentTick int64 = 0
Expand All @@ -64,29 +64,26 @@ func (h *MultiplayerHandler) RoomStream(stream pb.MultiplayerService_RoomStreamS
return err
}

if h.rooms[request.GetRoomId()] == nil {
h.rooms[request.GetRoomId()] = make(map[string]*pb.Player)
}

currentTick++
if currentTick%32 == 0 {
log.Trace().Msg(request.String())
}

h.roomsMapMutex.Lock()
h.rooms[request.GetRoomId()][request.GetPlayer().GetId()] = request.GetPlayer()
h.roomsMapMutex.Unlock()

currentPlayers := make([]*pb.Player, 0, len(h.rooms[request.GetRoomId()]))
if len(h.rooms[request.GetRoomId()]) > 2 {
h.currentPlayersMutex.Lock()
for _, player := range h.rooms[request.GetRoomId()] {
currentPlayers = append(currentPlayers, player)
addedKey := -1
for key, player := range h.rooms[request.GetRoomId()] {
if player.GetId() == request.GetPlayer().GetId() {
addedKey = key
}
h.currentPlayersMutex.Unlock()
}
if addedKey == -1 {
h.rooms[request.GetRoomId()] = append(h.rooms[request.GetRoomId()], request.GetPlayer())
} else {
h.rooms[request.GetRoomId()][addedKey] = request.GetPlayer()
}
h.roomsMapMutex.Unlock()

err = stream.Send(&pb.RoomStreamResponse{Players: currentPlayers})
err = stream.Send(&pb.RoomStreamResponse{Players: h.rooms[request.GetRoomId()]})
if err != nil {
if err == io.EOF {
break
Expand Down

0 comments on commit 488e9e0

Please sign in to comment.