Prevent chat and other player rendering race conditions when logging in at the same time

This commit is contained in:
2025-04-16 12:28:30 +02:00
parent 62a6bb2926
commit 541f53c06a
3 changed files with 133 additions and 37 deletions
+37 -14
View File
@@ -59,6 +59,12 @@ func (c *Chat) HandleServerMessages(messages []*pb.ChatMessage) {
// Convert protobuf messages to our local type
for _, msg := range messages {
// Skip invalid messages
if msg == nil {
log.Printf("Warning: Received nil chat message")
continue
}
localMsg := types.ChatMessage{
PlayerID: msg.PlayerId,
Username: msg.Username,
@@ -81,24 +87,41 @@ func (c *Chat) HandleServerMessages(messages []*pb.ChatMessage) {
}
// Add floating message to the player
if game, ok := c.userData.(*Game); ok {
if msg.PlayerId == game.Player.ID {
game.Player.Lock()
game.Player.FloatingMessage = &types.FloatingMessage{
if game, ok := c.userData.(*Game); ok && game != nil {
// Make sure each game component exists before using it
if game.PlayerManager == nil {
log.Printf("Warning: PlayerManager is nil when processing chat message")
continue
}
if msg.PlayerId == game.PlayerManager.LocalPlayer.ID {
// Check if local player exists
if game.PlayerManager.LocalPlayer == nil {
log.Printf("Warning: Local player is nil when trying to add floating message")
continue
}
game.PlayerManager.LocalPlayer.Lock()
game.PlayerManager.LocalPlayer.FloatingMessage = &types.FloatingMessage{
Content: msg.Content,
ExpireTime: time.Now().Add(6 * time.Second),
}
game.Player.Unlock()
} else if otherPlayer, exists := game.OtherPlayers[msg.PlayerId]; exists {
otherPlayer.Lock()
otherPlayer.FloatingMessage = &types.FloatingMessage{
Content: msg.Content,
ExpireTime: time.Now().Add(6 * time.Second),
}
otherPlayer.Unlock()
log.Printf("Added floating message to other player %d", msg.PlayerId)
game.PlayerManager.LocalPlayer.Unlock()
} else {
log.Printf("Could not find other player %d to add floating message", msg.PlayerId)
// The other player might not be in our list yet, handle safely
player := game.PlayerManager.GetPlayer(msg.PlayerId)
if player == nil {
log.Printf("Could not find other player %d to add floating message (player not in game yet)", msg.PlayerId)
continue
}
player.Lock()
player.FloatingMessage = &types.FloatingMessage{
Content: msg.Content,
ExpireTime: time.Now().Add(6 * time.Second),
}
player.Unlock()
log.Printf("Added floating message to other player %d", msg.PlayerId)
}
}
}