代码风格优化

This commit is contained in:
milimoe 2025-12-19 22:28:53 +08:00
parent 1988ebe2a0
commit b11db3364a
Signed by: milimoe
GPG Key ID: 9554D37E4B8991D0
24 changed files with 398 additions and 443 deletions

View File

@ -216,36 +216,36 @@ namespace Milimoe.FunGame.Core.Api.Transmittal
private class SocketRequest : SocketHandlerController private class SocketRequest : SocketHandlerController
{ {
public Dictionary<string, object> RequestData { get; } = []; public Dictionary<string, object> RequestData { get; } = [];
public Dictionary<string, object> ResultData => _ResultData; public Dictionary<string, object> ResultData => _resultData;
public RequestResult Result => _Result; public RequestResult Result => _result;
public string Error => _Error; public string Error => _error;
private readonly Socket? Socket = null; private readonly Socket? _socket = null;
private readonly HTTPClient? HTTPClient = null; private readonly HTTPClient? _httpClient = null;
private readonly DataRequestType RequestType = DataRequestType.UnKnown; private readonly DataRequestType _requestType = DataRequestType.UnKnown;
private readonly Guid RequestID = Guid.Empty; private readonly Guid _requestID = Guid.Empty;
private readonly bool IsLongRunning = false; private readonly bool _isLongRunning = false;
private readonly SocketRuntimeType RuntimeType = SocketRuntimeType.Client; private readonly SocketRuntimeType _runtimeType = SocketRuntimeType.Client;
private Dictionary<string, object> _ResultData = []; private Dictionary<string, object> _resultData = [];
private RequestResult _Result = RequestResult.Missing; private RequestResult _result = RequestResult.Missing;
private string _Error = ""; private string _error = "";
public SocketRequest(Socket? socket, DataRequestType type, Guid requestId, bool longRunning = false, SocketRuntimeType runtime = SocketRuntimeType.Client) : base(socket) public SocketRequest(Socket? socket, DataRequestType type, Guid requestId, bool longRunning = false, SocketRuntimeType runtime = SocketRuntimeType.Client) : base(socket)
{ {
Socket = socket; _socket = socket;
RequestType = type; _requestType = type;
RequestID = requestId; _requestID = requestId;
IsLongRunning = longRunning; _isLongRunning = longRunning;
RuntimeType = runtime; _runtimeType = runtime;
} }
public SocketRequest(HTTPClient? client, DataRequestType type, Guid requestId, bool longRunning = false, SocketRuntimeType runtime = SocketRuntimeType.Client) : base(client) public SocketRequest(HTTPClient? client, DataRequestType type, Guid requestId, bool longRunning = false, SocketRuntimeType runtime = SocketRuntimeType.Client) : base(client)
{ {
HTTPClient = client; _httpClient = client;
RequestType = type; _requestType = type;
RequestID = requestId; _requestID = requestId;
IsLongRunning = longRunning; _isLongRunning = longRunning;
RuntimeType = runtime; _runtimeType = runtime;
} }
public void SendRequest() public void SendRequest()
@ -253,17 +253,17 @@ namespace Milimoe.FunGame.Core.Api.Transmittal
try try
{ {
SetWorking(); SetWorking();
if (RuntimeType == SocketRuntimeType.Addon) if (_runtimeType == SocketRuntimeType.Addon)
{ {
if (RequestData.ContainsKey(SocketSet.Plugins_Mark)) RequestData[SocketSet.Plugins_Mark] = "true"; if (RequestData.ContainsKey(SocketSet.Plugins_Mark)) RequestData[SocketSet.Plugins_Mark] = "true";
else RequestData.Add(SocketSet.Plugins_Mark, true); else RequestData.Add(SocketSet.Plugins_Mark, true);
} }
else RequestData.Remove(SocketSet.Plugins_Mark); else RequestData.Remove(SocketSet.Plugins_Mark);
if (Socket != null && Socket.Send(SocketMessageType.DataRequest, RequestType, RequestID, RequestData) == SocketResult.Success) if (_socket != null && _socket.Send(SocketMessageType.DataRequest, _requestType, _requestID, RequestData) == SocketResult.Success)
{ {
WaitForWorkDone(); WaitForWorkDone();
} }
else if (HTTPClient != null) else if (_httpClient != null)
{ {
throw new AsyncSendException(); throw new AsyncSendException();
} }
@ -272,8 +272,8 @@ namespace Milimoe.FunGame.Core.Api.Transmittal
catch (Exception e) catch (Exception e)
{ {
Working = false; Working = false;
_Result = RequestResult.Fail; _result = RequestResult.Fail;
_Error = e.GetErrorInfo(); _error = e.GetErrorInfo();
} }
} }
@ -282,17 +282,17 @@ namespace Milimoe.FunGame.Core.Api.Transmittal
try try
{ {
SetWorking(); SetWorking();
if (RuntimeType == SocketRuntimeType.Addon) if (_runtimeType == SocketRuntimeType.Addon)
{ {
if (RequestData.ContainsKey(SocketSet.Plugins_Mark)) RequestData[SocketSet.Plugins_Mark] = "true"; if (RequestData.ContainsKey(SocketSet.Plugins_Mark)) RequestData[SocketSet.Plugins_Mark] = "true";
else RequestData.Add(SocketSet.Plugins_Mark, true); else RequestData.Add(SocketSet.Plugins_Mark, true);
} }
else RequestData.Remove(SocketSet.Plugins_Mark); else RequestData.Remove(SocketSet.Plugins_Mark);
if (Socket != null && Socket.Send(SocketMessageType.DataRequest, RequestType, RequestID, RequestData) == SocketResult.Success) if (_socket != null && _socket.Send(SocketMessageType.DataRequest, _requestType, _requestID, RequestData) == SocketResult.Success)
{ {
await WaitForWorkDoneAsync(); await WaitForWorkDoneAsync();
} }
else if (HTTPClient != null && await HTTPClient.Send(SocketMessageType.DataRequest, RequestType, RequestID, RequestData) == SocketResult.Success) else if (_httpClient != null && await _httpClient.Send(SocketMessageType.DataRequest, _requestType, _requestID, RequestData) == SocketResult.Success)
{ {
await WaitForWorkDoneAsync(); await WaitForWorkDoneAsync();
} }
@ -301,8 +301,8 @@ namespace Milimoe.FunGame.Core.Api.Transmittal
catch (Exception e) catch (Exception e)
{ {
Working = false; Working = false;
_Result = RequestResult.Fail; _result = RequestResult.Fail;
_Error = e.GetErrorInfo(); _error = e.GetErrorInfo();
} }
} }
@ -314,21 +314,21 @@ namespace Milimoe.FunGame.Core.Api.Transmittal
{ {
DataRequestType type = obj.GetParam<DataRequestType>(0); DataRequestType type = obj.GetParam<DataRequestType>(0);
Guid id = obj.GetParam<Guid>(1); Guid id = obj.GetParam<Guid>(1);
if (type == RequestType && id == RequestID) if (type == _requestType && id == _requestID)
{ {
if (!IsLongRunning) Dispose(); if (!_isLongRunning) Dispose();
ReceivedObject = obj; ReceivedObject = obj;
Working = false; Working = false;
_ResultData = obj.GetParam<Dictionary<string, object>>(2) ?? []; _resultData = obj.GetParam<Dictionary<string, object>>(2) ?? [];
_Result = RequestResult.Success; _result = RequestResult.Success;
} }
} }
} }
catch (Exception e) catch (Exception e)
{ {
Working = false; Working = false;
_Result = RequestResult.Fail; _result = RequestResult.Fail;
_Error = e.GetErrorInfo(); _error = e.GetErrorInfo();
} }
} }
} }
@ -339,36 +339,36 @@ namespace Milimoe.FunGame.Core.Api.Transmittal
private class GamingRequest : SocketHandlerController private class GamingRequest : SocketHandlerController
{ {
public Dictionary<string, object> RequestData { get; } = []; public Dictionary<string, object> RequestData { get; } = [];
public Dictionary<string, object> ResultData => _ResultData; public Dictionary<string, object> ResultData => _resultData;
public RequestResult Result => _Result; public RequestResult Result => _result;
public string Error => _Error; public string Error => _error;
private readonly Socket? Socket = null; private readonly Socket? _socket = null;
private readonly HTTPClient? HTTPClient = null; private readonly HTTPClient? _httpClient = null;
private readonly GamingType GamingType = GamingType.None; private readonly GamingType _gamingType = GamingType.None;
private readonly Guid RequestID = Guid.Empty; private readonly Guid _requestID = Guid.Empty;
private readonly bool IsLongRunning = false; private readonly bool _isLongRunning = false;
private readonly SocketRuntimeType RuntimeType = SocketRuntimeType.Client; private readonly SocketRuntimeType _runtimeType = SocketRuntimeType.Client;
private Dictionary<string, object> _ResultData = []; private Dictionary<string, object> _resultData = [];
private RequestResult _Result = RequestResult.Missing; private RequestResult _result = RequestResult.Missing;
private string _Error = ""; private string _error = "";
public GamingRequest(Socket? socket, GamingType type, Guid requestId, bool longRunning = false, SocketRuntimeType runtime = SocketRuntimeType.Client) : base(socket) public GamingRequest(Socket? socket, GamingType type, Guid requestId, bool longRunning = false, SocketRuntimeType runtime = SocketRuntimeType.Client) : base(socket)
{ {
Socket = socket; _socket = socket;
GamingType = type; _gamingType = type;
RequestID = requestId; _requestID = requestId;
IsLongRunning = longRunning; _isLongRunning = longRunning;
RuntimeType = runtime; _runtimeType = runtime;
} }
public GamingRequest(HTTPClient? client, GamingType type, Guid requestId, bool longRunning = false, SocketRuntimeType runtime = SocketRuntimeType.Client) : base(client) public GamingRequest(HTTPClient? client, GamingType type, Guid requestId, bool longRunning = false, SocketRuntimeType runtime = SocketRuntimeType.Client) : base(client)
{ {
HTTPClient = client; _httpClient = client;
GamingType = type; _gamingType = type;
RequestID = requestId; _requestID = requestId;
IsLongRunning = longRunning; _isLongRunning = longRunning;
RuntimeType = runtime; _runtimeType = runtime;
} }
public void SendRequest() public void SendRequest()
@ -376,17 +376,17 @@ namespace Milimoe.FunGame.Core.Api.Transmittal
try try
{ {
SetWorking(); SetWorking();
if (RuntimeType == SocketRuntimeType.Addon) if (_runtimeType == SocketRuntimeType.Addon)
{ {
if (RequestData.ContainsKey(SocketSet.Plugins_Mark)) RequestData[SocketSet.Plugins_Mark] = "true"; if (RequestData.ContainsKey(SocketSet.Plugins_Mark)) RequestData[SocketSet.Plugins_Mark] = "true";
else RequestData.Add(SocketSet.Plugins_Mark, true); else RequestData.Add(SocketSet.Plugins_Mark, true);
} }
else RequestData.Remove(SocketSet.Plugins_Mark); else RequestData.Remove(SocketSet.Plugins_Mark);
if (Socket != null && Socket.Send(SocketMessageType.GamingRequest, GamingType, RequestID, RequestData) == SocketResult.Success) if (_socket != null && _socket.Send(SocketMessageType.GamingRequest, _gamingType, _requestID, RequestData) == SocketResult.Success)
{ {
WaitForWorkDone(); WaitForWorkDone();
} }
else if (HTTPClient != null) else if (_httpClient != null)
{ {
throw new AsyncSendException(); throw new AsyncSendException();
} }
@ -395,8 +395,8 @@ namespace Milimoe.FunGame.Core.Api.Transmittal
catch (Exception e) catch (Exception e)
{ {
Working = false; Working = false;
_Result = RequestResult.Fail; _result = RequestResult.Fail;
_Error = e.GetErrorInfo(); _error = e.GetErrorInfo();
} }
} }
@ -405,17 +405,17 @@ namespace Milimoe.FunGame.Core.Api.Transmittal
try try
{ {
SetWorking(); SetWorking();
if (RuntimeType == SocketRuntimeType.Addon) if (_runtimeType == SocketRuntimeType.Addon)
{ {
if (RequestData.ContainsKey(SocketSet.Plugins_Mark)) RequestData[SocketSet.Plugins_Mark] = "true"; if (RequestData.ContainsKey(SocketSet.Plugins_Mark)) RequestData[SocketSet.Plugins_Mark] = "true";
else RequestData.Add(SocketSet.Plugins_Mark, true); else RequestData.Add(SocketSet.Plugins_Mark, true);
} }
else RequestData.Remove(SocketSet.Plugins_Mark); else RequestData.Remove(SocketSet.Plugins_Mark);
if (Socket != null && Socket.Send(SocketMessageType.GamingRequest, GamingType, RequestID, RequestData) == SocketResult.Success) if (_socket != null && _socket.Send(SocketMessageType.GamingRequest, _gamingType, _requestID, RequestData) == SocketResult.Success)
{ {
await WaitForWorkDoneAsync(); await WaitForWorkDoneAsync();
} }
else if (HTTPClient != null && await HTTPClient.Send(SocketMessageType.GamingRequest, GamingType, RequestID, RequestData) == SocketResult.Success) else if (_httpClient != null && await _httpClient.Send(SocketMessageType.GamingRequest, _gamingType, _requestID, RequestData) == SocketResult.Success)
{ {
await WaitForWorkDoneAsync(); await WaitForWorkDoneAsync();
} }
@ -424,8 +424,8 @@ namespace Milimoe.FunGame.Core.Api.Transmittal
catch (Exception e) catch (Exception e)
{ {
Working = false; Working = false;
_Result = RequestResult.Fail; _result = RequestResult.Fail;
_Error = e.GetErrorInfo(); _error = e.GetErrorInfo();
} }
} }
@ -437,21 +437,21 @@ namespace Milimoe.FunGame.Core.Api.Transmittal
{ {
GamingType type = obj.GetParam<GamingType>(0); GamingType type = obj.GetParam<GamingType>(0);
Guid id = obj.GetParam<Guid>(1); Guid id = obj.GetParam<Guid>(1);
if (type == GamingType && id == RequestID) if (type == _gamingType && id == _requestID)
{ {
if (!IsLongRunning) Dispose(); if (!_isLongRunning) Dispose();
ReceivedObject = obj; ReceivedObject = obj;
Working = false; Working = false;
_ResultData = obj.GetParam<Dictionary<string, object>>(2) ?? []; _resultData = obj.GetParam<Dictionary<string, object>>(2) ?? [];
_Result = RequestResult.Success; _result = RequestResult.Success;
} }
} }
} }
catch (Exception e) catch (Exception e)
{ {
Working = false; Working = false;
_Result = RequestResult.Fail; _result = RequestResult.Fail;
_Error = e.GetErrorInfo(); _error = e.GetErrorInfo();
} }
} }
} }

