87 lines
2.6 KiB
C#
87 lines
2.6 KiB
C#
/*
|
||
* @Author: 白哉
|
||
* @Description: 聊天管理
|
||
* @Date: 2026年01月19日 星期一 11:01:05
|
||
* @Modify:
|
||
*/
|
||
|
||
|
||
using System;
|
||
using System.Collections.Generic;
|
||
using MemoryPack;
|
||
using TH1_Logic.Net;
|
||
using TH1_Logic.Steam;
|
||
using UnityEngine;
|
||
|
||
|
||
namespace TH1_Logic.Chat
|
||
{
|
||
public class ChatManager
|
||
{
|
||
public static ChatManager Instance = new ChatManager();
|
||
public List<ChatItem> ChatItems = new List<ChatItem>();
|
||
private Dictionary<int, ChatItem> _chatItems = new Dictionary<int, ChatItem>();
|
||
|
||
private const int MaxStorageCount = 999;
|
||
private const int TrimCount = 900;
|
||
|
||
/// <summary>
|
||
/// ChatItems 发生变化时触发,UI 层订阅此回调来刷新显示。
|
||
/// </summary>
|
||
public System.Action OnChatUpdated;
|
||
|
||
|
||
public void SendChatItem(string message)
|
||
{
|
||
var item = new ChatItem();
|
||
item.Hash = System.Guid.NewGuid().GetHashCode();
|
||
item.SenderId = LobbyManager.Instance.Lobby.GetSelfMemberId();
|
||
item.Message = BannedWordFilter.Filter(message);
|
||
item.Time = Time.time;
|
||
|
||
ChatItems.Add(item);
|
||
_chatItems[item.Hash] = item;
|
||
|
||
if (LobbyManager.Instance.Lobby.IsLobbyOwner()) GameNetSender.Instance.BroadcastChatMessage(item);
|
||
else GameNetSender.Instance.SendChatMessage(item);
|
||
|
||
TrimIfNeeded();
|
||
Debug.Log($"[ChatManager] SendChatItem: \"{message}\", total={ChatItems.Count}, listeners={OnChatUpdated?.GetInvocationList()?.Length ?? 0}");
|
||
OnChatUpdated?.Invoke();
|
||
}
|
||
|
||
public void ReceiveChatItem(ChatItem newItem)
|
||
{
|
||
if (newItem == null || _chatItems.ContainsKey(newItem.Hash)) return;
|
||
newItem.Message = BannedWordFilter.Filter(newItem.Message);
|
||
newItem.Time = Time.time;
|
||
ChatItems.Add(newItem);
|
||
_chatItems[newItem.Hash] = newItem;
|
||
if (LobbyManager.Instance.Lobby.IsLobbyOwner()) GameNetSender.Instance.BroadcastChatMessage(newItem);
|
||
|
||
TrimIfNeeded();
|
||
OnChatUpdated?.Invoke();
|
||
}
|
||
|
||
private void TrimIfNeeded()
|
||
{
|
||
if (ChatItems.Count <= MaxStorageCount) return;
|
||
for (int i = 0; i < TrimCount; i++)
|
||
_chatItems.Remove(ChatItems[i].Hash);
|
||
ChatItems.RemoveRange(0, TrimCount);
|
||
}
|
||
}
|
||
|
||
|
||
[MemoryPackable]
|
||
public partial class ChatItem
|
||
{
|
||
public int Hash;
|
||
public float Time;
|
||
public ulong SenderId;
|
||
public string Message;
|
||
|
||
[MemoryPackIgnore]
|
||
public bool AlreadyUIShow;
|
||
}
|
||
} |