代码风格优化

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

View File

@ -16,24 +16,17 @@ namespace Milimoe.FunGame.Core.Api.Transmittal
/// <summary>
/// Smtp客户端信息
/// </summary>
public SmtpClientInfo SmtpClientInfo => _SmtpClientInfo;
public SmtpClientInfo SmtpClientInfo { get; private set; }
/// <summary>
/// 上一个邮件发送的结果
/// </summary>
public MailSendResult LastestResult => _LastestResult;
public MailSendResult LastestResult { get; private set; } = MailSendResult.NotSend;
/// <summary>
/// 上一个邮件的发送错误信息(如果发送失败)
/// </summary>
public string ErrorMsg => _ErrorMsg;
/**
*
*/
private readonly SmtpClientInfo _SmtpClientInfo;
private MailSendResult _LastestResult = MailSendResult.NotSend;
private string _ErrorMsg = "";
public string ErrorMsg { get; private set; } = "";
/// <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)
{
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);
}
@ -74,8 +67,9 @@ namespace Milimoe.FunGame.Core.Api.Transmittal
/// <returns></returns>
public MailSendResult Send(MailObject mail)
{
_LastestResult = MailManager.Send(this, mail, out _ErrorMsg);
return _LastestResult;
LastestResult = MailManager.Send(this, mail, out string errorMsg);
if (!string.IsNullOrWhiteSpace(errorMsg)) ErrorMsg = errorMsg;
return LastestResult;
}
private bool _isDisposed = false;

View File

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

View File

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

View File