View File

@ -16,24 +16,17 @@ namespace Milimoe.FunGame.Core.Api.Transmittal
/// <summary> /// <summary>
/// Smtp客户端信息 /// Smtp客户端信息
/// </summary> /// </summary>
public SmtpClientInfo SmtpClientInfo => _SmtpClientInfo; public SmtpClientInfo SmtpClientInfo { get; private set; }
/// <summary> /// <summary>
/// 上一个邮件发送的结果 /// 上一个邮件发送的结果
/// </summary> /// </summary>
public MailSendResult LastestResult => _LastestResult; public MailSendResult LastestResult { get; private set; } = MailSendResult.NotSend;
/// <summary> /// <summary>
/// 上一个邮件的发送错误信息(如果发送失败) /// 上一个邮件的发送错误信息(如果发送失败)
/// </summary> /// </summary>
public string ErrorMsg => _ErrorMsg; public string ErrorMsg { get; private set; } = "";
/**
*
*/
private readonly SmtpClientInfo _SmtpClientInfo;
private MailSendResult _LastestResult = MailSendResult.NotSend;
private string _ErrorMsg = "";
/// <summary> /// <summary>
/// 创建邮件服务 /// 创建邮件服务
@ -47,7 +40,7 @@ namespace Milimoe.FunGame.Core.Api.Transmittal
public MailSender(string senderMailAddress, string senderName, string senderPassword, string host, int port, bool ssl) public MailSender(string senderMailAddress, string senderName, string senderPassword, string host, int port, bool ssl)
{ {
MailSenderID = Guid.NewGuid(); MailSenderID = Guid.NewGuid();
_SmtpClientInfo = new SmtpClientInfo(senderMailAddress, senderName, senderPassword, host, port, ssl); SmtpClientInfo = new SmtpClientInfo(senderMailAddress, senderName, senderPassword, host, port, ssl);
if (!MailManager.MailSenders.ContainsKey(MailSenderID)) MailManager.MailSenders.Add(MailSenderID, this); if (!MailManager.MailSenders.ContainsKey(MailSenderID)) MailManager.MailSenders.Add(MailSenderID, this);
} }
@ -74,8 +67,9 @@ namespace Milimoe.FunGame.Core.Api.Transmittal
/// <returns></returns> /// <returns></returns>
public MailSendResult Send(MailObject mail) public MailSendResult Send(MailObject mail)
{ {
_LastestResult = MailManager.Send(this, mail, out _ErrorMsg); LastestResult = MailManager.Send(this, mail, out string errorMsg);
return _LastestResult; if (!string.IsNullOrWhiteSpace(errorMsg)) ErrorMsg = errorMsg;
return LastestResult;
} }
private bool _isDisposed = false; private bool _isDisposed = false;

View File

