Add system messages to chat

This commit is contained in:
bdnugget 2025-01-20 00:03:15 +01:00
parent e3c570349c
commit d25ee09155

20
main.go
View File

@ -225,11 +225,14 @@ func handleConnection(conn net.Conn) {
ProtocolVersion: protoVersion,
}
addSystemMessage(fmt.Sprintf("%s connected", username))
// Ensure player state is saved on any kind of disconnect
defer func() {
if err := db.SavePlayerState(playerID, player.X, player.Y); err != nil {
log.Printf("Error saving state for player %d: %v", playerID, err)
}
addSystemMessage(fmt.Sprintf("%s disconnected", player.Username))
mu.Lock()
delete(players, playerID)
delete(playerConns, playerID)
@ -308,6 +311,23 @@ func addChatMessage(playerID int32, content string) {
chatHistory = append(chatHistory, msg)
}
func addSystemMessage(content string) {
chatMutex.Lock()
defer chatMutex.Unlock()
msg := &pb.ChatMessage{
PlayerId: 0, // System messages use ID 0
Username: "System",
Content: content,
Timestamp: time.Now().UnixNano(),
}
if len(chatHistory) >= 100 {
chatHistory = chatHistory[1:]
}
chatHistory = append(chatHistory, msg)
}
func processActions() {
mu.Lock()
defer mu.Unlock()