Files
Fishing2/Assets/Scripts/Commands/Command.cs
2025-05-10 12:49:47 +08:00

158 lines
3.9 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using NBC;
namespace NBF
{
public class Command
{
public enum LogType
{
Info,
Warn,
Error
}
public struct LogData
{
public string Log;
public LogType Type;
public LogData(string log, LogType type)
{
Log = log;
Type = type;
}
}
private static readonly Dictionary<string, ICommand> _commands = new Dictionary<string, ICommand>();
#region Log
public static readonly List<LogData> Logs = new List<LogData>();
private const int MaxLog = 1000;
public static Action OnLogChange;
public static void LogInfo(string log)
{
AddLog(log, LogType.Info);
}
public static void LogWarn(string log)
{
AddLog(log, LogType.Warn);
}
public static void LogError(string log)
{
AddLog(log, LogType.Error);
}
private static void AddLog(string log, LogType type)
{
if (Logs.Count > MaxLog)
{
var sub = Logs.Count - MaxLog;
for (int i = 0; i < sub; i++)
{
Logs.RemoveAt(0);
}
}
Logs.Add(new LogData(log, type));
OnLogChange?.Invoke();
}
#endregion
/// <summary>
/// 反射所有GM命令
/// </summary>
public static void Init()
{
try
{
var assembly = AppDomain.CurrentDomain.GetAssemblies()
.First(a => a.GetName().Name == "Assembly-CSharp");
var type = typeof(ICommand);
var types = assembly.GetTypes();
Log.Info("command 6");
var commandTypes =
types.Where(u => type.IsAssignableFrom(u) && u.IsClass && !u.IsAbstract && !u.IsGenericType);
foreach (var c in commandTypes)
{
if (Activator.CreateInstance(c) is ICommand command)
{
_commands[command.Command] = command;
}
}
}
catch (Exception e)
{
Log.Error(e);
}
}
public static void Open()
{
// UI.Inst.OpenUI<CommandPanel>();
}
public static void Close()
{
// UI.Inst.DestroyUI<CommandPanel>();
}
public static bool Has(string command)
{
return _commands.ContainsKey(command);
}
/// <summary>
/// 获取所有指令实例
/// </summary>
/// <returns></returns>
public static List<ICommand> GetAll()
{
return _commands.Values.ToList();
}
public static ICommand Get(string command)
{
return _commands.GetValueOrDefault(command);
}
/// <summary>
/// 执行命令
/// </summary>
/// <param name="command"></param>
/// <returns></returns>
public static bool Run(string command)
{
var args = new CommandArgs(command);
var inst = Get(args.Command);
return inst?.Execute(args) ?? false;
}
/// <summary>
/// 匹配相识的命令
/// </summary>
/// <param name="command"></param>
/// <returns></returns>
public static List<ICommand> Match(string command)
{
var list = new List<ICommand>();
foreach (var key in _commands.Keys)
{
if (key.Contains(command))
{
list.Add(_commands[key]);
}
}
return list;
}
}
}