@ -21,10 +21,10 @@ namespace Milimoe.FunGame.Core.Api.Utility
List<Type>? Classes = null; List<Type>? Classes = null;
if (Assembly != null) if (Assembly != null)
{ {
Classes = Assembly.GetTypes().Where(w => Classes = [.. Assembly.GetTypes().Where(w =>
w.Namespace == "Milimoe.FunGame.Core.Implement" && w.Namespace == "Milimoe.FunGame.Core.Implement" &&
w.Name.Contains(ClassName) w.Name.Contains(ClassName)
).ToList(); )];
if (Classes != null && Classes.Count > 0) if (Classes != null && Classes.Count > 0)
return Classes[0]; return Classes[0];
else return null; else return null;

View File

@ -16,33 +16,23 @@ namespace Milimoe.FunGame.Core.Controller
/// <summary> /// <summary>
/// 与服务器的连接套接字实例 /// 与服务器的连接套接字实例
/// </summary> /// </summary>
public Socket? Socket => _Socket; public Socket? Socket { get; private set; } = null;
/// <summary> /// <summary>
/// 与服务器的连接套接字实例WebSocket /// 与服务器的连接套接字实例WebSocket
/// </summary> /// </summary>
public HTTPClient? HTTPClient => _HTTPClient; public HTTPClient? HTTPClient { get; private set; } = null;
/// <summary> /// <summary>
/// 套接字是否已经连接 /// 套接字是否已经连接
/// </summary> /// </summary>
public bool Connected => _Socket != null && _Socket.Connected; public bool Connected => Socket != null && Socket.Connected;
/// <summary> /// <summary>
/// 接收服务器信息的线程 /// 接收服务器信息的线程
/// </summary> /// </summary>
protected Task? _ReceivingTask; protected Task? _ReceivingTask;
/// <summary>
/// 用于类内赋值
/// </summary>
protected Socket? _Socket;
/// <summary>
/// 用于类内赋值
/// </summary>
protected HTTPClient? _HTTPClient;
/// <summary> /// <summary>
/// 是否正在接收服务器信息 /// 是否正在接收服务器信息
/// </summary> /// </summary>
@ -58,7 +48,7 @@ namespace Milimoe.FunGame.Core.Controller
try try
{ {
result = _Socket?.Send(SocketMessageType.Disconnect, "") == SocketResult.Success; result = Socket?.Send(SocketMessageType.Disconnect, "") == SocketResult.Success;
} }
catch (Exception e) catch (Exception e)
{ {
@ -78,7 +68,7 @@ namespace Milimoe.FunGame.Core.Controller
try try
{ {
result = _Socket?.Send(SocketMessageType.EndGame, "") == SocketResult.Success; result = Socket?.Send(SocketMessageType.EndGame, "") == SocketResult.Success;
} }
catch (Exception e) catch (Exception e)
{ {
@ -135,7 +125,7 @@ namespace Milimoe.FunGame.Core.Controller
// 与服务器建立连接 // 与服务器建立连接
if (type == TransmittalType.Socket) if (type == TransmittalType.Socket)
{ {
connectArgs = await Connect_Socket(connectArgs, address, port); connectArgs = await ConnectSocket(connectArgs, address, port);
} }
else if (type == TransmittalType.WebSocket) else if (type == TransmittalType.WebSocket)
{ {
@ -167,20 +157,20 @@ namespace Milimoe.FunGame.Core.Controller
/// <param name="address"></param> /// <param name="address"></param>
/// <param name="port"></param> /// <param name="port"></param>
/// <returns></returns> /// <returns></returns>
private async Task<ArrayList> Connect_Socket(ArrayList connectArgs, string address, int port) private async Task<ArrayList> ConnectSocket(ArrayList connectArgs, string address, int port)
{ {
ConnectResult result = ConnectResult.Success; ConnectResult result = ConnectResult.Success;
string msg = ""; string msg = "";
string serverName = ""; string serverName = "";
string notice = ""; string notice = "";
_Socket?.Close(); Socket?.Close();
_Socket = Socket.Connect(address, port); Socket = Socket.Connect(address, port);
if (_Socket != null && _Socket.Connected) if (Socket != null && Socket.Connected)
{ {
if (_Socket.Send(SocketMessageType.Connect, connectArgs.Cast<object>().ToArray()) == SocketResult.Success) if (Socket.Send(SocketMessageType.Connect, [.. connectArgs.Cast<object>()]) == SocketResult.Success)
{ {
SocketObject[] objs = _Socket.Receive(); SocketObject[] objs = Socket.Receive();
foreach (SocketObject obj in objs) foreach (SocketObject obj in objs)
{ {
if (obj.SocketType == SocketMessageType.Connect) if (obj.SocketType == SocketMessageType.Connect)
@ -190,7 +180,7 @@ namespace Milimoe.FunGame.Core.Controller
result = success ? ConnectResult.Success : ConnectResult.ConnectFailed; result = success ? ConnectResult.Success : ConnectResult.ConnectFailed;
if (success) if (success)
{ {
_Socket.Token = obj.GetParam<Guid>(2); Socket.Token = obj.GetParam<Guid>(2);
serverName = obj.GetParam<string>(3) ?? ""; serverName = obj.GetParam<string>(3) ?? "";
notice = obj.GetParam<string>(4) ?? ""; notice = obj.GetParam<string>(4) ?? "";
StartReceiving(); StartReceiving();
@ -204,14 +194,14 @@ namespace Milimoe.FunGame.Core.Controller
} }
} }
}); });
_Socket.ConnectionLost += Error; Socket.ConnectionLost += Error;
} }
} }
} }
} }
else result = ConnectResult.ConnectFailed; else result = ConnectResult.ConnectFailed;
} }
else _Socket?.Close(); else Socket?.Close();
return [result, msg, serverName, notice]; return [result, msg, serverName, notice];
} }
@ -232,12 +222,12 @@ namespace Milimoe.FunGame.Core.Controller
string serverName = ""; string serverName = "";
string notice = ""; string notice = "";
_HTTPClient?.Close(); HTTPClient?.Close();
_HTTPClient = await HTTPClient.Connect(address, ssl, port, subUrl, connectArgs.Cast<object>().ToArray()); HTTPClient = await HTTPClient.Connect(address, ssl, port, subUrl, [.. connectArgs.Cast<object>()]);
if (_HTTPClient.Connected) if (HTTPClient.Connected)
{ {
bool webSocketConnected = false; bool webSocketConnected = false;
_HTTPClient.AddSocketObjectHandler(obj => HTTPClient.AddSocketObjectHandler(obj =>
{ {
try try
{ {
@ -248,7 +238,7 @@ namespace Milimoe.FunGame.Core.Controller
result = success ? ConnectResult.Success : ConnectResult.ConnectFailed; result = success ? ConnectResult.Success : ConnectResult.ConnectFailed;
if (success) if (success)
{ {
_HTTPClient.Token = obj.GetParam<Guid>(2); HTTPClient.Token = obj.GetParam<Guid>(2);
serverName = obj.GetParam<string>(3) ?? ""; serverName = obj.GetParam<string>(3) ?? "";
notice = obj.GetParam<string>(4) ?? ""; notice = obj.GetParam<string>(4) ?? "";
} }
@ -266,11 +256,11 @@ namespace Milimoe.FunGame.Core.Controller
{ {
await Task.Delay(100); await Task.Delay(100);
} }
_HTTPClient.ConnectionLost += Error; HTTPClient.ConnectionLost += Error;
} }
else else
{ {
_HTTPClient?.Close(); HTTPClient?.Close();
result = ConnectResult.ConnectFailed; result = ConnectResult.ConnectFailed;
} }
@ -340,15 +330,12 @@ namespace Milimoe.FunGame.Core.Controller
/// 关闭 Socket 连接 /// 关闭 Socket 连接
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public bool Close_Socket() public bool CloseSocket()
{ {
try try
{ {
if (_Socket != null) Socket?.Close();
{ Socket = null;
_Socket.Close();
_Socket = null;
}
if (_ReceivingTask != null && !_ReceivingTask.IsCompleted) if (_ReceivingTask != null && !_ReceivingTask.IsCompleted)
{ {
_ReceivingTask.Wait(1); _ReceivingTask.Wait(1);
@ -372,11 +359,8 @@ namespace Milimoe.FunGame.Core.Controller
{ {
try try
{ {
if (_HTTPClient != null) HTTPClient?.Close();
{ HTTPClient = null;
_HTTPClient.Close();
_HTTPClient = null;
}
} }
catch (Exception e) catch (Exception e)
{ {
@ -409,14 +393,14 @@ namespace Milimoe.FunGame.Core.Controller
/// <exception cref="ConnectFailedException"></exception> /// <exception cref="ConnectFailedException"></exception>
public DataRequest NewDataRequest(DataRequestType RequestType) public DataRequest NewDataRequest(DataRequestType RequestType)
{ {
if (_Socket != null) if (Socket != null)
{ {
DataRequest request = new(_Socket, RequestType); DataRequest request = new(Socket, RequestType);
return request; return request;
} }
else if (_HTTPClient != null) else if (HTTPClient != null)
{ {
DataRequest request = new(_HTTPClient, RequestType); DataRequest request = new(HTTPClient, RequestType);
return request; return request;
} }
throw new ConnectFailedException(); throw new ConnectFailedException();
@ -430,14 +414,14 @@ namespace Milimoe.FunGame.Core.Controller
/// <exception cref="ConnectFailedException"></exception> /// <exception cref="ConnectFailedException"></exception>
public DataRequest NewLongRunningDataRequest(DataRequestType RequestType) public DataRequest NewLongRunningDataRequest(DataRequestType RequestType)
{ {
if (_Socket != null) if (Socket != null)
{ {
DataRequest request = new(_Socket, RequestType, true); DataRequest request = new(Socket, RequestType, true);
return request; return request;
} }
else if (_HTTPClient != null) else if (HTTPClient != null)
{ {
DataRequest request = new(_HTTPClient, RequestType, true); DataRequest request = new(HTTPClient, RequestType, true);
return request; return request;
} }
throw new ConnectFailedException(); throw new ConnectFailedException();
@ -452,14 +436,14 @@ namespace Milimoe.FunGame.Core.Controller
/// <exception cref="ConnectFailedException"></exception> /// <exception cref="ConnectFailedException"></exception>
public DataRequest NewDataRequestForAddon(DataRequestType RequestType) public DataRequest NewDataRequestForAddon(DataRequestType RequestType)
{ {
if (_Socket != null) if (Socket != null)
{ {
DataRequest request = new(_Socket, RequestType, false, SocketRuntimeType.Addon); DataRequest request = new(Socket, RequestType, false, SocketRuntimeType.Addon);
return request; return request;
} }
else if (_HTTPClient != null) else if (HTTPClient != null)
{ {
DataRequest request = new(_HTTPClient, RequestType, false, SocketRuntimeType.Addon); DataRequest request = new(HTTPClient, RequestType, false, SocketRuntimeType.Addon);
return request; return request;
} }
throw new ConnectFailedException(); throw new ConnectFailedException();
@ -474,14 +458,14 @@ namespace Milimoe.FunGame.Core.Controller
/// <exception cref="ConnectFailedException"></exception> /// <exception cref="ConnectFailedException"></exception>
public DataRequest NewLongRunningDataRequestForAddon(DataRequestType RequestType) public DataRequest NewLongRunningDataRequestForAddon(DataRequestType RequestType)
{ {
if (_Socket != null) if (Socket != null)
{ {
DataRequest request = new(_Socket, RequestType, true, SocketRuntimeType.Addon); DataRequest request = new(Socket, RequestType, true, SocketRuntimeType.Addon);
return request; return request;
} }
else if (_HTTPClient != null) else if (HTTPClient != null)
{ {
DataRequest request = new(_HTTPClient, RequestType, true, SocketRuntimeType.Addon); DataRequest request = new(HTTPClient, RequestType, true, SocketRuntimeType.Addon);
return request; return request;
} }
throw new ConnectFailedException(); throw new ConnectFailedException();
@ -496,14 +480,14 @@ namespace Milimoe.FunGame.Core.Controller
/// <exception cref="ConnectFailedException"></exception> /// <exception cref="ConnectFailedException"></exception>
public DataRequest NewDataRequestForAddon(GamingType GamingType) public DataRequest NewDataRequestForAddon(GamingType GamingType)
{ {
if (_Socket != null) if (Socket != null)
{ {
DataRequest request = new(_Socket, GamingType, false, SocketRuntimeType.Addon); DataRequest request = new(Socket, GamingType, false, SocketRuntimeType.Addon);
return request; return request;
} }
else if (_HTTPClient != null) else if (HTTPClient != null)
{ {
DataRequest request = new(_HTTPClient, GamingType, false, SocketRuntimeType.Addon); DataRequest request = new(HTTPClient, GamingType, false, SocketRuntimeType.Addon);
return request; return request;
} }
throw new ConnectFailedException(); throw new ConnectFailedException();
@ -518,14 +502,14 @@ namespace Milimoe.FunGame.Core.Controller
/// <exception cref="ConnectFailedException"></exception> /// <exception cref="ConnectFailedException"></exception>
public DataRequest NewLongRunningDataRequestForAddon(GamingType GamingType) public DataRequest NewLongRunningDataRequestForAddon(GamingType GamingType)
{ {
if (_Socket != null) if (Socket != null)
{ {
DataRequest request = new(_Socket, GamingType, true, SocketRuntimeType.Addon); DataRequest request = new(Socket, GamingType, true, SocketRuntimeType.Addon);
return request; return request;
} }
else if (_HTTPClient != null) else if (HTTPClient != null)
{ {
DataRequest request = new(_HTTPClient, GamingType, true, SocketRuntimeType.Addon); DataRequest request = new(HTTPClient, GamingType, true, SocketRuntimeType.Addon);
return request; return request;
} }
throw new ConnectFailedException(); throw new ConnectFailedException();
@ -545,7 +529,7 @@ namespace Milimoe.FunGame.Core.Controller
Receiving(); Receiving();
} }
}); });
_Socket?.StartReceiving(_ReceivingTask); Socket?.StartReceiving(_ReceivingTask);
} }
/// <summary> /// <summary>
@ -554,9 +538,9 @@ namespace Milimoe.FunGame.Core.Controller
/// <returns></returns> /// <returns></returns>
protected SocketObject[] GetServerMessages() protected SocketObject[] GetServerMessages()
{ {
if (_Socket != null && _Socket.Connected) if (Socket != null && Socket.Connected)
{ {
return _Socket.Receive(); return Socket.Receive();
} }
return []; return [];
} }
@ -567,7 +551,7 @@ namespace Milimoe.FunGame.Core.Controller
/// <returns></returns> /// <returns></returns>
protected SocketMessageType Receiving() protected SocketMessageType Receiving()
{ {
if (_Socket is null) return SocketMessageType.Unknown; if (Socket is null) return SocketMessageType.Unknown;
SocketMessageType result = SocketMessageType.Unknown; SocketMessageType result = SocketMessageType.Unknown;
try try
{ {
@ -580,8 +564,8 @@ namespace Milimoe.FunGame.Core.Controller
} }
catch (Exception e) catch (Exception e)
{ {
_Socket?.OnConnectionLost(e); Socket?.OnConnectionLost(e);
Close_Socket(); CloseSocket();
} }
return result; return result;
} }
@ -601,7 +585,7 @@ namespace Milimoe.FunGame.Core.Controller
case SocketMessageType.Disconnect: case SocketMessageType.Disconnect:
if (transmittalType == TransmittalType.Socket) if (transmittalType == TransmittalType.Socket)
{ {
Close_Socket(); CloseSocket();
} }
else if (transmittalType == TransmittalType.WebSocket) else if (transmittalType == TransmittalType.WebSocket)
{ {

View File

@ -125,13 +125,13 @@ namespace Milimoe.FunGame.Core.Entity
{ {
get get
{ {
return _Level >= 1 ? _Level : 1; return field >= 1 ? field : 1;
} }
set set
{ {
int past = _Level; int past = field;
_Level = Math.Min(Math.Max(1, value), GameplayEquilibriumConstant.MaxLevel); field = Math.Min(Math.Max(1, value), GameplayEquilibriumConstant.MaxLevel);
if (past != _Level) if (past != field)
{ {
OnAttributeChanged(); OnAttributeChanged();
Recovery(); Recovery();
@ -228,13 +228,13 @@ namespace Milimoe.FunGame.Core.Entity
{ {
get get
{ {
return _HP < 0 ? 0 : (_HP > MaxHP ? MaxHP : _HP); return field < 0 ? 0 : (field > MaxHP ? MaxHP : field);
} }
set set
{ {
_HP = value; field = value;
if (_HP > MaxHP) _HP = MaxHP; if (field > MaxHP) field = MaxHP;
else if (_HP < 0) _HP = 0; else if (field < 0) field = 0;
} }
} }
@ -287,13 +287,13 @@ namespace Milimoe.FunGame.Core.Entity
{ {
get get
{ {
return _MP < 0 ? 0 : (_MP > MaxMP ? MaxMP : _MP); return field < 0 ? 0 : (field > MaxMP ? MaxMP : field);
} }
set set
{ {
_MP = value; field = value;
if (_MP > MaxMP) _MP = MaxMP; if (field > MaxMP) field = MaxMP;
else if (_MP < 0) _MP = 0; else if (field < 0) field = 0;
} }
} }
@ -304,13 +304,13 @@ namespace Milimoe.FunGame.Core.Entity
{ {
get get
{ {
return _EP < 0 ? 0 : (_EP > GameplayEquilibriumConstant.MaxEP ? GameplayEquilibriumConstant.MaxEP : _EP); return field < 0 ? 0 : (field > GameplayEquilibriumConstant.MaxEP ? GameplayEquilibriumConstant.MaxEP : field);
} }
set set
{ {
_EP = value; field = value;
if (_EP > GameplayEquilibriumConstant.MaxEP) _EP = GameplayEquilibriumConstant.MaxEP; if (field > GameplayEquilibriumConstant.MaxEP) field = GameplayEquilibriumConstant.MaxEP;
else if (_EP < 0) _EP = 0; else if (field < 0) field = 0;
} }
} }
@ -450,11 +450,11 @@ namespace Milimoe.FunGame.Core.Entity
{ {
get get
{ {
return Calculation.PercentageCheck(_PhysicalPenetration); return Calculation.PercentageCheck(field);
} }
set set
{ {
_PhysicalPenetration = Calculation.PercentageCheck(value); field = Calculation.PercentageCheck(value);
} }
} }
@ -465,11 +465,11 @@ namespace Milimoe.FunGame.Core.Entity
{ {
get get
{ {
return Calculation.PercentageCheck(_MagicalPenetration); return Calculation.PercentageCheck(field);
} }
set set
{ {
_MagicalPenetration = Calculation.PercentageCheck(value); field = Calculation.PercentageCheck(value);
} }
} }
@ -898,40 +898,6 @@ namespace Milimoe.FunGame.Core.Entity
/// </summary> /// </summary>
public HashSet<Item> Items { get; } = []; public HashSet<Item> Items { get; } = [];
/**
* ===== =====
*/
/// <summary>
/// 等级
/// </summary>
private int _Level = 1;
/// <summary>
/// 生命值
/// </summary>
private double _HP = 0;
/// <summary>
/// 魔法值
/// </summary>
private double _MP = 0;
/// <summary>
/// 能量值
/// </summary>
private double _EP = 0;
/// <summary>
/// 物理穿透
/// </summary>
private double _PhysicalPenetration = 0;
/// <summary>
/// 魔法穿透
/// </summary>
private double _MagicalPenetration = 0;
protected Character() protected Character()
{ {
User = General.UnknownUserInstance; User = General.UnknownUserInstance;

View File

@ -9,11 +9,24 @@ namespace Milimoe.FunGame.Core.Entity
{ {
public DateTime? StartTime { get; set; } = null; public DateTime? StartTime { get; set; } = null;
public DateTime? EndTime { get; set; } = null; public DateTime? EndTime { get; set; } = null;
public DateTime? EndAwardedTime
{
get
{
if (field is null && EndTime != null)
{
return EndTime.Value.AddDays(7);
}
return field;
}
set => field = value;
}
public string Description { get; set; } = ""; public string Description { get; set; } = "";
public ActivityState Status { get; private set; } = ActivityState.Future; public ActivityState Status { get; private set; } = ActivityState.Future;
public HashSet<Quest> Quests { get; set; } = []; public HashSet<Quest> Quests { get; } = [];
public long Predecessor { get; set; } = -1; public long Predecessor { get; set; } = -1;
public ActivityState PredecessorStatus { get; set; } = ActivityState.Future; public ActivityState PredecessorStatus { get; set; } = ActivityState.Future;
public Dictionary<long, HashSet<long>> QuestsAwardedUsers { get; } = [];
public Activity(long id, string name, DateTime? startTime = null, DateTime? endTime = null) public Activity(long id, string name, DateTime? startTime = null, DateTime? endTime = null)
{ {
@ -101,6 +114,34 @@ namespace Milimoe.FunGame.Core.Entity
return args.AllowAccess; return args.AllowAccess;
} }
public bool RegisterAwardedUser(long userId, Quest quest)
{
if (Quests.Contains(quest))
{
if (!QuestsAwardedUsers.TryGetValue(quest.Id, out HashSet<long>? value))
{
value = [];
QuestsAwardedUsers[quest.Id] = value;
}
value.Add(userId);
return true;
}
return false;
}
public bool RegisterAwardedUser(long userId, long questId) => Quests.FirstOrDefault(q => q.Id == questId && q.Status == QuestState.Completed) is Quest quest && RegisterAwardedUser(userId, quest);
public bool HasUserAwarded(long userId, Quest quest)
{
if (QuestsAwardedUsers.TryGetValue(quest.Id, out HashSet<long>? value))
{
return value.Contains(userId);
}
return false;
}
public bool HasUserAwarded(long userId, long questId) => Quests.FirstOrDefault(q => q.Id == questId) is Quest quest && HasUserAwarded(userId, quest);
public void GetActivityInfo(long userId, long questId = 0) public void GetActivityInfo(long userId, long questId = 0)
{ {
UpdateState(); UpdateState();

View File

@ -169,18 +169,18 @@ namespace Milimoe.FunGame.Core.Entity
/// </summary> /// </summary>
public Character? Character public Character? Character
{ {
get => _character; get => field;
set set
{ {
_character = value; field = value;
if (Skills.Active != null) Skills.Active.Character = _character; Skills.Active?.Character = field;
foreach (Skill skill in Skills.Passives) foreach (Skill skill in Skills.Passives)
{ {
skill.Character = _character; skill.Character = field;
} }
foreach (Skill skill in Skills.Magics) foreach (Skill skill in Skills.Magics)
{ {
skill.Character = _character; skill.Character = field;
} }
} }
} }
@ -229,7 +229,7 @@ namespace Milimoe.FunGame.Core.Entity
Character.Skills.Add(skill); Character.Skills.Add(skill);
} }
} }
if (Character != null) OnItemEquipped(Character, this, type); if (Character != null) OnItemEquipped(Character, type);
} }
/// <summary> /// <summary>
@ -273,7 +273,7 @@ namespace Milimoe.FunGame.Core.Entity
Character.EquipSlot.Accessory2 = null; Character.EquipSlot.Accessory2 = null;
break; break;
} }
OnItemUnEquipped(Character, this, type); OnItemUnEquipped(Character, type);
} }
Character = null; Character = null;
EquipSlotType = EquipSlotType.None; EquipSlotType = EquipSlotType.None;
@ -285,7 +285,7 @@ namespace Milimoe.FunGame.Core.Entity
/// <param name="queue"></param> /// <param name="queue"></param>
public void SetGamingQueue(IGamingQueue queue) public void SetGamingQueue(IGamingQueue queue)
{ {
if (Skills.Active != null) Skills.Active.GamingQueue = queue; Skills.Active?.GamingQueue = queue;
foreach (Skill skill in Skills.Passives) foreach (Skill skill in Skills.Passives)
{ {
skill.GamingQueue = queue; skill.GamingQueue = queue;
@ -390,9 +390,8 @@ namespace Milimoe.FunGame.Core.Entity
/// 当物品被装备时 /// 当物品被装备时
/// </summary> /// </summary>
/// <param name="character"></param> /// <param name="character"></param>
/// <param name="item"></param>
/// <param name="type"></param> /// <param name="type"></param>
protected virtual void OnItemEquipped(Character character, Item item, EquipSlotType type) protected virtual void OnItemEquipped(Character character, EquipSlotType type)
{ {
} }
@ -401,9 +400,8 @@ namespace Milimoe.FunGame.Core.Entity
/// 当物品被取消装备时 /// 当物品被取消装备时
/// </summary> /// </summary>
/// <param name="character"></param> /// <param name="character"></param>
/// <param name="item"></param>
/// <param name="type"></param> /// <param name="type"></param>
protected virtual void OnItemUnEquipped(Character character, Item item, EquipSlotType type) protected virtual void OnItemUnEquipped(Character character, EquipSlotType type)
{ {
} }
@ -703,10 +701,7 @@ namespace Milimoe.FunGame.Core.Entity
/// <param name="level"></param> /// <param name="level"></param>
public void SetLevel(int level) public void SetLevel(int level)
{ {
if (Skills.Active != null) Skills.Active?.Level = level;
{
Skills.Active.Level = level;
}
foreach (Skill skill in Skills.Passives) foreach (Skill skill in Skills.Passives)
{ {
skill.Level = level; skill.Level = level;
@ -724,10 +719,5 @@ namespace Milimoe.FunGame.Core.Entity
skill.Level = level; skill.Level = level;
} }
} }
/// <summary>
/// 所属的角色
/// </summary>
private Character? _character = null;
} }
} }

View File

@ -95,23 +95,23 @@ namespace Milimoe.FunGame.Core.Entity
{ {
get get
{ {
return Math.Max(1, _Level); return Math.Max(1, _level);
} }
set set
{ {
_Level = Math.Min(Math.Max(1, value), GameplayEquilibriumConstant.MaxNormalAttackLevel); _level = Math.Min(Math.Max(1, value), GameplayEquilibriumConstant.MaxNormalAttackLevel);
} }
} }
/// <summary> /// <summary>
/// 是否是魔法伤害 /// 是否是魔法伤害
/// </summary> /// </summary>
public bool IsMagic => _IsMagic; public bool IsMagic => _isMagic;
/// <summary> /// <summary>
/// 魔法伤害需要指定魔法类型 /// 魔法伤害需要指定魔法类型
/// </summary> /// </summary>
public MagicType MagicType => _MagicType; public MagicType MagicType => _magicType;
/// <summary> /// <summary>
/// 是否可用 /// 是否可用
@ -364,12 +364,12 @@ namespace Milimoe.FunGame.Core.Entity
/// <param name="queue"></param> /// <param name="queue"></param>
public void SetMagicType(bool? isMagic, MagicType? magicType = null, IGamingQueue? queue = null) public void SetMagicType(bool? isMagic, MagicType? magicType = null, IGamingQueue? queue = null)
{ {
_ExIsMagic = isMagic; _exIsMagic = isMagic;
if (isMagic.HasValue && isMagic.Value) if (isMagic.HasValue && isMagic.Value)
{ {
magicType ??= MagicType.None; magicType ??= MagicType.None;
} }
_ExMagicType = magicType; _exMagicType = magicType;
ResolveMagicType(queue); ResolveMagicType(queue);
} }
@ -400,37 +400,37 @@ namespace Milimoe.FunGame.Core.Entity
/// </summary> /// </summary>
internal void ResolveMagicType(IGamingQueue? queue = null) internal void ResolveMagicType(IGamingQueue? queue = null)
{ {
bool past = _IsMagic; bool past = _isMagic;
MagicType pastType = _MagicType; MagicType pastType = _magicType;
if (NormalAttackOfEffects.Count > 0) if (NormalAttackOfEffects.Count > 0)
{ {
if (NormalAttackOfEffects.Values.OrderByDescending(n => n.Priority).FirstOrDefault() is NormalAttackOfEffect naoe) if (NormalAttackOfEffects.Values.OrderByDescending(n => n.Priority).FirstOrDefault() is NormalAttackOfEffect naoe)
{ {
_IsMagic = naoe.IsMagic; _isMagic = naoe.IsMagic;
_MagicType = naoe.MagicType; _magicType = naoe.MagicType;
} }
} }
else if (_ExIsMagic.HasValue && _ExMagicType.HasValue) else if (_exIsMagic.HasValue && _exMagicType.HasValue)
{ {
_IsMagic = _ExIsMagic.Value; _isMagic = _exIsMagic.Value;
_MagicType = _ExMagicType.Value; _magicType = _exMagicType.Value;
} }
else else
{ {
_IsMagic = false; _isMagic = false;
_MagicType = MagicType.None; _magicType = MagicType.None;
if (Character.EquipSlot.Weapon != null) if (Character.EquipSlot.Weapon != null)
{ {
WeaponType type = Character.EquipSlot.Weapon.WeaponType; WeaponType type = Character.EquipSlot.Weapon.WeaponType;
if (type == WeaponType.Talisman || type == WeaponType.Staff) if (type == WeaponType.Talisman || type == WeaponType.Staff)
{ {
_IsMagic = true; _isMagic = true;
} }
} }
} }
if (queue != null && (past != _IsMagic || pastType != _MagicType)) if (queue != null && (past != _isMagic || pastType != _magicType))
{ {
queue.WriteLine($"[ {Character} ] 的普通攻击类型已转变为:{(_IsMagic ? CharacterSet.GetMagicDamageName(_MagicType) : "")}"); queue.WriteLine($"[ {Character} ] 的普通攻击类型已转变为:{(_isMagic ? CharacterSet.GetMagicDamageName(_magicType) : "")}");
} }
} }
@ -470,27 +470,27 @@ namespace Milimoe.FunGame.Core.Entity
/// <summary> /// <summary>
/// 等级 /// 等级
/// </summary> /// </summary>
private int _Level = 0; private int _level = 0;
/// <summary> /// <summary>
/// 是否是魔法伤害 [ 生效型 ] /// 是否是魔法伤害 [ 生效型 ]
/// </summary> /// </summary>
private bool _IsMagic = isMagic; private bool _isMagic = isMagic;
/// <summary> /// <summary>
/// 魔法类型 [ 生效型 ] /// 魔法类型 [ 生效型 ]
/// </summary> /// </summary>
private MagicType _MagicType = magicType; private MagicType _magicType = magicType;
/// <summary> /// <summary>
/// 是否是魔法伤害 [ 修改型 ] /// 是否是魔法伤害 [ 修改型 ]
/// </summary> /// </summary>
private bool? _ExIsMagic = null; private bool? _exIsMagic = null;
/// <summary> /// <summary>
/// 魔法类型 [ 修改型 ] /// 魔法类型 [ 修改型 ]
/// </summary> /// </summary>
private MagicType? _ExMagicType = null; private MagicType? _exMagicType = null;
} }
/// <summary> /// <summary>

View File

@ -49,12 +49,12 @@ namespace Milimoe.FunGame.Core.Entity
{ {
get get
{ {
return Math.Max(0, _Level); return Math.Max(0, field);
} }
set set
{ {
int max = SkillSet.GetSkillMaxLevel(SkillType, GameplayEquilibriumConstant); int max = SkillSet.GetSkillMaxLevel(SkillType, GameplayEquilibriumConstant);
_Level = Math.Min(Math.Max(0, value), max); field = Math.Min(Math.Max(0, value), max);
OnLevelUp(); OnLevelUp();
} }
} }
@ -101,9 +101,9 @@ namespace Milimoe.FunGame.Core.Entity
[InitOptional] [InitOptional]
public int CastRange public int CastRange
{ {
get => Math.Max(1, CastAnywhere ? (GamingQueue?.Map != null ? GamingQueue.Map.Grids.Count : 999) : _CastRange); get => Math.Max(1, CastAnywhere ? (GamingQueue?.Map != null ? GamingQueue.Map.Grids.Count : 999) : field);
set => _CastRange = Math.Max(1, value); set => field = Math.Max(1, value);
} } = 3;
/// <summary> /// <summary>
/// 可选取自身 /// 可选取自身
@ -151,7 +151,7 @@ namespace Milimoe.FunGame.Core.Entity
/// <see cref="SkillRangeType.Diamond"/> - 菱形。默认的曼哈顿距离正方形<para/> /// <see cref="SkillRangeType.Diamond"/> - 菱形。默认的曼哈顿距离正方形<para/>
/// <see cref="SkillRangeType.Circle"/> - 圆形。基于欧几里得距离的圆形<para/> /// <see cref="SkillRangeType.Circle"/> - 圆形。基于欧几里得距离的圆形<para/>
/// <see cref="SkillRangeType.Square"/> - 正方形<para/> /// <see cref="SkillRangeType.Square"/> - 正方形<para/>
/// <see cref="SkillRangeType.Line"/> - 施法者与目标之的直线<para/> /// <see cref="SkillRangeType.Line"/> - 施法者与目标之的直线<para/>
/// <see cref="SkillRangeType.LinePass"/> - 施法者与目标所在的直线,贯穿至地图边缘<para/> /// <see cref="SkillRangeType.LinePass"/> - 施法者与目标所在的直线,贯穿至地图边缘<para/>
/// <see cref="SkillRangeType.Sector"/> - 扇形<para/> /// <see cref="SkillRangeType.Sector"/> - 扇形<para/>
/// 注意,该属性不影响选取目标的范围。选取目标的范围由 <see cref="Library.Common.Addon.GameMap"/> 决定。 /// 注意,该属性不影响选取目标的范围。选取目标的范围由 <see cref="Library.Common.Addon.GameMap"/> 决定。
@ -682,15 +682,5 @@ namespace Milimoe.FunGame.Core.Entity
} }
return skill; return skill;
} }
/// <summary>
/// 等级
/// </summary>
private int _Level = 0;
/// <summary>
/// 施法距离
/// </summary>
private int _CastRange = 3;
} }
} }

View File

@ -20,13 +20,13 @@ namespace Milimoe.FunGame.Core.Entity
{ {
get get
{ {
return _customName.Trim() == "" ? User.Username + "的库存" : _customName; return field.Trim() == "" ? User.Username + "的库存" : field;
} }
set set
{ {
_customName = value; field = value;
} }
} } = "";
/// <summary> /// <summary>
/// 库存属于哪个玩家 /// 库存属于哪个玩家
@ -60,20 +60,20 @@ namespace Milimoe.FunGame.Core.Entity
{ {
get get
{ {
if (_character != null) if (field != null)
{ {
return _character; return field;
} }
else if (Characters.Count > 0) else if (Characters.Count > 0)
{ {
_character = Characters.First(); field = Characters.First();
return _character; return field;
} }
return Factory.GetCharacter(); return Factory.GetCharacter();
} }
set set
{ {
_character = value; field = value;
} }
} }
@ -87,9 +87,6 @@ namespace Milimoe.FunGame.Core.Entity
/// </summary> /// </summary>
public Dictionary<long, DateTime> Training { get; set; } = []; public Dictionary<long, DateTime> Training { get; set; } = [];
private Character? _character;
private string _customName = "";
internal Inventory(User user) internal Inventory(User user)
{ {
User = user; User = user;

View File

@ -34,14 +34,14 @@ namespace Milimoe.FunGame.Core.Library.Common.Addon
/// <summary> /// <summary>
/// 加载标记 /// 加载标记
/// </summary> /// </summary>
private bool IsLoaded = false; private bool _isLoaded = false;
/// <summary> /// <summary>
/// 加载模组 /// 加载模组
/// </summary> /// </summary>
public bool Load(params object[] objs) public bool Load(params object[] objs)
{ {
if (IsLoaded) if (_isLoaded)
{ {
return false; return false;
} }
@ -49,13 +49,13 @@ namespace Milimoe.FunGame.Core.Library.Common.Addon
if (BeforeLoad()) if (BeforeLoad())
{ {
// 模组加载后,不允许再次加载此模组 // 模组加载后,不允许再次加载此模组
IsLoaded = true; _isLoaded = true;
// 注册工厂 // 注册工厂
Factory.OpenFactory.RegisterFactory(EntityFactory()); Factory.OpenFactory.RegisterFactory(EntityFactory());
// 如果加载后需要执行代码请重写AfterLoad方法 // 如果加载后需要执行代码请重写AfterLoad方法
AfterLoad(); AfterLoad();
} }
return IsLoaded; return _isLoaded;
} }
/// <summary> /// <summary>

View File

@ -101,7 +101,7 @@ namespace Milimoe.FunGame.Core.Library.Common.Addon
/// <summary> /// <summary>
/// 加载标记 /// 加载标记
/// </summary> /// </summary>
private bool IsLoaded = false; private bool _isLoaded = false;
/// <summary> /// <summary>
/// 加载地图 /// 加载地图
@ -110,7 +110,7 @@ namespace Milimoe.FunGame.Core.Library.Common.Addon
/// <returns></returns> /// <returns></returns>
public bool Load(params object[] objs) public bool Load(params object[] objs)
{ {
if (IsLoaded) if (_isLoaded)
{ {
return false; return false;
} }
@ -118,7 +118,7 @@ namespace Milimoe.FunGame.Core.Library.Common.Addon
if (BeforeLoad()) if (BeforeLoad())
{ {
// 地图加载后,不允许再次加载此地图 // 地图加载后,不允许再次加载此地图
IsLoaded = true; _isLoaded = true;
// 生成格子 // 生成格子
for (int x = 0; x < Length; x++) for (int x = 0; x < Length; x++)
{ {
@ -133,7 +133,7 @@ namespace Milimoe.FunGame.Core.Library.Common.Addon
} }
} }
} }
return IsLoaded; return _isLoaded;
} }
/// <summary> /// <summary>

View File

@ -65,8 +65,8 @@ namespace Milimoe.FunGame.Core.Library.Common.Addon
/// </summary> /// </summary>
public string AssociatedServerModuleName public string AssociatedServerModuleName
{ {
get => IsConnectToOtherServerModule ? _AssociatedServerModuleName : Name; get => IsConnectToOtherServerModule ? _associatedServerModuleName : Name;
set => _AssociatedServerModuleName = value; set => _associatedServerModuleName = value;
} }
/// <summary> /// <summary>
@ -74,8 +74,8 @@ namespace Milimoe.FunGame.Core.Library.Common.Addon
/// </summary> /// </summary>
public AddonController<IGameModule> Controller public AddonController<IGameModule> Controller
{ {
get => _Controller ?? throw new NotImplementedException(); get => _controller ?? throw new NotImplementedException();
internal set => _Controller = value; internal set => _controller = value;
} }
/// <summary> /// <summary>
@ -84,13 +84,13 @@ namespace Milimoe.FunGame.Core.Library.Common.Addon
BaseAddonController<IGameModule> IAddonController<IGameModule>.Controller BaseAddonController<IGameModule> IAddonController<IGameModule>.Controller
{ {
get => Controller; get => Controller;
set => _Controller = (AddonController<IGameModule>?)value; set => _controller = (AddonController<IGameModule>?)value;
} }
/// <summary> /// <summary>
/// 控制器内部变量 /// 控制器内部变量
/// </summary> /// </summary>
private AddonController<IGameModule>? _Controller; private AddonController<IGameModule>? _controller;
/// <summary> /// <summary>
/// 必须重写此方法,游戏的主要逻辑写在这里面<para/> /// 必须重写此方法,游戏的主要逻辑写在这里面<para/>
@ -114,14 +114,14 @@ namespace Milimoe.FunGame.Core.Library.Common.Addon
/// <summary> /// <summary>
/// 加载标记 /// 加载标记
/// </summary> /// </summary>
private bool IsLoaded = false; private bool _isLoaded = false;
/// <summary> /// <summary>
/// 加载模组 /// 加载模组
/// </summary> /// </summary>
public bool Load(params object[] objs) public bool Load(params object[] objs)
{ {
if (IsLoaded) if (_isLoaded)
{ {
return false; return false;
} }
@ -129,13 +129,13 @@ namespace Milimoe.FunGame.Core.Library.Common.Addon
if (BeforeLoad(objs)) if (BeforeLoad(objs))
{ {
// 模组加载后,不允许再次加载此模组 // 模组加载后,不允许再次加载此模组
IsLoaded = true; _isLoaded = true;
// 初始化此模组传入委托或者Model // 初始化此模组传入委托或者Model
Init(objs); Init(objs);
// 触发绑定事件 // 触发绑定事件
BindEvent(); BindEvent();
} }
return IsLoaded; return _isLoaded;
} }
/// <summary> /// <summary>
@ -160,24 +160,24 @@ namespace Milimoe.FunGame.Core.Library.Common.Addon
/// </summary> /// </summary>
private void Init(params object[] objs) private void Init(params object[] objs)
{ {
if (objs.Length > 0) Session = (Session)objs[0]; if (objs.Length > 0) _session = (Session)objs[0];
if (objs.Length > 1) Config = (FunGameConfig)objs[1]; if (objs.Length > 1) _config = (FunGameConfig)objs[1];
} }
/// <summary> /// <summary>
/// Session对象 /// Session对象
/// </summary> /// </summary>
protected Session Session = new(); protected Session _session = new();
/// <summary> /// <summary>
/// Config对象 /// Config对象
/// </summary> /// </summary>
protected FunGameConfig Config = new(); protected FunGameConfig _config = new();
/// <summary> /// <summary>
/// 关联的服务器模组名称 /// 关联的服务器模组名称
/// </summary> /// </summary>
private string _AssociatedServerModuleName = ""; private string _associatedServerModuleName = "";
/// <summary> /// <summary>
/// 绑定事件。在<see cref="BeforeLoad"/>后触发 /// 绑定事件。在<see cref="BeforeLoad"/>后触发

View File

@ -50,8 +50,8 @@ namespace Milimoe.FunGame.Core.Library.Common.Addon
/// </summary> /// </summary>
public ServerAddonController<IGameModuleServer> Controller public ServerAddonController<IGameModuleServer> Controller
{ {
get => _Controller ?? throw new NotImplementedException(); get => _controller ?? throw new NotImplementedException();
internal set => _Controller = value; internal set => _controller = value;
} }
/// <summary> /// <summary>
@ -60,13 +60,13 @@ namespace Milimoe.FunGame.Core.Library.Common.Addon
BaseAddonController<IGameModuleServer> IAddonController<IGameModuleServer>.Controller BaseAddonController<IGameModuleServer> IAddonController<IGameModuleServer>.Controller
{ {
get => Controller; get => Controller;
set => _Controller = (ServerAddonController<IGameModuleServer>?)value; set => _controller = (ServerAddonController<IGameModuleServer>?)value;
} }
/// <summary> /// <summary>
/// 控制器内部变量 /// 控制器内部变量
/// </summary> /// </summary>
private ServerAddonController<IGameModuleServer>? _Controller; private ServerAddonController<IGameModuleServer>? _controller;
/// <summary> /// <summary>
/// 此模组所有正在运行的游戏对象 /// 此模组所有正在运行的游戏对象
@ -127,14 +127,14 @@ namespace Milimoe.FunGame.Core.Library.Common.Addon
/// <summary> /// <summary>
/// 加载标记 /// 加载标记
/// </summary> /// </summary>
private bool IsLoaded = false; private bool _isLoaded = false;
/// <summary> /// <summary>
/// 加载模组 /// 加载模组
/// </summary> /// </summary>
public bool Load(params object[] objs) public bool Load(params object[] objs)
{ {
if (IsLoaded) if (_isLoaded)
{ {
return false; return false;
} }
@ -142,9 +142,9 @@ namespace Milimoe.FunGame.Core.Library.Common.Addon
if (BeforeLoad()) if (BeforeLoad())
{ {
// 模组加载后,不允许再次加载此模组 // 模组加载后,不允许再次加载此模组
IsLoaded = true; _isLoaded = true;
} }
return IsLoaded; return _isLoaded;
} }
/// <summary> /// <summary>

View File

@ -34,14 +34,14 @@ namespace Milimoe.FunGame.Core.Library.Common.Addon
/// <summary> /// <summary>
/// 加载标记 /// 加载标记
/// </summary> /// </summary>
private bool IsLoaded = false; private bool _isLoaded = false;
/// <summary> /// <summary>
/// 加载模组 /// 加载模组
/// </summary> /// </summary>
public bool Load(params object[] objs) public bool Load(params object[] objs)
{ {
if (IsLoaded) if (_isLoaded)
{ {
return false; return false;
} }
@ -49,13 +49,13 @@ namespace Milimoe.FunGame.Core.Library.Common.Addon
if (BeforeLoad()) if (BeforeLoad())
{ {
// 模组加载后,不允许再次加载此模组 // 模组加载后,不允许再次加载此模组
IsLoaded = true; _isLoaded = true;
// 注册工厂 // 注册工厂
Factory.OpenFactory.RegisterFactory(ItemFactory()); Factory.OpenFactory.RegisterFactory(ItemFactory());
// 如果加载后需要执行代码请重写AfterLoad方法 // 如果加载后需要执行代码请重写AfterLoad方法
AfterLoad(); AfterLoad();
} }
return IsLoaded; return _isLoaded;
} }
/// <summary> /// <summary>

View File

@ -34,8 +34,8 @@ namespace Milimoe.FunGame.Core.Library.Common.Addon
/// </summary> /// </summary>
public AddonController<IPlugin> Controller public AddonController<IPlugin> Controller
{ {
get => _Controller ?? throw new NotImplementedException(); get => _controller ?? throw new NotImplementedException();
internal set => _Controller = value; internal set => _controller = value;
} }
/// <summary> /// <summary>
@ -44,25 +44,25 @@ namespace Milimoe.FunGame.Core.Library.Common.Addon
BaseAddonController<IPlugin> IAddonController<IPlugin>.Controller BaseAddonController<IPlugin> IAddonController<IPlugin>.Controller
{ {
get => Controller; get => Controller;
set => _Controller = (AddonController<IPlugin>?)value; set => _controller = (AddonController<IPlugin>?)value;
} }
/// <summary> /// <summary>
/// 控制器内部变量 /// 控制器内部变量
/// </summary> /// </summary>
private AddonController<IPlugin>? _Controller; private AddonController<IPlugin>? _controller;
/// <summary> /// <summary>
/// 加载标记 /// 加载标记
/// </summary> /// </summary>
private bool IsLoaded = false; private bool _isLoaded = false;
/// <summary> /// <summary>
/// 加载插件 /// 加载插件
/// </summary> /// </summary>
public bool Load(params object[] objs) public bool Load(params object[] objs)
{ {
if (IsLoaded) if (_isLoaded)
{ {
return false; return false;
} }
@ -70,13 +70,13 @@ namespace Milimoe.FunGame.Core.Library.Common.Addon
if (BeforeLoad(objs)) if (BeforeLoad(objs))
{ {
// 插件加载后,不允许再次加载此插件 // 插件加载后,不允许再次加载此插件
IsLoaded = true; _isLoaded = true;
// 初始化此插件传入委托或者Model // 初始化此插件传入委托或者Model
Init(objs); Init(objs);
// 触发绑定事件 // 触发绑定事件
BindEvent(); BindEvent();
} }
return IsLoaded; return _isLoaded;
} }
/// <summary> /// <summary>
@ -101,19 +101,19 @@ namespace Milimoe.FunGame.Core.Library.Common.Addon
/// </summary> /// </summary>
private void Init(params object[] objs) private void Init(params object[] objs)
{ {
if (objs.Length > 0) Session = (Session)objs[0]; if (objs.Length > 0) _session = (Session)objs[0];
if (objs.Length > 1) Config = (FunGameConfig)objs[1]; if (objs.Length > 1) _config = (FunGameConfig)objs[1];
} }
/// <summary> /// <summary>
/// Session对象 /// Session对象
/// </summary> /// </summary>
protected Session Session = new(); protected Session _session = new();
/// <summary> /// <summary>
/// Config对象 /// Config对象
/// </summary> /// </summary>
protected FunGameConfig Config = new(); protected FunGameConfig _config = new();
/// <summary> /// <summary>
/// 绑定事件。在<see cref="BeforeLoad"/>后触发 /// 绑定事件。在<see cref="BeforeLoad"/>后触发

View File

@ -33,8 +33,8 @@ namespace Milimoe.FunGame.Core.Library.Common.Addon
/// </summary> /// </summary>
public ServerAddonController<IPlugin> Controller public ServerAddonController<IPlugin> Controller
{ {
get => _Controller ?? throw new NotImplementedException(); get => _controller ?? throw new NotImplementedException();
internal set => _Controller = value; internal set => _controller = value;
} }
/// <summary> /// <summary>
@ -43,25 +43,25 @@ namespace Milimoe.FunGame.Core.Library.Common.Addon
BaseAddonController<IPlugin> IAddonController<IPlugin>.Controller BaseAddonController<IPlugin> IAddonController<IPlugin>.Controller
{ {
get => Controller; get => Controller;
set => _Controller = (ServerAddonController<IPlugin>?)value; set => _controller = (ServerAddonController<IPlugin>?)value;
} }
/// <summary> /// <summary>
/// 控制器内部变量 /// 控制器内部变量
/// </summary> /// </summary>
private ServerAddonController<IPlugin>? _Controller; private ServerAddonController<IPlugin>? _controller;
/// <summary> /// <summary>
/// 加载标记 /// 加载标记
/// </summary> /// </summary>
private bool IsLoaded = false; private bool _isLoaded = false;
/// <summary> /// <summary>
/// 加载插件 /// 加载插件
/// </summary> /// </summary>
public bool Load(params object[] objs) public bool Load(params object[] objs)
{ {
if (IsLoaded) if (_isLoaded)
{ {
return false; return false;
} }
@ -69,11 +69,11 @@ namespace Milimoe.FunGame.Core.Library.Common.Addon
if (BeforeLoad(objs)) if (BeforeLoad(objs))
{ {
// 插件加载后,不允许再次加载此插件 // 插件加载后,不允许再次加载此插件
IsLoaded = true; _isLoaded = true;
// 触发绑定事件 // 触发绑定事件
BindEvent(); BindEvent();
} }
return IsLoaded; return _isLoaded;
} }
/// <summary> /// <summary>

View File

@ -34,14 +34,14 @@ namespace Milimoe.FunGame.Core.Library.Common.Addon
/// <summary> /// <summary>
/// 加载标记 /// 加载标记
/// </summary> /// </summary>
private bool IsLoaded = false; private bool _isLoaded = false;
/// <summary> /// <summary>
/// 加载模组 /// 加载模组
/// </summary> /// </summary>
public bool Load(params object[] objs) public bool Load(params object[] objs)
{ {
if (IsLoaded) if (_isLoaded)
{ {
return false; return false;
} }
@ -49,14 +49,14 @@ namespace Milimoe.FunGame.Core.Library.Common.Addon
if (BeforeLoad()) if (BeforeLoad())
{ {
// 模组加载后,不允许再次加载此模组 // 模组加载后,不允许再次加载此模组
IsLoaded = true; _isLoaded = true;
// 注册工厂 // 注册工厂
Factory.OpenFactory.RegisterFactory(SkillFactory()); Factory.OpenFactory.RegisterFactory(SkillFactory());
Factory.OpenFactory.RegisterFactory(EffectFactory()); Factory.OpenFactory.RegisterFactory(EffectFactory());
// 如果加载后需要执行代码请重写AfterLoad方法 // 如果加载后需要执行代码请重写AfterLoad方法
AfterLoad(); AfterLoad();
} }
return IsLoaded; return _isLoaded;
} }
/// <summary> /// <summary>

View File

@ -33,8 +33,8 @@ namespace Milimoe.FunGame.Core.Library.Common.Addon
/// </summary> /// </summary>
public ServerAddonController<IAddon> Controller public ServerAddonController<IAddon> Controller
{ {
get => _Controller ?? throw new NotImplementedException(); get => _controller ?? throw new NotImplementedException();
internal set => _Controller = value; internal set => _controller = value;
} }
/// <summary> /// <summary>
@ -43,13 +43,13 @@ namespace Milimoe.FunGame.Core.Library.Common.Addon
BaseAddonController<IAddon> IAddonController<IAddon>.Controller BaseAddonController<IAddon> IAddonController<IAddon>.Controller
{ {
get => Controller; get => Controller;
set => _Controller = (ServerAddonController<IAddon>?)value; set => _controller = (ServerAddonController<IAddon>?)value;
} }
/// <summary> /// <summary>
/// 控制器内部变量 /// 控制器内部变量
/// </summary> /// </summary>
private ServerAddonController<IAddon>? _Controller; private ServerAddonController<IAddon>? _controller;
/// <summary> /// <summary>
/// 加载标记 /// 加载标记

View File

@ -7,26 +7,26 @@ namespace Milimoe.FunGame.Core.Library.Common.Architecture
public class HeartBeat : ISocketHeartBeat public class HeartBeat : ISocketHeartBeat
{ {
public TransmittalType TransmittalType { get; } = TransmittalType.Socket; public TransmittalType TransmittalType { get; } = TransmittalType.Socket;
public bool SendingHeartBeat => _SendingHeartBeat; public bool SendingHeartBeat => _sendingHeartBeat;
public int HeartBeatFaileds => _HeartBeatFaileds; public int HeartBeatFaileds => _heartBeatFaileds;
private Task? SendingHeartBeatTask; private Task? _sendingHeartBeatTask;
private bool _SendingHeartBeat = false; private bool _sendingHeartBeat = false;
private bool _LastHeartbeatReceived = false; private bool _lastHeartbeatReceived = false;
private int _HeartBeatFaileds = 0; private int _heartBeatFaileds = 0;
private readonly Socket? _Socket = null; private readonly Socket? _socket = null;
private readonly HTTPClient? _HTTPClient = null; private readonly HTTPClient? _httpClient = null;
public HeartBeat(Socket socket) public HeartBeat(Socket socket)
{ {
_Socket = socket; _socket = socket;
TransmittalType = TransmittalType.Socket; TransmittalType = TransmittalType.Socket;
} }
public HeartBeat(HTTPClient client) public HeartBeat(HTTPClient client)
{ {
_HTTPClient = client; _httpClient = client;
TransmittalType = TransmittalType.WebSocket; TransmittalType = TransmittalType.WebSocket;
} }
@ -34,20 +34,20 @@ namespace Milimoe.FunGame.Core.Library.Common.Architecture
{ {
if (!FunGameInfo.FunGame_DebugMode) if (!FunGameInfo.FunGame_DebugMode)
{ {
_SendingHeartBeat = true; _sendingHeartBeat = true;
_Socket?.AddSocketObjectHandler(SocketObject_Handler); _socket?.AddSocketObjectHandler(SocketObject_Handler);
_HTTPClient?.AddSocketObjectHandler(SocketObject_Handler); _httpClient?.AddSocketObjectHandler(SocketObject_Handler);
SendingHeartBeatTask = Task.Factory.StartNew(SendHeartBeat); _sendingHeartBeatTask = Task.Factory.StartNew(SendHeartBeat);
} }
} }
public void StopSendingHeartBeat() public void StopSendingHeartBeat()
{ {
_SendingHeartBeat = false; _sendingHeartBeat = false;
SendingHeartBeatTask?.Wait(1); _sendingHeartBeatTask?.Wait(1);
SendingHeartBeatTask = null; _sendingHeartBeatTask = null;
_Socket?.RemoveSocketObjectHandler(SocketObject_Handler); _socket?.RemoveSocketObjectHandler(SocketObject_Handler);
_HTTPClient?.RemoveSocketObjectHandler(SocketObject_Handler); _httpClient?.RemoveSocketObjectHandler(SocketObject_Handler);
} }
private async Task SendHeartBeat() private async Task SendHeartBeat()
@ -55,51 +55,51 @@ namespace Milimoe.FunGame.Core.Library.Common.Architecture
try try
{ {
await Task.Delay(100); await Task.Delay(100);
if (_Socket != null) if (_socket != null)
{ {
while (_Socket.Connected) while (_socket.Connected)
{ {
if (!SendingHeartBeat) _SendingHeartBeat = true; if (!SendingHeartBeat) _sendingHeartBeat = true;
// 发送心跳包 // 发送心跳包
_LastHeartbeatReceived = false; _lastHeartbeatReceived = false;
if (_Socket.Send(SocketMessageType.HeartBeat) == SocketResult.Success) if (_socket.Send(SocketMessageType.HeartBeat) == SocketResult.Success)
{ {
await Task.Delay(4 * 1000); await Task.Delay(4 * 1000);
if (!_LastHeartbeatReceived) AddHeartBeatFaileds(); if (!_lastHeartbeatReceived) AddHeartBeatFaileds();
} }
else AddHeartBeatFaileds(); else AddHeartBeatFaileds();
await Task.Delay(20 * 1000); await Task.Delay(20 * 1000);
} }
} }
else if (_HTTPClient != null) else if (_httpClient != null)
{ {
while (_HTTPClient.WebSocket?.State == System.Net.WebSockets.WebSocketState.Open) while (_httpClient.WebSocket?.State == System.Net.WebSockets.WebSocketState.Open)
{ {
if (!SendingHeartBeat) _SendingHeartBeat = true; if (!SendingHeartBeat) _sendingHeartBeat = true;
// 发送心跳包 // 发送心跳包
_LastHeartbeatReceived = false; _lastHeartbeatReceived = false;
if (await _HTTPClient.Send(SocketMessageType.HeartBeat) == SocketResult.Success) if (await _httpClient.Send(SocketMessageType.HeartBeat) == SocketResult.Success)
{ {
await Task.Delay(4 * 1000); await Task.Delay(4 * 1000);
if (!_LastHeartbeatReceived) AddHeartBeatFaileds(); if (!_lastHeartbeatReceived) AddHeartBeatFaileds();
} }
else AddHeartBeatFaileds(); else AddHeartBeatFaileds();
await Task.Delay(20 * 1000); await Task.Delay(20 * 1000);
} }
} }
_SendingHeartBeat = false; _sendingHeartBeat = false;
} }
catch (System.Exception e) catch (System.Exception e)
{ {
if (_Socket != null) if (_socket != null)
{ {
_Socket.OnConnectionLost(e); _socket.OnConnectionLost(e);
_Socket.Close(); _socket.Close();
} }
if (_HTTPClient != null) if (_httpClient != null)
{ {
_HTTPClient.OnConnectionLost(e); _httpClient.OnConnectionLost(e);
_HTTPClient.Close(); _httpClient.Close();
} }
} }
} }
@ -107,10 +107,10 @@ namespace Milimoe.FunGame.Core.Library.Common.Architecture
private void AddHeartBeatFaileds() private void AddHeartBeatFaileds()
{ {
// 超过三次没回应心跳,服务器连接失败。 // 超过三次没回应心跳,服务器连接失败。
if (_HeartBeatFaileds++ >= 3) if (_heartBeatFaileds++ >= 3)
{ {
_Socket?.Close(); _socket?.Close();
_HTTPClient?.Close(); _httpClient?.Close();
throw new LostConnectException(); throw new LostConnectException();
} }
} }
@ -119,8 +119,8 @@ namespace Milimoe.FunGame.Core.Library.Common.Architecture
{ {
if (obj.SocketType == SocketMessageType.HeartBeat) if (obj.SocketType == SocketMessageType.HeartBeat)
{ {
_LastHeartbeatReceived = true; _lastHeartbeatReceived = true;
_HeartBeatFaileds = 0; _heartBeatFaileds = 0;
} }
} }
} }

View File

@ -6,21 +6,21 @@ namespace Milimoe.FunGame.Core.Model
{ {
public class RoomList : IEnumerable<Room> public class RoomList : IEnumerable<Room>
{ {
private readonly Dictionary<string, Room> _List = []; private readonly Dictionary<string, Room> _list = [];
private readonly Dictionary<string, List<User>> _UserList = []; private readonly Dictionary<string, List<User>> _userList = [];
private readonly Dictionary<string, List<User>> _ReadyUserList = []; private readonly Dictionary<string, List<User>> _readyUserList = [];
public Room this[string roomid] => GetRoom(roomid); public Room this[string roomid] => GetRoom(roomid);
public int Count => _List.Count; public int Count => _list.Count;
public int GetUserCount(string roomid) => this[roomid].UserAndIsReady.Count; public int GetUserCount(string roomid) => this[roomid].UserAndIsReady.Count;
public int GetReadyUserCount(string roomid) => GetReadyUserList(roomid).Count; public int GetReadyUserCount(string roomid) => GetReadyUserList(roomid).Count;
public List<Room> ListRoom => [.. _List.Values]; public List<Room> ListRoom => [.. _list.Values];
public List<string> ListRoomID => [.. _List.Keys]; public List<string> ListRoomID => [.. _list.Keys];
public User GetRoomMaster(string roomid) => this[roomid].RoomMaster; public User GetRoomMaster(string roomid) => this[roomid].RoomMaster;
@ -32,16 +32,16 @@ namespace Milimoe.FunGame.Core.Model
public void Clear() public void Clear()
{ {
_List.Clear(); _list.Clear();
_UserList.Clear(); _userList.Clear();
_ReadyUserList.Clear(); _readyUserList.Clear();
} }
public void AddRoom(Room room) public void AddRoom(Room room)
{ {
_List.Add(room.Roomid, room); _list.Add(room.Roomid, room);
_UserList.Add(room.Roomid, []); _userList.Add(room.Roomid, []);
_ReadyUserList.Add(room.Roomid, []); _readyUserList.Add(room.Roomid, []);
} }
public void AddRooms(List<Room> rooms) public void AddRooms(List<Room> rooms)
@ -54,9 +54,9 @@ namespace Milimoe.FunGame.Core.Model
public void RemoveRoom(string roomid) public void RemoveRoom(string roomid)
{ {
_List.Remove(roomid); _list.Remove(roomid);
_UserList.Remove(roomid); _userList.Remove(roomid);
_ReadyUserList.Remove(roomid); _readyUserList.Remove(roomid);
} }
public void RemoveRoom(Room room) => RemoveRoom(room.Roomid); public void RemoveRoom(Room room) => RemoveRoom(room.Roomid);
@ -96,9 +96,9 @@ namespace Milimoe.FunGame.Core.Model
} }
} }
public Room GetRoom(string roomid) => _List.TryGetValue(roomid, out Room? room) ? room : General.HallInstance; public Room GetRoom(string roomid) => _list.TryGetValue(roomid, out Room? room) ? room : General.HallInstance;
public bool Exists(string roomid) => _List.ContainsKey(roomid); public bool Exists(string roomid) => _list.ContainsKey(roomid);
public void SetRoomMaster(string roomid, User user) public void SetRoomMaster(string roomid, User user)
{ {

View File

@ -13,8 +13,7 @@ namespace Milimoe.FunGame.Core.Service
/// <summary> /// <summary>
/// 实际的 <see cref="System.Net.HttpListener"/> 监听实例 [ 单例 ] /// 实际的 <see cref="System.Net.HttpListener"/> 监听实例 [ 单例 ]
/// </summary> /// </summary>
internal static HttpListener? HttpListener => _HttpListener; internal static HttpListener? HttpListener { get; private set; } = null;
private static HttpListener? _HttpListener = null;
/// <summary> /// <summary>
/// 开始监听 /// 开始监听
@ -27,10 +26,10 @@ namespace Milimoe.FunGame.Core.Service
/// <returns></returns> /// <returns></returns>
internal static HttpListener StartListening(string address = "*", int port = 22223, string subUrl = "ws", bool ssl = false) internal static HttpListener StartListening(string address = "*", int port = 22223, string subUrl = "ws", bool ssl = false)
{ {
_HttpListener = new(); HttpListener = new();
_HttpListener.Prefixes.Add((ssl ? "https://" : "http://") + address + ":" + port + "/" + subUrl.Trim('/') + "/"); HttpListener.Prefixes.Add((ssl ? "https://" : "http://") + address + ":" + port + "/" + subUrl.Trim('/') + "/");
_HttpListener.Start(); HttpListener.Start();
return _HttpListener; return HttpListener;
} }
/// <summary> /// <summary>

View File

@ -12,15 +12,12 @@ namespace Milimoe.FunGame.Core.Service
/// <summary> /// <summary>
/// 客户端专用Socket /// 客户端专用Socket
/// </summary> /// </summary>
internal static Socket? Socket => _Socket; internal static Socket? Socket { get; private set; } = null;
/// <summary> /// <summary>
/// 服务器端专用Socket /// 服务器端专用Socket
/// </summary> /// </summary>
internal static Socket? ServerSocket => _ServerSocket; internal static Socket? ServerSocket { get; private set; } = null;
private static Socket? _Socket = null;
private static Socket? _ServerSocket = null;
#endregion #endregion
@ -37,12 +34,12 @@ namespace Milimoe.FunGame.Core.Service
if (maxConnection <= 0) maxConnection = SocketSet.MaxConnection_2C2G; if (maxConnection <= 0) maxConnection = SocketSet.MaxConnection_2C2G;
try try
{ {
_ServerSocket = new(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); ServerSocket = new(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ServerEndPoint = new(IPAddress.Any, port); IPEndPoint ServerEndPoint = new(IPAddress.Any, port);
_ServerSocket.Bind(ServerEndPoint); ServerSocket.Bind(ServerEndPoint);
_ServerSocket.Listen(maxConnection); ServerSocket.Listen(maxConnection);
_ServerSocket.NoDelay = true; ServerSocket.NoDelay = true;
return _ServerSocket; return ServerSocket;
} }
catch catch
{ {
@ -102,15 +99,15 @@ namespace Milimoe.FunGame.Core.Service
if (ClientSocket.Connected) if (ClientSocket.Connected)
{ {
ClientSocket.NoDelay = true; ClientSocket.NoDelay = true;
_Socket = ClientSocket; Socket = ClientSocket;
break; break;
} }
} }
} }
}); });
if (t.Wait(10 * 1000) && (_Socket?.Connected ?? false)) if (t.Wait(10 * 1000) && (Socket?.Connected ?? false))
{ {
return _Socket; return Socket;
} }
else else
{ {
@ -121,7 +118,7 @@ namespace Milimoe.FunGame.Core.Service
} }
catch catch
{ {
_Socket?.Close(); Socket?.Close();
} }
return null; return null;
} }

View File

@ -23,17 +23,14 @@ namespace Milimoe.FunGame.Core.Service
/// </summary> /// </summary>
private class TaskAwaiter : ITaskAwaiter private class TaskAwaiter : ITaskAwaiter
{ {
public bool IsCompleted => _IsCompleted; public bool IsCompleted { get; private set; } = false;
public Exception Exception => _Exception; public Exception Exception { get; private set; } = new();
private delegate void CompletedEvent(); private delegate void CompletedEvent();
private delegate void ErrorEvent(Exception e); private delegate void ErrorEvent(Exception e);
private event CompletedEvent? Completed; private event CompletedEvent? Completed;
private event ErrorEvent? Error; private event ErrorEvent? Error;
private bool _IsCompleted = false;
private Exception _Exception = new();
internal TaskAwaiter(Action action) => Worker(action); internal TaskAwaiter(Action action) => Worker(action);
internal TaskAwaiter(Func<Task> function) => Worker(function); internal TaskAwaiter(Func<Task> function) => Worker(function);
@ -71,12 +68,12 @@ namespace Milimoe.FunGame.Core.Service
try try
{ {
await Task.Run(action); await Task.Run(action);
_IsCompleted = true; IsCompleted = true;
Completed?.Invoke(); Completed?.Invoke();
} }
catch (Exception e) catch (Exception e)
{ {
_Exception = e; Exception = e;
Error?.Invoke(e); Error?.Invoke(e);
} }
}); });
@ -89,12 +86,12 @@ namespace Milimoe.FunGame.Core.Service
try try
{ {
await function(); await function();
_IsCompleted = true; IsCompleted = true;
Completed?.Invoke(); Completed?.Invoke();
} }
catch (Exception e) catch (Exception e)
{ {
_Exception = e; Exception = e;
Error?.Invoke(e); Error?.Invoke(e);
} }
}); });