Fix panic on disconnect by adding mutex

This commit is contained in:
bdnugget 2025-01-13 10:04:09 +01:00
parent a459e8b4a5
commit 4b73492ffc

View File

@ -27,6 +27,7 @@ var (
players = make(map[int]*Player)
actionQueue = make(map[int][]*pb.Action) // Queue to store actions for each player
playerConns = make(map[int]net.Conn) // Map to store player connections
mu sync.RWMutex // Add mutex for protecting shared maps
)
func main() {
@ -60,11 +61,12 @@ func main() {
func handleConnection(conn net.Conn) {
defer conn.Close()
// Assign a new player ID and add the player to the game state
mu.Lock()
playerID := len(players) + 1
newPlayer := &Player{ID: playerID, X: 5, Y: 5}
players[playerID] = newPlayer
playerConns[playerID] = conn
mu.Unlock()
fmt.Printf("Player %d connected\n", playerID)
// Send player ID to the client
@ -90,6 +92,7 @@ func handleConnection(conn net.Conn) {
log.Printf("Error reading from player %d: %v", playerID, err)
delete(players, playerID)
delete(playerConns, playerID)
delete(actionQueue, playerID)
return
}
@ -107,6 +110,9 @@ func handleConnection(conn net.Conn) {
}
func processActions() {
mu.Lock()
defer mu.Unlock()
// Update players based on queued actions
for playerID, actions := range actionQueue {
player := players[playerID]