@ -125,13 +125,13 @@ namespace Milimoe.FunGame.Core.Entity
{
get
{
return _Level >= 1 ? _Level : 1;
return field >= 1 ? field : 1;
}
set
{
int past = _Level;
_Level = Math.Min(Math.Max(1, value), GameplayEquilibriumConstant.MaxLevel);
if (past != _Level)
int past = field;
field = Math.Min(Math.Max(1, value), GameplayEquilibriumConstant.MaxLevel);
if (past != field)
{
OnAttributeChanged();
Recovery();
@ -228,13 +228,13 @@ namespace Milimoe.FunGame.Core.Entity
{
get
{
return _HP < 0 ? 0 : (_HP > MaxHP ? MaxHP : _HP);
return field < 0 ? 0 : (field > MaxHP ? MaxHP : field);
}
set
{
_HP = value;
if (_HP > MaxHP) _HP = MaxHP;
else if (_HP < 0) _HP = 0;
field = value;
if (field > MaxHP) field = MaxHP;
else if (field < 0) field = 0;
}
}
@ -287,13 +287,13 @@ namespace Milimoe.FunGame.Core.Entity
{
get
{
return _MP < 0 ? 0 : (_MP > MaxMP ? MaxMP : _MP);
return field < 0 ? 0 : (field > MaxMP ? MaxMP : field);
}
set
{
_MP = value;
if (_MP > MaxMP) _MP = MaxMP;
else if (_MP < 0) _MP = 0;
field = value;
if (field > MaxMP) field = MaxMP;
else if (field < 0) field = 0;
}
}
@ -304,13 +304,13 @@ namespace Milimoe.FunGame.Core.Entity
{
get
{
return _EP < 0 ? 0 : (_EP > GameplayEquilibriumConstant.MaxEP ? GameplayEquilibriumConstant.MaxEP : _EP);
return field < 0 ? 0 : (field > GameplayEquilibriumConstant.MaxEP ? GameplayEquilibriumConstant.MaxEP : field);
}
set
{
_EP = value;
if (_EP > GameplayEquilibriumConstant.MaxEP) _EP = GameplayEquilibriumConstant.MaxEP;
else if (_EP < 0) _EP = 0;
field = value;
if (field > GameplayEquilibriumConstant.MaxEP) field = GameplayEquilibriumConstant.MaxEP;
else if (field < 0) field = 0;
}
}
@ -450,11 +450,11 @@ namespace Milimoe.FunGame.Core.Entity
{
get
{
return Calculation.PercentageCheck(_PhysicalPenetration);
return Calculation.PercentageCheck(field);
}
set
{
_PhysicalPenetration = Calculation.PercentageCheck(value);
field = Calculation.PercentageCheck(value);
}
}
@ -465,11 +465,11 @@ namespace Milimoe.FunGame.Core.Entity
{
get
{
return Calculation.PercentageCheck(_MagicalPenetration);
return Calculation.PercentageCheck(field);
}
set
{
_MagicalPenetration = Calculation.PercentageCheck(value);
field = Calculation.PercentageCheck(value);
}
}
@ -898,40 +898,6 @@ namespace Milimoe.FunGame.Core.Entity
/// </summary>
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()
{
User = General.UnknownUserInstance;

View File

@ -9,11 +9,24 @@ namespace Milimoe.FunGame.Core.Entity
{
public DateTime? StartTime { 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 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 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)
{
@ -101,6 +114,34 @@ namespace Milimoe.FunGame.Core.Entity
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)
{
UpdateState();

View File

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

View File

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

View File

@ -49,12 +49,12 @@ namespace Milimoe.FunGame.Core.Entity
{
get
{
return Math.Max(0, _Level);
return Math.Max(0, field);
}
set
{
int max = SkillSet.GetSkillMaxLevel(SkillType, GameplayEquilibriumConstant);
_Level = Math.Min(Math.Max(0, value), max);
field = Math.Min(Math.Max(0, value), max);
OnLevelUp();
}
}
@ -101,9 +101,9 @@ namespace Milimoe.FunGame.Core.Entity
[InitOptional]
public int CastRange
{
get => Math.Max(1, CastAnywhere ? (GamingQueue?.Map != null ? GamingQueue.Map.Grids.Count : 999) : _CastRange);
set => _CastRange = Math.Max(1, value);
}
get => Math.Max(1, CastAnywhere ? (GamingQueue?.Map != null ? GamingQueue.Map.Grids.Count : 999) : field);
set => field = Math.Max(1, value);
} = 3;
/// <summary>
/// 可选取自身
@ -151,7 +151,7 @@ namespace Milimoe.FunGame.Core.Entity
/// <see cref="SkillRangeType.Diamond"/> - 菱形。默认的曼哈顿距离正方形<para/>
/// <see cref="SkillRangeType.Circle"/> - 圆形。基于欧几里得距离的圆形<para/>
/// <see cref="SkillRangeType.Square"/> - 正方形<para/>
/// <see cref="SkillRangeType.Line"/> - 施法者与目标之的直线<para/>
/// <see cref="SkillRangeType.Line"/> - 施法者与目标之的直线<para/>
/// <see cref="SkillRangeType.LinePass"/> - 施法者与目标所在的直线,贯穿至地图边缘<para/>
/// <see cref="SkillRangeType.Sector"/> - 扇形<para/>
/// 注意,该属性不影响选取目标的范围。选取目标的范围由 <see cref="Library.Common.Addon.GameMap"/> 决定。
@ -682,15 +682,5 @@ namespace Milimoe.FunGame.Core.Entity
}
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
{
return _customName.Trim() == "" ? User.Username + "的库存" : _customName;
return field.Trim() == "" ? User.Username + "的库存" : field;
}
set
{
_customName = value;
field = value;
}
}
} = "";
/// <summary>
/// 库存属于哪个玩家
@ -60,20 +60,20 @@ namespace Milimoe.FunGame.Core.Entity
{
get
{
if (_character != null)
if (field != null)
{
return _character;
return field;
}
else if (Characters.Count > 0)
{
_character = Characters.First();
return _character;
field = Characters.First();
return field;
}
return Factory.GetCharacter();
}
set
{
_character = value;
field = value;
}
}
@ -87,9 +87,6 @@ namespace Milimoe.FunGame.Core.Entity
/// </summary>
public Dictionary<long, DateTime> Training { get; set; } = [];
private Character? _character;
private string _customName = "";
internal Inventory(User user)
{
User = user;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -6,21 +6,21 @@ namespace Milimoe.FunGame.Core.Model
{
public class RoomList : IEnumerable<Room>
{
private readonly Dictionary<string, Room> _List = [];
private readonly Dictionary<string, List<User>> _UserList = [];
private readonly Dictionary<string, List<User>> _ReadyUserList = [];
private readonly Dictionary<string, Room> _list = [];
private readonly Dictionary<string, List<User>> _userList = [];
private readonly Dictionary<string, List<User>> _readyUserList = [];
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 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;
@ -32,16 +32,16 @@ namespace Milimoe.FunGame.Core.Model
public void Clear()
{
_List.Clear();
_UserList.Clear();
_ReadyUserList.Clear();
_list.Clear();
_userList.Clear();
_readyUserList.Clear();
}
public void AddRoom(Room room)
{
_List.Add(room.Roomid, room);
_UserList.Add(room.Roomid, []);
_ReadyUserList.Add(room.Roomid, []);
_list.Add(room.Roomid, room);
_userList.Add(room.Roomid, []);
_readyUserList.Add(room.Roomid, []);
}
public void AddRooms(List<Room> rooms)
@ -54,9 +54,9 @@ namespace Milimoe.FunGame.Core.Model
public void RemoveRoom(string roomid)
{
_List.Remove(roomid);
_UserList.Remove(roomid);
_ReadyUserList.Remove(roomid);
_list.Remove(roomid);
_userList.Remove(roomid);
_readyUserList.Remove(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)
{

View File

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

View File

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

View File

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