修改架构 (#15)

* 修改架构 第一部分

* update Connect()

* 更新LoginController

* 删除using

* 添加Login事件

* 修改架构 第二部分

* 将ShowMessage封装到底层窗体

* 将LoginController修改为非静态
This commit is contained in:
milimoe 2023-09-04 00:30:52 +08:00 committed by GitHub
parent 55f9b3e004
commit cd149e0cf1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
20 changed files with 1376 additions and 1453 deletions

View File

@ -1,50 +1,193 @@
using Milimoe.FunGame.Core.Library.Common.Event; using Milimoe.FunGame.Core.Api.Transmittal;
using Milimoe.FunGame.Desktop.Library; using Milimoe.FunGame.Core.Api.Utility;
using Milimoe.FunGame.Desktop.Model; using Milimoe.FunGame.Core.Entity;
using Milimoe.FunGame.Core.Library.Common.Event;
using Milimoe.FunGame.Core.Library.Constant;
using Milimoe.FunGame.Core.Library.Exception; using Milimoe.FunGame.Core.Library.Exception;
using Milimoe.FunGame.Core.Controller; using Milimoe.FunGame.Core.Library.SQLScript.Common;
using Milimoe.FunGame.Core.Library.SQLScript.Entity;
using Milimoe.FunGame.Desktop.Library;
using Milimoe.FunGame.Desktop.Library.Component;
using Milimoe.FunGame.Desktop.UI;
namespace Milimoe.FunGame.Desktop.Controller namespace Milimoe.FunGame.Desktop.Controller
{ {
public class LoginController : SocketHandlerController public class LoginController
{ {
private readonly LoginModel LoginModel; private readonly GeneralForm UIForm;
private readonly DataRequest LoginRequest;
private readonly DataRequest ForgetPasswordRequest;
private readonly DataRequest UpdatePasswordRequest;
public LoginController() public LoginController(GeneralForm form)
{ {
LoginModel = new LoginModel(); UIForm = form;
LoginRequest = RunTime.NewLongRunningDataRequest(DataRequestType.RunTime_Login);
ForgetPasswordRequest = RunTime.NewLongRunningDataRequest(DataRequestType.Login_GetFindPasswordVerifyCode);
UpdatePasswordRequest = RunTime.NewLongRunningDataRequest(DataRequestType.Login_UpdatePassword);
} }
public override void Dispose() public void Dispose()
{ {
LoginModel.Dispose(); LoginRequest.Dispose();
ForgetPasswordRequest.Dispose();
UpdatePasswordRequest.Dispose();
} }
public static async Task<bool> LoginAccount(params object[]? objs) public async Task<bool> LoginAccountAsync(string username, string password, string autokey = "")
{ {
bool result = false; bool result = false;
string msg = "";
LoginEventArgs args = new(username, password, autokey);
try try
{ {
LoginEventArgs LoginEventArgs = new(objs); if (OnBeforeLoginEvent(args))
if (RunTime.Login?.OnBeforeLoginEvent(LoginEventArgs) == Core.Library.Constant.EventResult.Fail) return false; {
LoginRequest.AddRequestData("username", username);
result = await LoginModel.LoginAccountAsync(objs); LoginRequest.AddRequestData("password", password);
LoginRequest.AddRequestData("autokey", autokey);
if (result) RunTime.Login?.OnSucceedLoginEvent(LoginEventArgs); await LoginRequest.SendRequestAsync();
else RunTime.Login?.OnFailedLoginEvent(LoginEventArgs); if (LoginRequest.Result == RequestResult.Success)
RunTime.Login?.OnAfterLoginEvent(LoginEventArgs); {
Guid key = LoginRequest.GetResult<Guid>("checkloginkey");
msg = LoginRequest.GetResult<string>("msg") ?? "";
if (msg != "")
{
UIForm.ShowMessage(ShowMessageType.Error, msg);
}
else if (key != Guid.Empty)
{
LoginRequest.AddRequestData("checkloginkey", key);
await LoginRequest.SendRequestAsync();
if (LoginRequest.Result == RequestResult.Success)
{
msg = LoginRequest.GetResult<string>("msg") ?? "";
if (msg != "")
{
UIForm.ShowMessage(ShowMessageType.Error, msg);
}
else
{
User user = LoginRequest.GetResult<User>("user") ?? Factory.GetUser();
if (user.Id != 0)
{
// 创建User对象并返回到Main
RunTime.Main?.UpdateUI(MainInvokeType.SetUser, user);
result = true;
}
}
}
}
}
}
} }
catch (Exception e) catch (Exception e)
{ {
RunTime.WritelnSystemInfo(e.GetErrorInfo()); RunTime.WritelnSystemInfo(e.GetErrorInfo());
} }
if (!result && msg == "")
{
UIForm.ShowMessage(ShowMessageType.Error, "登录失败!");
}
OnAfterLoginEvent(result, args);
return result; return result;
} }
public static string ForgetPassword_CheckVerifyCode(string username, string email, string verifycode = "") => LoginModel.ForgetPassword_CheckVerifyCode(username, email, verifycode); public async Task<string> ForgetPassword_CheckVerifyCodeAsync(string username, string email, string verifycode)
{
string msg = "无法找回您的密码,请稍后再试。";
public static string ForgetPassword_UpdatePassword(string username, string password) => LoginModel.ForgetPassword_UpdatePassword(username, password); try
{
ForgetPasswordRequest.AddRequestData(ForgetVerifyCodes.Column_Username, username);
ForgetPasswordRequest.AddRequestData(ForgetVerifyCodes.Column_Email, email);
if (verifycode.Trim() == "")
{
// 未发送verifycode说明需要系统生成一个验证码
ForgetPasswordRequest.AddRequestData(ForgetVerifyCodes.Column_ForgetVerifyCode, "");
await ForgetPasswordRequest.SendRequestAsync();
if (ForgetPasswordRequest.Result == RequestResult.Success)
{
msg = ForgetPasswordRequest.GetResult<string>("msg") ?? msg;
}
else RunTime.WritelnSystemInfo(ForgetPasswordRequest.Error);
}
else
{
// 发送verifycode需要验证
ForgetPasswordRequest.AddRequestData(ForgetVerifyCodes.Column_ForgetVerifyCode, verifycode);
await ForgetPasswordRequest.SendRequestAsync();
if (ForgetPasswordRequest.Result == RequestResult.Success)
{
msg = ForgetPasswordRequest.GetResult<string>("msg") ?? msg;
}
else RunTime.WritelnSystemInfo(ForgetPasswordRequest.Error);
}
}
catch (Exception e)
{
RunTime.WritelnSystemInfo(e.GetErrorInfo());
}
return msg;
}
public async Task<string> ForgetPassword_UpdatePasswordAsync(string username, string password)
{
string msg = "无法更新您的密码,请稍后再试。";
try
{
UpdatePasswordRequest.AddRequestData(UserQuery.Column_Username, username);
UpdatePasswordRequest.AddRequestData(UserQuery.Column_Password, password.Encrypt(username));
await UpdatePasswordRequest.SendRequestAsync();
if (UpdatePasswordRequest.Result == RequestResult.Success)
{
msg = UpdatePasswordRequest.GetResult<string>("msg") ?? msg;
}
else RunTime.WritelnSystemInfo(UpdatePasswordRequest.Error);
}
catch (Exception e)
{
RunTime.WritelnSystemInfo(e.GetErrorInfo());
}
return msg;
}
private bool OnBeforeLoginEvent(LoginEventArgs LoginEventArgs)
{
if (UIForm.GetType() == typeof(Login))
{
return ((Login)UIForm).OnBeforeLoginEvent(LoginEventArgs) == EventResult.Success;
}
return true;
}
private void OnAfterLoginEvent(bool result, LoginEventArgs LoginEventArgs)
{
try
{
if (UIForm.GetType() == typeof(Login))
{
Login login = (Login)UIForm;
if (result) login.OnSucceedLoginEvent(LoginEventArgs);
else login.OnFailedLoginEvent(LoginEventArgs);
login.OnAfterLoginEvent(LoginEventArgs);
}
else if (UIForm.GetType() == typeof(Main))
{
if (result) ((Main)UIForm).OnSucceedLoginEvent(LoginEventArgs);
}
}
catch (Exception e)
{
RunTime.WritelnSystemInfo(e.GetErrorInfo());
}
}
} }
} }

View File

@ -1,168 +1,278 @@
using Milimoe.FunGame.Core.Controller; using Milimoe.FunGame.Core.Api.Transmittal;
using Milimoe.FunGame.Core.Controller;
using Milimoe.FunGame.Core.Entity; using Milimoe.FunGame.Core.Entity;
using Milimoe.FunGame.Core.Library.Common.Event; using Milimoe.FunGame.Core.Library.Common.Network;
using Milimoe.FunGame.Core.Library.Constant; using Milimoe.FunGame.Core.Library.Constant;
using Milimoe.FunGame.Core.Library.Exception; using Milimoe.FunGame.Core.Library.Exception;
using Milimoe.FunGame.Core.Model;
using Milimoe.FunGame.Desktop.Library; using Milimoe.FunGame.Desktop.Library;
using Milimoe.FunGame.Desktop.Model;
using Milimoe.FunGame.Desktop.UI; using Milimoe.FunGame.Desktop.UI;
namespace Milimoe.FunGame.Desktop.Controller namespace Milimoe.FunGame.Desktop.Controller
{ {
public class MainController : SocketHandlerController public class MainController : SocketHandlerController
{ {
private MainModel MainModel { get; } private readonly Main Main;
private Main Main { get; } private readonly Session Usercfg = RunTime.Session;
private readonly DataRequest ChatRequest;
private readonly DataRequest CreateRoomRequest;
private readonly DataRequest GetRoomPlayerCountRequest;
private readonly DataRequest UpdateRoomRequest;
private readonly DataRequest IntoRoomRequest;
private readonly DataRequest QuitRoomRequest;
private readonly Core.Model.Session Usercfg = RunTime.Session; public MainController(Main main) : base(RunTime.Socket)
public MainController(Main Main)
{ {
this.Main = Main; Main = main;
MainModel = new MainModel(Main); ChatRequest = RunTime.NewLongRunningDataRequest(DataRequestType.Main_Chat);
CreateRoomRequest = RunTime.NewLongRunningDataRequest(DataRequestType.Main_CreateRoom);
GetRoomPlayerCountRequest = RunTime.NewLongRunningDataRequest(DataRequestType.Room_GetRoomPlayerCount);
UpdateRoomRequest = RunTime.NewLongRunningDataRequest(DataRequestType.Main_UpdateRoom);
IntoRoomRequest = RunTime.NewLongRunningDataRequest(DataRequestType.Main_IntoRoom);
QuitRoomRequest = RunTime.NewLongRunningDataRequest(DataRequestType.Main_QuitRoom);
Disposed += MainController_Disposed;
} }
public override void Dispose() #region
public async Task<bool> LogOutAsync()
{ {
MainModel.Dispose(); try
{
// 需要当时登录给的Key发回去确定是账号本人在操作才允许登出
if (Usercfg.LoginKey != Guid.Empty)
{
DataRequest request = RunTime.NewDataRequest(DataRequestType.RunTime_Logout);
request.AddRequestData("loginkey", Usercfg.LoginKey);
await request.SendRequestAsync();
if (request.Result == RequestResult.Success)
{
string msg = "";
Guid key = Guid.Empty;
msg = request.GetResult<string>("msg") ?? "";
key = request.GetResult<Guid>("key");
if (key == Usercfg.LoginKey)
{
Usercfg.LoginKey = Guid.Empty;
Main.UpdateUI(MainInvokeType.LogOut, msg ?? "");
return true;
}
}
}
throw new CanNotLogOutException();
}
catch (Exception e)
{
Main.ShowMessage(ShowMessageType.Error, "无法登出您的账号,请联系服务器管理员。", "登出失败", 5);
Main.GetMessage(e.GetErrorInfo());
}
return false;
} }
public async Task<bool> LogOut() public async Task<bool> IntoRoomAsync(Room room)
{
try
{
string rid = room.Roomid;
IntoRoomRequest.AddRequestData("room", rid);
await IntoRoomRequest.SendRequestAsync();
if (IntoRoomRequest.Result == RequestResult.Success)
{
string roomid = IntoRoomRequest.GetResult<string>("roomid") ?? "";
if (rid == roomid)
{
// 先确认是否是加入的房间,防止服务端返回错误的房间
if (roomid.Trim() != "" && roomid == "-1")
{
Main.GetMessage($"已连接至公共聊天室。");
}
else
{
Usercfg.InRoom = room;
}
return true;
}
}
throw new CanNotIntoRoomException();
}
catch (Exception e)
{
Main.GetMessage(e.GetErrorInfo());
return false;
}
}
public async Task<bool> UpdateRoomAsync()
{ {
bool result = false; bool result = false;
try try
{ {
GeneralEventArgs EventArgs = new(); List<Room> list = new();
if (Main.OnBeforeLogoutEvent(EventArgs) == EventResult.Fail) return result; await UpdateRoomRequest.SendRequestAsync();
if (UpdateRoomRequest.Result == RequestResult.Success)
if (Usercfg.LoginUser.Id == 0) return result;
if (Usercfg.InRoom.Roomid != "-1")
{ {
string roomid = Usercfg.InRoom.Roomid; list = UpdateRoomRequest.GetResult<List<Room>>("roomid") ?? new();
bool isMaster = Usercfg.InRoom.RoomMaster?.Id == Usercfg.LoginUser?.Id; Main.UpdateUI(MainInvokeType.UpdateRoom, list);
await MainModel.QuitRoom(roomid, isMaster);
} }
else throw new CanNotIntoRoomException();
result = await MainModel.LogOut();
if (result) Main.OnSucceedLogoutEvent(EventArgs);
else Main.OnFailedLogoutEvent(EventArgs);
Main.OnAfterLogoutEvent(EventArgs);
} }
catch (Exception e) catch (Exception e)
{ {
Main.GetMessage(e.GetErrorInfo(), TimeType.None); Main.GetMessage(e.GetErrorInfo());
} }
return result; return result;
} }
public async Task<bool> UpdateRoom() public async Task<int> GetRoomPlayerCountAsync(string roomid)
{ {
return await MainModel.UpdateRoom(); try
{
GetRoomPlayerCountRequest.AddRequestData("roomid", roomid);
await GetRoomPlayerCountRequest.SendRequestAsync();
return GetRoomPlayerCountRequest.GetResult<int>("count");
}
catch (Exception e)
{
Main.GetMessage(e.GetErrorInfo());
return 0;
}
} }
public async Task<bool> IntoRoom(Room room) public async Task<bool> QuitRoomAsync(string roomid, bool isMaster)
{ {
bool result = false; bool result = false;
try try
{ {
RoomEventArgs EventArgs = new(room); QuitRoomRequest.AddRequestData("roomid", roomid);
if (Main.OnBeforeIntoRoomEvent(EventArgs) == EventResult.Fail) return result; QuitRoomRequest.AddRequestData("isMaster", isMaster);
await QuitRoomRequest.SendRequestAsync();
result = await MainModel.IntoRoom(room); if (QuitRoomRequest.Result == RequestResult.Success)
{
if (result) Main.OnSucceedIntoRoomEvent(EventArgs); result = QuitRoomRequest.GetResult<bool>("result");
else Main.OnFailedIntoRoomEvent(EventArgs); if (result)
Main.OnAfterIntoRoomEvent(EventArgs); {
Usercfg.InRoom = General.HallInstance;
return result;
}
}
throw new CanNotIntoRoomException();
} }
catch (Exception e) catch (Exception e)
{ {
Main.GetMessage(e.GetErrorInfo(), TimeType.None); Main.GetMessage(e.GetErrorInfo());
}
return result; return result;
} }
}
public async Task<bool> QuitRoom(Room room, bool isMaster) public async Task<string> CreateRoomAsync(string RoomType, string Password = "")
{ {
bool result = false; string roomid = "-1";
string roomid = room.Roomid;
try try
{ {
RoomEventArgs EventArgs = new(room); CreateRoomRequest.AddRequestData("roomtype", RoomType);
if (Main.OnBeforeQuitRoomEvent(EventArgs) == EventResult.Fail) return result; CreateRoomRequest.AddRequestData("user", Usercfg.LoginUser);
CreateRoomRequest.AddRequestData("password", Password);
result = await MainModel.QuitRoom(roomid, isMaster); await CreateRoomRequest.SendRequestAsync();
if (CreateRoomRequest.Result == RequestResult.Success)
if (result) Main.OnSucceedQuitRoomEvent(EventArgs); {
else Main.OnFailedQuitRoomEvent(EventArgs); roomid = CreateRoomRequest.GetResult<string>("roomid") ?? "-1";
Main.OnAfterQuitRoomEvent(EventArgs); }
} }
catch (Exception e) catch (Exception e)
{ {
Main.GetMessage(e.GetErrorInfo(), TimeType.None); Main.GetMessage(e.GetErrorInfo());
} }
return result; return roomid;
} }
public async Task<string> CreateRoom(string RoomType, string Password = "") public async Task<bool> ChatAsync(string msg)
{ {
string result = "";
try try
{ {
RoomEventArgs EventArgs = new(RoomType, Password); ChatRequest.AddRequestData("msg", msg);
if (Main.OnBeforeCreateRoomEvent(EventArgs) == EventResult.Fail) return result; await ChatRequest.SendRequestAsync();
if (ChatRequest.Result == RequestResult.Success)
result = await MainModel.CreateRoom(RoomType, Password); {
return true;
if (result.Trim() != "") Main.OnSucceedCreateRoomEvent(EventArgs); }
else Main.OnFailedCreateRoomEvent(EventArgs); throw new CanNotSendTalkException();
Main.OnAfterCreateRoomEvent(EventArgs);
} }
catch (Exception e) catch (Exception e)
{ {
Main.GetMessage(e.GetErrorInfo(), TimeType.None); Main.GetMessage(e.GetErrorInfo());
return false;
}
} }
return result; public override void SocketHandler(SocketObject SocketObject)
}
public async Task<int> GetRoomPlayerCount(string roomid)
{ {
return await MainModel.GetRoomPlayerCount(roomid);
}
public bool Chat(string msg)
{
bool result = false;
try try
{ {
SendTalkEventArgs EventArgs = new(msg); if (SocketObject.SocketType == SocketMessageType.HeartBeat)
if (Main.OnBeforeSendTalkEvent(EventArgs) == EventResult.Fail) return result;
if (msg.Trim() != "")
{ {
result = MainModel.Chat(msg); // 心跳包单独处理
if ((RunTime.Socket?.Connected ?? false) && Usercfg.LoginUser.Id != 0)
Main.UpdateUI(MainInvokeType.SetGreenAndPing);
}
else if (SocketObject.SocketType == SocketMessageType.ForceLogout)
{
// 服务器强制下线登录
Guid key = Guid.Empty;
string msg = "";
if (SocketObject.Length > 0) key = SocketObject.GetParam<Guid>(0);
if (SocketObject.Length > 1) msg = SocketObject.GetParam<string>(1) ?? "";
if (key == Usercfg.LoginKey)
{
Usercfg.LoginKey = Guid.Empty;
Main.UpdateUI(MainInvokeType.LogOut, msg ?? "");
}
}
else if (SocketObject.SocketType == SocketMessageType.Chat)
{
// 收到房间聊天信息
string user = "", msg = "";
if (SocketObject.Length > 0) user = SocketObject.GetParam<string>(0) ?? "";
if (SocketObject.Length > 1) msg = SocketObject.GetParam<string>(1) ?? "";
if (user != Usercfg.LoginUserName)
{
Main.GetMessage(msg, TimeType.None);
}
}
else if (SocketObject.SocketType == SocketMessageType.UpdateRoomMaster)
{
// 收到房间更换房主的信息
User user = General.UnknownUserInstance;
Room room = General.HallInstance;
if (SocketObject.Length > 0) user = SocketObject.GetParam<User>(0) ?? General.UnknownUserInstance;
if (SocketObject.Length > 1) room = SocketObject.GetParam<Room>(1) ?? General.HallInstance;
if (room.Roomid != "-1" && room.Roomid == Usercfg.InRoom.Roomid) Main.UpdateUI(MainInvokeType.UpdateRoomMaster, room);
} }
if (result) Main.OnSucceedSendTalkEvent(EventArgs);
else Main.OnFailedSendTalkEvent(EventArgs);
Main.OnAfterSendTalkEvent(EventArgs);
} }
catch (Exception e) catch (Exception e)
{ {
Main.GetMessage(e.GetErrorInfo(), TimeType.None); RunTime.Controller?.Error(e);
}
} }
return result; #endregion
#region
private void MainController_Disposed()
{
ChatRequest.Dispose();
CreateRoomRequest.Dispose();
GetRoomPlayerCountRequest.Dispose();
UpdateRoomRequest.Dispose();
IntoRoomRequest.Dispose();
QuitRoomRequest.Dispose();
} }
#endregion
} }
} }

View File

@ -1,39 +1,60 @@
using Milimoe.FunGame.Desktop.Library; using Milimoe.FunGame.Desktop.Library;
using Milimoe.FunGame.Desktop.Model;
using Milimoe.FunGame.Core.Library.Constant; using Milimoe.FunGame.Core.Library.Constant;
using Milimoe.FunGame.Desktop.UI; using Milimoe.FunGame.Desktop.UI;
using Milimoe.FunGame.Core.Library.Exception; using Milimoe.FunGame.Core.Library.Exception;
using Milimoe.FunGame.Core.Library.Common.Event; using Milimoe.FunGame.Core.Library.Common.Event;
using Milimoe.FunGame.Core.Controller; using Milimoe.FunGame.Core.Api.Utility;
using Milimoe.FunGame.Desktop.Library.Component;
using Milimoe.FunGame.Core.Api.Transmittal;
namespace Milimoe.FunGame.Desktop.Controller namespace Milimoe.FunGame.Desktop.Controller
{ {
public class RegisterController : SocketHandlerController public class RegisterController
{ {
private readonly Register Register; private readonly Register Register;
private readonly RegisterModel RegModel;
public RegisterController(Register reg) public RegisterController(Register reg)
{ {
Register = reg; Register = reg;
RegModel = new RegisterModel();
} }
public override void Dispose() public async Task<bool> RegAsync(string username = "", string password = "", string email = "")
{
RegModel.Dispose();
}
public async Task<bool> Reg(params object[]? objs)
{ {
bool result = false; bool result = false;
try try
{ {
RegisterEventArgs RegEventArgs = new (objs); password = password.Encrypt(username);
RegisterEventArgs RegEventArgs = new(username, password, email);
if (Register.OnBeforeRegEvent(RegEventArgs) == EventResult.Fail) return false; if (Register.OnBeforeRegEvent(RegEventArgs) == EventResult.Fail) return false;
result = await RegModel.Reg(objs); DataRequest request = RunTime.NewDataRequest(DataRequestType.Reg_GetRegVerifyCode);
request.AddRequestData("username", username);
request.AddRequestData("password", password);
request.AddRequestData("email", email);
request.AddRequestData("verifycode", "");
await request.SendRequestAsync();
if (request.Result == RequestResult.Success)
{
RegInvokeType InvokeType = request.GetResult<RegInvokeType>("type");
while (true)
{
string verifycode = ShowMessage.InputMessageCancel("请输入注册邮件中的6位数字验证码", "注册验证码", out MessageResult cancel);
if (cancel != MessageResult.Cancel)
{
request.AddRequestData("verifycode", verifycode);
await request.SendRequestAsync();
if (request.Result == RequestResult.Success)
{
bool success = request.GetResult<bool>("success");
string msg = request.GetResult<string>("msg") ?? "";
if (msg != "") ShowMessage.Message(msg, "注册结果");
if (success) return success;
}
}
else break;
}
}
if (result) Register.OnSucceedRegEvent(RegEventArgs); if (result) Register.OnSucceedRegEvent(RegEventArgs);
else Register.OnFailedRegEvent(RegEventArgs); else Register.OnFailedRegEvent(RegEventArgs);

View File

@ -1,115 +1,181 @@
using Milimoe.FunGame.Core.Api.Transmittal; using Milimoe.FunGame.Core.Api.Transmittal;
using Milimoe.FunGame.Core.Library.Common.Event; using Milimoe.FunGame.Core.Library.Common.Event;
using Milimoe.FunGame.Core.Library.Common.Network;
using Milimoe.FunGame.Core.Library.Constant; using Milimoe.FunGame.Core.Library.Constant;
using Milimoe.FunGame.Core.Library.Exception; using Milimoe.FunGame.Core.Library.Exception;
using Milimoe.FunGame.Desktop.Library; using Milimoe.FunGame.Desktop.Library;
using Milimoe.FunGame.Desktop.Model;
using Milimoe.FunGame.Desktop.UI; using Milimoe.FunGame.Desktop.UI;
namespace Milimoe.FunGame.Desktop.Controller namespace Milimoe.FunGame.Desktop.Controller
{ {
public class RunTimeController : Core.Controller.RunTimeController public class RunTimeController : Core.Controller.RunTimeController
{ {
public override bool Connected => RunTimeModel.Connected; private readonly Main Main;
private readonly Core.Model.Session Usercfg = RunTime.Session;
private readonly LoginController LoginController;
private RunTimeModel RunTimeModel { get; } public RunTimeController(Main main)
private Main Main { get; }
public RunTimeController(Main Main)
{ {
this.Main = Main; Main = main;
RunTimeModel = new RunTimeModel(Main); LoginController = new(Main);
} }
public override async Task<ConnectResult> Connect() public void Dispose()
{ {
ConnectResult result = ConnectResult.ConnectFailed;
try
{
ConnectEventArgs EventArgs = new(RunTime.Session.Server_IP, RunTime.Session.Server_Port);
if (Main.OnBeforeConnectEvent(EventArgs) == EventResult.Fail) return ConnectResult.ConnectFailed;
result = await RunTimeModel.Connect();
if (result == ConnectResult.Success) Main.OnSucceedConnectEvent(EventArgs);
else Main.OnFailedConnectEvent(EventArgs);
Main.OnAfterConnectEvent(EventArgs);
}
catch (Exception e)
{
Main.GetMessage(e.GetErrorInfo(), TimeType.None);
}
return result;
}
public override bool Disconnect()
{
bool result = false;
try
{
if (Main.OnBeforeDisconnectEvent(new GeneralEventArgs()) == EventResult.Fail) return result;
result = RunTimeModel.Disconnect();
if (result) Main.OnSucceedDisconnectEvent(new GeneralEventArgs());
else Main.OnFailedDisconnectEvent(new GeneralEventArgs());
Main.OnAfterDisconnectEvent(new GeneralEventArgs());
}
catch (Exception e)
{
Main.GetMessage(e.GetErrorInfo(), TimeType.None);
}
return result;
}
public override bool Close(Exception? e = null)
{
bool result;
if (Connected) Disconnect();
if (e != null)
{
RunTimeModel.Error(e);
result = true;
}
else result = RunTimeModel.Close();
return result;
}
public override bool Error(Exception e)
{
return Close(e);
}
public override async Task AutoLogin(string Username, string Password, string AutoKey)
{
try
{
LoginController LoginController = new();
await LoginController.LoginAccount(Username, Password, AutoKey);
LoginController.Dispose(); LoginController.Dispose();
} }
catch (Exception e)
{
Main.GetMessage(e.GetErrorInfo(), TimeType.None);
}
}
public override void WritelnSystemInfo(string msg) public override void WritelnSystemInfo(string msg)
{ {
Main?.GetMessage(msg); Main?.GetMessage(msg);
} }
public override DataRequest NewDataRequest(DataRequestType RequestType) public override void Error(Exception e)
{ {
DataRequest? request = RunTimeModel?.NewDataRequest(RequestType); Main.GetMessage(e.GetErrorInfo(), TimeType.None);
return request is null ? throw new ConnectFailedException() : request; Main.UpdateUI(MainInvokeType.Disconnected);
Main.OnFailedConnectEvent(new ConnectEventArgs(RunTime.Session.Server_IP, RunTime.Session.Server_Port));
Close();
}
public override ConnectResult Connect()
{
if (RunTime.Session.Server_IP == "" || RunTime.Session.Server_Port <= 0)
{
(RunTime.Session.Server_IP, RunTime.Session.Server_Port) = GetServerAddress();
if (RunTime.Session.Server_IP == "" || RunTime.Session.Server_Port <= 0)
{
Main.ShowMessage(ShowMessageType.Error, "查找可用的服务器失败!");
return ConnectResult.FindServerFailed;
}
}
try
{
if (Config.FunGame_isRetrying)
{
Main.GetMessage("正在连接服务器,请耐心等待。");
Config.FunGame_isRetrying = false;
return ConnectResult.CanNotConnect;
}
if (!Config.FunGame_isConnected)
{
Main.CurrentRetryTimes++;
if (Main.CurrentRetryTimes == 0) Main.GetMessage("开始连接服务器...", TimeType.General);
else Main.GetMessage("第" + Main.CurrentRetryTimes + "次重试连接服务器...");
// 超过重连次数上限
if (Main.CurrentRetryTimes + 1 > Main.MaxRetryTimes)
{
throw new CanNotConnectException();
}
// 与服务器建立连接
Socket?.Close();
Config.FunGame_isRetrying = true;
_Socket = Socket.Connect(RunTime.Session.Server_IP, RunTime.Session.Server_Port);
if (Socket != null && Socket.Connected)
{
// 设置可复用Socket
RunTime.Socket = Socket;
// 发送连接请求
DataRequest request = RunTime.NewDataRequest(DataRequestType.RunTime_Connect);
request.SendRequest();
if (request.Result == RequestResult.Success)
{
bool success = request.GetResult<bool>("success");
string msg = request.GetResult<string>("msg") ?? "";
if (!success)
{
// 服务器拒绝连接
if (msg != "")
{
Main.GetMessage(msg);
Main.ShowMessage(ShowMessageType.Error, msg);
}
return ConnectResult.ConnectFailed;
}
else
{
if (msg != "")
{
Main.GetMessage(msg);
}
Guid token = request.GetResult<Guid>("token");
string servername = request.GetResult<string>("servername") ?? "";
string notice = request.GetResult<string>("notice") ?? "";
Config.FunGame_ServerName = servername;
Config.FunGame_Notice = notice;
Socket!.Token = token;
Usercfg.SocketToken = token;
Main.GetMessage($"已连接服务器:{servername}。\n\n********** 服务器公告 **********\n\n{notice}\n\n");
// 设置等待登录的黄灯
Main.UpdateUI(MainInvokeType.WaitLoginAndSetYellow);
Main.GetMessage("连接服务器成功请登录账号以体验FunGame。");
Main.UpdateUI(MainInvokeType.Connected);
StartReceiving();
Task.Run(() =>
{
while (true)
{
if (_IsReceiving)
{
break;
}
}
});
return ConnectResult.Success;
}
}
Config.FunGame_isRetrying = false;
Socket.Close();
return ConnectResult.ConnectFailed;
}
Socket?.Close();
Config.FunGame_isRetrying = false;
throw new CanNotConnectException();
}
else
{
Main.GetMessage("已连接至服务器,请勿重复连接。");
return ConnectResult.CanNotConnect;
}
}
catch (Exception e)
{
Main.GetMessage(e.GetErrorInfo(), TimeType.None);
Main.UpdateUI(MainInvokeType.SetRed);
Config.FunGame_isRetrying = false;
return ConnectResult.ConnectFailed;
}
}
public override void AutoLogin(string Username, string Password, string AutoKey)
{
try
{
Core.Api.Utility.TaskUtility.StartAndAwaitTask(async () => await LoginController.LoginAccountAsync(Username, Password, AutoKey));
}
catch (Exception e)
{
Main.GetMessage(e.GetErrorInfo(), TimeType.None);
}
}
protected override void SocketHandler_Disconnect(SocketObject ServerMessage)
{
string msg = "";
if (ServerMessage.Parameters.Length > 0) msg = ServerMessage.GetParam<string>(0)!;
Main.GetMessage(msg);
Main.UpdateUI(MainInvokeType.Disconnect);
Close();
Main.OnSucceedDisconnectEvent(new GeneralEventArgs());
Main.OnAfterDisconnectEvent(new GeneralEventArgs());
}
protected override void SocketHandler_HeartBeat(SocketObject ServerMessage)
{
if (Socket != null && Socket.Connected && Usercfg.LoginUser.Id != 0)
{
Main.UpdateUI(MainInvokeType.SetGreenAndPing);
}
} }
} }
} }

View File

@ -1,4 +1,5 @@
using Milimoe.FunGame.Core.Api.Utility; using Milimoe.FunGame.Core.Api.Utility;
using Milimoe.FunGame.Core.Library.Constant;
using Milimoe.FunGame.Desktop.UI; using Milimoe.FunGame.Desktop.UI;
using Milimoe.FunGame.Desktop.Utility; using Milimoe.FunGame.Desktop.Utility;
@ -13,6 +14,99 @@ namespace Milimoe.FunGame.Desktop.Library.Component
InitializeComponent(); InitializeComponent();
} }
/// <summary>
/// 提供公共方法给Controller发送消息弹窗这样可以防止跨线程时弹窗不在最上层
/// </summary>
/// <param name="type"></param>
/// <param name="msg"></param>
/// <param name="title"></param>
/// <param name="autoclose"></param>
public MessageResult ShowMessage(ShowMessageType type, string msg, string title = "", int autoclose = 0)
{
MessageResult result = MessageResult.OK;
void action()
{
if (msg == "") return;
switch (type)
{
case ShowMessageType.General:
result = Library.Component.ShowMessage.Message(msg, title, autoclose);
break;
case ShowMessageType.Tip:
result = Library.Component.ShowMessage.TipMessage(msg, "", autoclose);
break;
case ShowMessageType.Warning:
result = Library.Component.ShowMessage.WarningMessage(msg, "", autoclose);
break;
case ShowMessageType.Error:
result = Library.Component.ShowMessage.ErrorMessage(msg, "", autoclose);
break;
case ShowMessageType.YesNo:
result = Library.Component.ShowMessage.YesNoMessage(msg, title);
break;
case ShowMessageType.OKCancel:
result = Library.Component.ShowMessage.OKCancelMessage(msg, title);
break;
case ShowMessageType.RetryCancel:
result = Library.Component.ShowMessage.RetryCancelMessage(msg, title);
break;
default:
break;
}
};
InvokeUpdateUI(action);
return result;
}
/// <summary>
/// 提供公共方法给Controller发送消息弹窗这样可以防止跨线程时弹窗不在最上层
/// </summary>
/// <param name="type"></param>
/// <param name="msg"></param>
/// <param name="title"></param>
/// <param name="autoclose"></param>
public string ShowInputMessage(string msg, string title)
{
string input = "";
void action()
{
if (msg == "") return;
input = Component.ShowMessage.InputMessage(msg, title);
};
InvokeUpdateUI(action);
return input;
}
/// <summary>
/// 提供公共方法给Controller发送消息弹窗这样可以防止跨线程时弹窗不在最上层<para/>
/// 支持返回点击的按钮,用于判断是否取消输入
/// </summary>
/// <param name="type"></param>
/// <param name="msg"></param>
/// <param name="title"></param>
/// <param name="autoclose"></param>
public string ShowInputMessageCancel(string msg, string title, out MessageResult result)
{
MessageResult resultThisMethod = MessageResult.Cancel;
string input = "";
void action()
{
if (msg == "") return;
input = Component.ShowMessage.InputMessageCancel(msg, title, out MessageResult resultShowMessage);
resultThisMethod = resultShowMessage;
};
InvokeUpdateUI(action);
result = resultThisMethod;
return input;
}
/// <summary> /// <summary>
/// 绑定事件,子类需要重写 /// 绑定事件,子类需要重写
/// </summary> /// </summary>
@ -105,5 +199,16 @@ namespace Milimoe.FunGame.Desktop.Library.Component
{ {
BindEvent(); BindEvent();
} }
/// <summary>
/// 委托更新UI
/// </summary>
/// <param name="action"></param>
protected virtual void InvokeUpdateUI(Action action)
{
if (InvokeRequired) Invoke(action);
else action();
}
} }
} }

View File

@ -158,23 +158,23 @@ namespace Milimoe.FunGame.Desktop.Library.Component
return result; return result;
} }
public static MessageResult TipMessage(string msg, string? title = null, int autoclose = 0) public static MessageResult TipMessage(string msg, string title = "", int autoclose = 0)
{ {
object[] objs = { title ?? TITLE_TIP, msg, autoclose, MessageButtonType.OK, BUTTON_OK }; object[] objs = { title == "" ? TITLE_TIP : title, msg, autoclose, MessageButtonType.OK, BUTTON_OK };
MessageResult result = new ShowMessage(objs).MessageResult; MessageResult result = new ShowMessage(objs).MessageResult;
return result; return result;
} }
public static MessageResult WarningMessage(string msg, string? title = null, int autoclose = 0) public static MessageResult WarningMessage(string msg, string title = "", int autoclose = 0)
{ {
object[] objs = { title ?? TITLE_WARNING, msg, autoclose, MessageButtonType.OK, BUTTON_OK }; object[] objs = { title == "" ? TITLE_WARNING : title, msg, autoclose, MessageButtonType.OK, BUTTON_OK };
MessageResult result = new ShowMessage(objs).MessageResult; MessageResult result = new ShowMessage(objs).MessageResult;
return result; return result;
} }
public static MessageResult ErrorMessage(string msg, string? title = null, int autoclose = 0) public static MessageResult ErrorMessage(string msg, string title = "", int autoclose = 0)
{ {
object[] objs = { title ?? TITLE_ERROR, msg, autoclose, MessageButtonType.OK, BUTTON_OK }; object[] objs = { title == "" ? TITLE_ERROR : title, msg, autoclose, MessageButtonType.OK, BUTTON_OK };
MessageResult result = new ShowMessage(objs).MessageResult; MessageResult result = new ShowMessage(objs).MessageResult;
return result; return result;
} }

View File

@ -1,5 +1,4 @@
using System.Text; using Milimoe.FunGame.Core.Library.Constant;
using Milimoe.FunGame.Core.Library.Constant;
namespace Milimoe.FunGame.Desktop.Library namespace Milimoe.FunGame.Desktop.Library
{ {
@ -61,4 +60,17 @@ namespace Milimoe.FunGame.Desktop.Library
FunGame_AutoRetryOff FunGame_AutoRetryOff
}; };
} }
public enum ShowMessageType
{
General,
Tip,
Warning,
Error,
YesNo,
OKCancel,
RetryCancel,
Input,
InputCancel
}
} }

View File

@ -32,5 +32,11 @@ namespace Milimoe.FunGame.Desktop.Library
DataRequest? request = Controller?.NewDataRequest(RequestType); DataRequest? request = Controller?.NewDataRequest(RequestType);
return request is null ? throw new ConnectFailedException() : request; return request is null ? throw new ConnectFailedException() : request;
} }
public static DataRequest NewLongRunningDataRequest(DataRequestType RequestType)
{
DataRequest? request = Controller?.NewLongRunningDataRequest(RequestType);
return request is null ? throw new ConnectFailedException() : request;
}
} }
} }

View File

@ -1,205 +0,0 @@
using Milimoe.FunGame.Core.Api.Transmittal;
using Milimoe.FunGame.Core.Api.Utility;
using Milimoe.FunGame.Core.Entity;
using Milimoe.FunGame.Core.Library.Common.Network;
using Milimoe.FunGame.Core.Library.Constant;
using Milimoe.FunGame.Core.Library.Exception;
using Milimoe.FunGame.Core.Library.SQLScript.Common;
using Milimoe.FunGame.Core.Library.SQLScript.Entity;
using Milimoe.FunGame.Core.Model;
using Milimoe.FunGame.Desktop.Library.Component;
using RunTime = Milimoe.FunGame.Desktop.Library.RunTime;
namespace Milimoe.FunGame.Desktop.Model
{
/// <summary>
/// 请不要越过Controller直接调用Model中的方法。
/// </summary>
public class LoginModel : SocketHandlerModel
{
private static new SocketObject Work;
private static new bool Working = false;
public LoginModel() : base(RunTime.Socket)
{
}
public override void SocketHandler(SocketObject SocketObject)
{
try
{
if (SocketObject.SocketType == SocketMessageType.RunTime_Login || SocketObject.SocketType == SocketMessageType.RunTime_CheckLogin)
{
Work = SocketObject;
Working = false;
}
}
catch (Exception e)
{
RunTime.WritelnSystemInfo(e.GetErrorInfo());
}
}
public static async Task<bool> LoginAccountAsync(params object[]? objs)
{
try
{
Socket? Socket = RunTime.Socket;
if (Socket != null && objs != null)
{
string username = "";
string password = "";
string autokey = "";
if (objs.Length > 0) username = (string)objs[0];
if (objs.Length > 1) password = (string)objs[1];
if (objs.Length > 2) autokey = (string)objs[2];
password = password.Encrypt(username);
SetWorking();
if (Socket.Send(SocketMessageType.RunTime_Login, username, password, autokey) == SocketResult.Success)
{
string ErrorMsg = "";
Guid CheckLoginKey = Guid.Empty;
(CheckLoginKey, ErrorMsg) = await Task.Factory.StartNew(GetCheckLoginKeyAsync);
if (ErrorMsg != null && ErrorMsg.Trim() != "")
{
ShowMessage.ErrorMessage(ErrorMsg, "登录失败");
return false;
}
SetWorking();
if (Socket.Send(SocketMessageType.RunTime_CheckLogin, CheckLoginKey) == SocketResult.Success)
{
User user = await Task.Factory.StartNew(GetLoginUserAsync);
// 创建User对象并返回到Main
RunTime.Main?.UpdateUI(MainInvokeType.SetUser, user);
return true;
}
}
}
}
catch (Exception e)
{
RunTime.WritelnSystemInfo(e.GetErrorInfo());
}
return false;
}
public static (Guid, string) GetCheckLoginKeyAsync()
{
Guid key = Guid.Empty;
string? msg = "";
try
{
WaitForWorkDone();
// 返回一个确认登录的Key
if (Work.Length > 0) key = Work.GetParam<Guid>(0);
if (Work.Length > 1) msg = Work.GetParam<string>(1);
if (key != Guid.Empty)
{
RunTime.Session.LoginKey = key;
}
}
catch (Exception e)
{
RunTime.WritelnSystemInfo(e.GetErrorInfo());
}
msg ??= "";
return (key, msg);
}
public static string ForgetPassword_CheckVerifyCode(string username, string email, string verifycode)
{
string msg = "无法找回您的密码,请稍后再试。";
try
{
DataRequest request = RunTime.NewDataRequest(DataRequestType.Login_GetFindPasswordVerifyCode);
request.AddRequestData(ForgetVerifyCodes.Column_Username, username);
request.AddRequestData(ForgetVerifyCodes.Column_Email, email);
if (verifycode.Trim() == "")
{
// 未发送verifycode说明需要系统生成一个验证码
request.AddRequestData(ForgetVerifyCodes.Column_ForgetVerifyCode, "");
request.SendRequest();
if (request.Result == RequestResult.Success)
{
msg = request.GetResult<string>("msg") ?? msg;
}
else RunTime.WritelnSystemInfo(request.Error);
}
else
{
// 发送verifycode需要验证
request.AddRequestData(ForgetVerifyCodes.Column_ForgetVerifyCode, verifycode);
request.SendRequest();
if (request.Result == RequestResult.Success)
{
msg = request.GetResult<string>("msg") ?? msg;
}
else RunTime.WritelnSystemInfo(request.Error);
}
}
catch (Exception e)
{
RunTime.WritelnSystemInfo(e.GetErrorInfo());
}
return msg;
}
public static string ForgetPassword_UpdatePassword(string username, string password)
{
string msg = "无法更新您的密码,请稍后再试。";
try
{
DataRequest request = RunTime.NewDataRequest(DataRequestType.Login_UpdatePassword);
request.AddRequestData(UserQuery.Column_Username, username);
request.AddRequestData(UserQuery.Column_Password, password.Encrypt(username));
request.SendRequest();
if (request.Result == RequestResult.Success)
{
msg = request.GetResult<string>("msg") ?? msg;
}
else RunTime.WritelnSystemInfo(request.Error);
}
catch (Exception e)
{
RunTime.WritelnSystemInfo(e.GetErrorInfo());
}
return msg;
}
private static User GetLoginUserAsync()
{
User user = General.UnknownUserInstance;
try
{
WaitForWorkDone();
// 返回构造User对象的DataSet
if (Work.Length > 0) user = Work.GetParam<User>(0) ?? General.UnknownUserInstance;
}
catch (Exception e)
{
RunTime.WritelnSystemInfo(e.GetErrorInfo());
}
return user;
}
private static new void SetWorking()
{
Working = true;
Work = default;
}
private static new void WaitForWorkDone()
{
while (true)
{
if (!Working) break;
}
}
}
}

View File

@ -1,344 +0,0 @@
using Milimoe.FunGame.Core.Entity;
using Milimoe.FunGame.Core.Library.Common.Network;
using Milimoe.FunGame.Core.Library.Constant;
using Milimoe.FunGame.Core.Library.Exception;
using Milimoe.FunGame.Core.Model;
using Milimoe.FunGame.Desktop.Library.Component;
using Milimoe.FunGame.Desktop.UI;
using RunTime = Milimoe.FunGame.Desktop.Library.RunTime;
namespace Milimoe.FunGame.Desktop.Model
{
public class MainModel : SocketHandlerModel
{
private readonly Main Main;
private readonly Session Usercfg = RunTime.Session;
public MainModel(Main main) : base(RunTime.Socket)
{
Main = main;
}
#region
public async Task<bool> LogOut()
{
try
{
// 需要当时登录给的Key发回去确定是账号本人在操作才允许登出
if (Usercfg.LoginKey != Guid.Empty)
{
SetWorking();
if (RunTime.Socket?.Send(SocketMessageType.RunTime_Logout, Usercfg.LoginKey) == SocketResult.Success)
{
string msg = "";
Guid key = Guid.Empty;
(msg, key) = await Task.Factory.StartNew(SocketHandler_LogOut);
if (key == Usercfg.LoginKey)
{
Usercfg.LoginKey = Guid.Empty;
Main.UpdateUI(MainInvokeType.LogOut, msg ?? "");
return true;
}
}
}
throw new CanNotLogOutException();
}
catch (Exception e)
{
ShowMessage.ErrorMessage("无法登出您的账号,请联系服务器管理员。", "登出失败", 5);
Main.GetMessage(e.GetErrorInfo());
}
return false;
}
public async Task<bool> IntoRoom(Room room)
{
try
{
SetWorking();
if (RunTime.Socket?.Send(SocketMessageType.Main_IntoRoom, room.Roomid) == SocketResult.Success)
{
string roomid = await Task.Factory.StartNew(SocketHandler_IntoRoom);
if (roomid.Trim() != "" && roomid == "-1")
{
Main.GetMessage($"已连接至公共聊天室。");
}
else
{
Usercfg.InRoom = room;
}
return true;
}
throw new CanNotIntoRoomException();
}
catch (Exception e)
{
Main.GetMessage(e.GetErrorInfo());
return false;
}
}
public async Task<bool> UpdateRoom()
{
try
{
SetWorking();
if (RunTime.Socket?.Send(SocketMessageType.Main_UpdateRoom) == SocketResult.Success)
{
List<Room> list = await Task.Factory.StartNew(SocketHandler_UpdateRoom);
Main.UpdateUI(MainInvokeType.UpdateRoom, list);
return true;
}
throw new GetRoomListException();
}
catch (Exception e)
{
Main.GetMessage(e.GetErrorInfo());
return false;
}
}
public async Task<int> GetRoomPlayerCount(string roomid)
{
try
{
SetWorking();
if (RunTime.Socket?.Send(SocketMessageType.Room_GetRoomPlayerCount, roomid) == SocketResult.Success)
{
return await Task.Factory.StartNew(SocketHandler_GetRoomPlayerCount);
}
return 0;
}
catch (Exception e)
{
Main.GetMessage(e.GetErrorInfo());
return 0;
}
}
public async Task<bool> QuitRoom(string roomid, bool isMaster)
{
bool result = false;
try
{
SetWorking();
if (RunTime.Socket?.Send(SocketMessageType.Main_QuitRoom, roomid, isMaster) == SocketResult.Success)
{
result = await Task.Factory.StartNew(SocketHandler_QuitRoom);
if (result)
{
Usercfg.InRoom = General.HallInstance;
return result;
}
}
throw new QuitRoomException();
}
catch (Exception e)
{
Main.GetMessage(e.GetErrorInfo());
return result;
}
}
public async Task<string> CreateRoom(string RoomType, string Password = "")
{
try
{
SetWorking();
if (RunTime.Socket?.Send(SocketMessageType.Main_CreateRoom, RoomType, Usercfg.LoginUser.Id, Password) == SocketResult.Success)
{
string roomid = await Task.Factory.StartNew(SocketHandler_CreateRoom);
if (roomid.Trim() != "")
{
return roomid;
}
}
throw new CreateRoomException();
}
catch (Exception e)
{
Main.GetMessage(e.GetErrorInfo());
return "";
}
}
public bool Chat(string msg)
{
try
{
if (RunTime.Socket?.Send(SocketMessageType.Main_Chat, msg) == SocketResult.Success)
{
return true;
}
throw new CanNotSendTalkException();
}
catch (Exception e)
{
Main.GetMessage(e.GetErrorInfo());
return false;
}
}
public override void SocketHandler(SocketObject SocketObject)
{
try
{
// 定义接收的通信类型
SocketMessageType[] SocketMessageTypes = new SocketMessageType[] { SocketMessageType.Main_GetNotice, SocketMessageType.RunTime_Logout, SocketMessageType.Main_IntoRoom, SocketMessageType.Main_QuitRoom,
SocketMessageType.Main_Chat, SocketMessageType.Main_UpdateRoom, SocketMessageType.Main_CreateRoom };
if (SocketObject.SocketType == SocketMessageType.RunTime_HeartBeat)
{
// 心跳包单独处理
if ((RunTime.Socket?.Connected ?? false) && Usercfg.LoginUser.Id != 0)
Main.UpdateUI(MainInvokeType.SetGreenAndPing);
}
else if (SocketObject.SocketType == SocketMessageType.RunTime_ForceLogout)
{
// 服务器强制下线登录
Guid key = Guid.Empty;
string? msg = "";
if (SocketObject.Length > 0) key = SocketObject.GetParam<Guid>(0);
if (SocketObject.Length > 1) msg = SocketObject.GetParam<string>(1);
msg ??= "";
if (key == Usercfg.LoginKey)
{
Usercfg.LoginKey = Guid.Empty;
Main.UpdateUI(MainInvokeType.LogOut, msg ?? "");
}
}
else if (SocketObject.SocketType == SocketMessageType.Main_Chat)
{
// 收到房间聊天信息
string? user = "", msg = "";
if (SocketObject.Length > 0) user = SocketObject.GetParam<string>(0);
if (SocketObject.Length > 1) msg = SocketObject.GetParam<string>(1);
if (user != Usercfg.LoginUserName)
{
Main.GetMessage(msg, TimeType.None);
}
}
else if (SocketObject.SocketType == SocketMessageType.Room_UpdateRoomMaster)
{
// 收到房间更换房主的信息
User user = General.UnknownUserInstance;
Room room = General.HallInstance;
if (SocketObject.Length > 0) user = SocketObject.GetParam<User>(0) ?? General.UnknownUserInstance;
if (SocketObject.Length > 1) room = SocketObject.GetParam<Room>(1) ?? General.HallInstance;
if (room.Roomid != "-1" && room.Roomid == Usercfg.InRoom.Roomid) Main.UpdateUI(MainInvokeType.UpdateRoomMaster, room);
}
else if (SocketMessageTypes.Contains(SocketObject.SocketType))
{
Work = SocketObject;
Working = false;
}
}
catch (Exception e)
{
RunTime.Controller?.Error(e);
}
}
#endregion
#region SocketHandler
private (string, Guid) SocketHandler_LogOut()
{
string? msg = "";
Guid key = Guid.Empty;
try
{
WaitForWorkDone();
// 返回一个Key如果这个Key是空的登出失败
if (Work.Length > 0) key = Work.GetParam<Guid>(0);
if (Work.Length > 1) msg = Work.GetParam<string>(1);
}
catch (Exception e)
{
Main.GetMessage(e.GetErrorInfo());
}
msg ??= "";
return (msg, key);
}
private string SocketHandler_IntoRoom()
{
string? roomid = "";
try
{
WaitForWorkDone();
if (Work.Length > 0) roomid = Work.GetParam<string>(0);
}
catch (Exception e)
{
Main.GetMessage(e.GetErrorInfo());
}
roomid ??= "";
return roomid;
}
private string SocketHandler_CreateRoom()
{
string? roomid = "";
try
{
WaitForWorkDone();
if (Work.Length > 0) roomid = Work.GetParam<string>(0);
}
catch (Exception e)
{
Main.GetMessage(e.GetErrorInfo());
}
roomid ??= "";
return roomid;
}
private bool SocketHandler_QuitRoom()
{
bool result = false;
try
{
WaitForWorkDone();
if (Work.Length > 0) result = Work.GetParam<bool>(0);
}
catch (Exception e)
{
Main.GetMessage(e.GetErrorInfo());
}
return result;
}
private int SocketHandler_GetRoomPlayerCount()
{
int count = 0;
try
{
WaitForWorkDone();
if (Work.Length > 0) count = Work.GetParam<int>(0);
}
catch (Exception e)
{
Main.GetMessage(e.GetErrorInfo());
}
return count;
}
private List<Room> SocketHandler_UpdateRoom()
{
List<Room> list = new();
try
{
WaitForWorkDone();
if (Work.Length > 0) list = Work.GetParam<List<Room>>(0) ?? new();
}
catch (Exception e)
{
Main.GetMessage(e.GetErrorInfo());
}
return list;
}
#endregion
}
}

View File

@ -1,123 +0,0 @@
using Milimoe.FunGame.Core.Api.Utility;
using Milimoe.FunGame.Core.Library.Common.Network;
using Milimoe.FunGame.Core.Library.Constant;
using Milimoe.FunGame.Core.Library.Exception;
using Milimoe.FunGame.Core.Model;
using Milimoe.FunGame.Desktop.Library;
using Milimoe.FunGame.Desktop.Library.Component;
using RunTime = Milimoe.FunGame.Desktop.Library.RunTime;
namespace Milimoe.FunGame.Desktop.Model
{
public class RegisterModel : SocketHandlerModel
{
public RegisterModel() : base(RunTime.Socket)
{
}
public override void SocketHandler(SocketObject SocketObject)
{
try
{
if (SocketObject.SocketType == SocketMessageType.RunTime_Reg || SocketObject.SocketType == SocketMessageType.RunTime_CheckReg)
{
Work = SocketObject;
Working = false;
}
}
catch (Exception e)
{
RunTime.WritelnSystemInfo(e.GetErrorInfo());
}
}
public async Task<bool> Reg(params object[]? objs)
{
try
{
Socket? Socket = RunTime.Socket;
if (Socket != null && objs != null)
{
string username = "";
string password = "";
string email = "";
if (objs.Length > 0) username = (string)objs[0];
if (objs.Length > 1) password = (string)objs[1];
password = password.Encrypt(username);
if (objs.Length > 2) email = (string)objs[2];
SetWorking();
if (Socket.Send(SocketMessageType.RunTime_Reg, username, email) == SocketResult.Success)
{
RegInvokeType InvokeType = await Task.Factory.StartNew(GetRegInvokeType);
while (true)
{
switch (InvokeType)
{
case RegInvokeType.InputVerifyCode:
string verifycode = ShowMessage.InputMessageCancel("请输入注册邮件中的6位数字验证码", "注册验证码", out MessageResult cancel);
if (cancel != MessageResult.Cancel)
{
SetWorking();
if (Socket.Send(SocketMessageType.RunTime_CheckReg, username, password, email, verifycode) == SocketResult.Success)
{
bool success = false;
string msg = "";
(success, msg) = await Task.Factory.StartNew(GetRegResult);
ShowMessage.Message(msg, "注册结果");
if (success) return success;
}
break;
}
else return false;
case RegInvokeType.DuplicateUserName:
ShowMessage.WarningMessage("此账号名已被注册,请使用其他账号名。");
return false;
case RegInvokeType.DuplicateEmail:
ShowMessage.WarningMessage("此邮箱已被使用,请使用其他邮箱注册。");
return false;
}
}
}
}
}
catch (Exception e)
{
RunTime.WritelnSystemInfo(e.GetErrorInfo());
}
return false;
}
private RegInvokeType GetRegInvokeType()
{
RegInvokeType type = RegInvokeType.None;
try
{
WaitForWorkDone();
if (Work.Length > 0) type = Work.GetParam<RegInvokeType>(0);
}
catch (Exception e)
{
RunTime.WritelnSystemInfo(e.GetErrorInfo());
}
return type;
}
private (bool, string) GetRegResult()
{
bool success = false;
string? msg = "";
try
{
WaitForWorkDone();
if (Work.Length > 0) success = Work.GetParam<bool>(0);
if (Work.Length > 1) msg = Work.GetParam<string>(1) ?? "";
}
catch (Exception e)
{
RunTime.WritelnSystemInfo(e.GetErrorInfo());
}
return (success, msg);
}
}
}

View File

@ -1,160 +1,4 @@
using Milimoe.FunGame.Core.Library.Common.Event; namespace Milimoe.FunGame.Desktop.Model
using Milimoe.FunGame.Core.Library.Common.Network;
using Milimoe.FunGame.Core.Library.Constant;
using Milimoe.FunGame.Core.Library.Exception;
using Milimoe.FunGame.Desktop.Library.Component;
using Milimoe.FunGame.Desktop.Library;
using Milimoe.FunGame.Desktop.UI;
namespace Milimoe.FunGame.Desktop.Model
{ {
/// <summary> // wait to remove
/// 与创建关闭Socket相关的方法使用此类
/// </summary>
public class RunTimeModel : Core.Model.RunTime
{
private readonly Main Main;
private readonly Core.Model.Session Usercfg = RunTime.Session;
public RunTimeModel(Main main)
{
Main = main;
}
public override async Task<ConnectResult> Connect()
{
if (RunTime.Session.Server_IP == "" || RunTime.Session.Server_Port <= 0)
{
(RunTime.Session.Server_IP, RunTime.Session.Server_Port) = GetServerAddress();
if (RunTime.Session.Server_IP == "" || RunTime.Session.Server_Port <= 0)
{
ShowMessage.ErrorMessage("查找可用的服务器失败!");
return ConnectResult.FindServerFailed;
}
}
try
{
if (Config.FunGame_isRetrying)
{
Main.GetMessage("正在连接服务器,请耐心等待。");
Config.FunGame_isRetrying = false;
return ConnectResult.CanNotConnect;
}
if (!Config.FunGame_isConnected)
{
Main.CurrentRetryTimes++;
if (Main.CurrentRetryTimes == 0) Main.GetMessage("开始连接服务器...", TimeType.General);
else Main.GetMessage("第" + Main.CurrentRetryTimes + "次重试连接服务器...");
// 超过重连次数上限
if (Main.CurrentRetryTimes + 1 > Main.MaxRetryTimes)
{
throw new CanNotConnectException();
}
// 与服务器建立连接
Socket?.Close();
Config.FunGame_isRetrying = true;
_Socket = Socket.Connect(RunTime.Session.Server_IP, RunTime.Session.Server_Port);
if (Socket != null && Socket.Connected)
{
// 设置可复用Socket
RunTime.Socket = Socket;
// 发送连接请求
if (Socket.Send(SocketMessageType.RunTime_Connect) == SocketResult.Success)
{
SocketMessageType Result = Receiving();
if (Result == SocketMessageType.RunTime_Connect)
{
Main.GetMessage("连接服务器成功请登录账号以体验FunGame。");
Main.UpdateUI(MainInvokeType.Connected);
StartReceiving();
await Task.Factory.StartNew(() =>
{
while (true)
{
if (_IsReceiving)
{
break;
}
}
});
return ConnectResult.Success;
}
}
Config.FunGame_isRetrying = false;
Socket.Close();
return ConnectResult.ConnectFailed;
}
Socket?.Close();
Config.FunGame_isRetrying = false;
throw new CanNotConnectException();
}
else
{
Main.GetMessage("已连接至服务器,请勿重复连接。");
return ConnectResult.CanNotConnect;
}
}
catch (Exception e)
{
Main.GetMessage(e.GetErrorInfo(), TimeType.None);
Main.UpdateUI(MainInvokeType.SetRed);
Config.FunGame_isRetrying = false;
return ConnectResult.ConnectFailed;
}
}
public override void Error(Exception e)
{
Main.GetMessage(e.GetErrorInfo(), TimeType.None);
Main.UpdateUI(MainInvokeType.Disconnected);
Main.OnFailedConnectEvent(new ConnectEventArgs(RunTime.Session.Server_IP, RunTime.Session.Server_Port));
Close();
}
protected override bool SocketHandler_Connect(SocketObject ServerMessage)
{
string msg = "";
Guid token = Guid.Empty;
if (ServerMessage.Parameters.Length > 0) msg = ServerMessage.GetParam<string>(0)!;
string[] strings = msg.Split(';');
if (strings.Length != 2)
{
// 服务器拒绝连接
msg = strings[0];
Main.GetMessage(msg);
ShowMessage.ErrorMessage(msg);
return false;
}
string ServerName = strings[0];
string ServerNotice = strings[1];
Config.FunGame_ServerName = ServerName;
Config.FunGame_Notice = ServerNotice;
if (ServerMessage.Parameters.Length > 1) token = ServerMessage.GetParam<Guid>(1);
Socket!.Token = token;
Usercfg.SocketToken = token;
Main.GetMessage($"已连接服务器:{ServerName}。\n\n********** 服务器公告 **********\n\n{ServerNotice}\n\n");
// 设置等待登录的黄灯
Main.UpdateUI(MainInvokeType.WaitLoginAndSetYellow);
return true;
}
protected override void SocketHandler_Disconnect(SocketObject ServerMessage)
{
string msg = "";
if (ServerMessage.Parameters.Length > 0) msg = ServerMessage.GetParam<string>(0)!;
Main.GetMessage(msg);
Main.UpdateUI(MainInvokeType.Disconnect);
Close();
Main.OnSucceedDisconnectEvent(new GeneralEventArgs());
Main.OnAfterDisconnectEvent(new GeneralEventArgs());
}
protected override void SocketHandler_HeartBeat(SocketObject ServerMessage)
{
if (Socket != null && Socket.Connected && Usercfg.LoginUser.Id != 0)
{
Main.UpdateUI(MainInvokeType.SetGreenAndPing);
}
}
}
} }

View File

@ -48,7 +48,7 @@ namespace Milimoe.FunGame.Desktop.UI
Title.Location = new Point(7, 6); Title.Location = new Point(7, 6);
Title.Size = new Size(312, 47); Title.Size = new Size(312, 47);
Title.TabIndex = 8; Title.TabIndex = 8;
Title.Text = "Find Your Password"; Title.Text = "Forget Password";
Title.TextAlign = ContentAlignment.MiddleLeft; Title.TextAlign = ContentAlignment.MiddleLeft;
// //
// ExitButton // ExitButton

View File

@ -1,24 +1,25 @@
using Milimoe.FunGame.Core.Library.Constant; using Milimoe.FunGame.Core.Api.Utility;
using Milimoe.FunGame.Core.Library.Constant;
using Milimoe.FunGame.Core.Library.Exception; using Milimoe.FunGame.Core.Library.Exception;
using Milimoe.FunGame.Desktop.Controller; using Milimoe.FunGame.Desktop.Controller;
using Milimoe.FunGame.Desktop.Library; using Milimoe.FunGame.Desktop.Library;
using Milimoe.FunGame.Desktop.Library.Component;
namespace Milimoe.FunGame.Desktop.UI namespace Milimoe.FunGame.Desktop.UI
{ {
public partial class ForgetPassword public partial class ForgetPassword
{ {
private readonly LoginController LoginController;
public ForgetPassword() public ForgetPassword()
{ {
InitializeComponent(); InitializeComponent();
} LoginController = new(this);
Disposed += ForgetPassword_Disposed;
protected override void BindEvent()
{
base.BindEvent();
} }
private void FindPassword_Click(object sender, EventArgs e) private void FindPassword_Click(object sender, EventArgs e)
{
TaskUtility.StartAndAwaitTask(async () =>
{ {
if (RunTime.Socket != null) if (RunTime.Socket != null)
{ {
@ -26,7 +27,7 @@ namespace Milimoe.FunGame.Desktop.UI
string email = EmailText.Text.Trim(); string email = EmailText.Text.Trim();
if (username == "" || email == "") if (username == "" || email == "")
{ {
ShowMessage.ErrorMessage("账号或邮箱不能为空!"); ShowMessage(ShowMessageType.Error, "账号或邮箱不能为空!");
UsernameText.Focus(); UsernameText.Focus();
return; return;
} }
@ -37,26 +38,26 @@ namespace Milimoe.FunGame.Desktop.UI
try try
{ {
// 发送找回密码请求 // 发送找回密码请求
msg = LoginController.ForgetPassword_CheckVerifyCode(username, email); msg = await LoginController.ForgetPassword_CheckVerifyCodeAsync(username, email, "");
if (msg.Trim() != "") if (msg.Trim() != "")
{ {
// 如果返回一个信息,则停止找回密码 // 如果返回一个信息,则停止找回密码
ShowMessage.ErrorMessage(msg); ShowMessage(ShowMessageType.Error, msg);
} }
else else
{ {
while (!success) while (!success)
{ {
string verifycode = ShowMessage.InputMessageCancel("请输入找回密码邮件中的6位数字验证码", "注册验证码", out MessageResult result); string verifycode = ShowInputMessageCancel("请输入找回密码邮件中的6位数字验证码", "注册验证码", out MessageResult result);
if (result != MessageResult.Cancel) if (result != MessageResult.Cancel)
{ {
if (verifycode.Trim() != "") if (verifycode.Trim() != "")
{ {
msg = LoginController.ForgetPassword_CheckVerifyCode(username, email, verifycode); msg = await LoginController.ForgetPassword_CheckVerifyCodeAsync(username, email, verifycode);
if (msg.Trim() != "") if (msg.Trim() != "")
{ {
ShowMessage.ErrorMessage(msg); ShowMessage(ShowMessageType.Error, msg);
} }
else else
{ {
@ -66,7 +67,7 @@ namespace Milimoe.FunGame.Desktop.UI
} }
else else
{ {
ShowMessage.WarningMessage("不能输入空值!"); ShowMessage(ShowMessageType.Warning, "不能输入空值!");
} }
} }
else break; else break;
@ -75,25 +76,25 @@ namespace Milimoe.FunGame.Desktop.UI
{ {
while (true) while (true)
{ {
string newpass = ShowMessage.InputMessageCancel("请输入新密码", "设置新密码", out MessageResult result); string newpass = ShowInputMessageCancel("请输入新密码", "设置新密码", out MessageResult result);
if (result != MessageResult.Cancel) if (result != MessageResult.Cancel)
{ {
if (newpass.Trim() != "") if (newpass.Trim() != "")
{ {
if (newpass.Length < 6 || newpass.Length > 15) // 字节范围 3~12 if (newpass.Length < 6 || newpass.Length > 15) // 字节范围 3~12
{ {
ShowMessage.ErrorMessage("密码长度不符合要求6~15个字符数"); ShowMessage(ShowMessageType.Error, "密码长度不符合要求6~15个字符数");
} }
else else
{ {
msg = LoginController.ForgetPassword_UpdatePassword(username, newpass); msg = await LoginController.ForgetPassword_UpdatePasswordAsync(username, newpass);
if (msg.Trim() != "") if (msg.Trim() != "")
{ {
ShowMessage.ErrorMessage(msg); ShowMessage(ShowMessageType.Error, msg);
} }
else else
{ {
ShowMessage.Message("密码更新成功!请您牢记新的密码。", "找回密码"); ShowMessage(ShowMessageType.General, "密码更新成功!请您牢记新的密码。", "找回密码");
break; break;
} }
} }
@ -101,7 +102,7 @@ namespace Milimoe.FunGame.Desktop.UI
} }
else else
{ {
if (ShowMessage.OKCancelMessage("确定放弃设置新密码吗?", "找回密码") == MessageResult.OK) if (ShowMessage(ShowMessageType.OKCancel, "确定放弃设置新密码吗?", "找回密码") == MessageResult.OK)
{ {
success = false; success = false;
break; break;
@ -120,6 +121,12 @@ namespace Milimoe.FunGame.Desktop.UI
RunTime.WritelnSystemInfo(ex.GetErrorInfo()); RunTime.WritelnSystemInfo(ex.GetErrorInfo());
} }
} }
});
}
private void ForgetPassword_Disposed(object? sender, EventArgs e)
{
LoginController.Dispose();
} }
} }
} }

View File

@ -1,4 +1,64 @@
<root> <?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing"">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" /> <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true"> <xsd:element name="root" msdata:IsDataSet="true">

View File

@ -28,203 +28,202 @@
/// </summary> /// </summary>
private void InitializeComponent() private void InitializeComponent()
{ {
this.components = new System.ComponentModel.Container(); components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Login)); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Login));
this.ExitButton = new Milimoe.FunGame.Desktop.Library.Component.ExitButton(this.components); ExitButton = new Library.Component.ExitButton(components);
this.MinButton = new Milimoe.FunGame.Desktop.Library.Component.MinButton(this.components); MinButton = new Library.Component.MinButton(components);
this.Username = new System.Windows.Forms.Label(); Username = new Label();
this.Password = new System.Windows.Forms.Label(); Password = new Label();
this.UsernameText = new System.Windows.Forms.TextBox(); UsernameText = new TextBox();
this.PasswordText = new System.Windows.Forms.TextBox(); PasswordText = new TextBox();
this.RegButton = new System.Windows.Forms.Button(); RegButton = new Button();
this.GoToLogin = new System.Windows.Forms.Button(); GoToLogin = new Button();
this.ForgetPassword = new System.Windows.Forms.Button(); ForgetPassword = new Button();
this.FastLogin = new System.Windows.Forms.Button(); FastLogin = new Button();
this.TransparentRect = new Milimoe.FunGame.Desktop.Library.Component.TransparentRect(); TransparentRect = new Library.Component.TransparentRect();
this.TransparentRect.SuspendLayout(); TransparentRect.SuspendLayout();
this.SuspendLayout(); SuspendLayout();
// //
// Title // Title
// //
this.Title.Font = new System.Drawing.Font("LanaPixel", 26.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point); Title.Font = new Font("LanaPixel", 26.25F, FontStyle.Bold, GraphicsUnit.Point);
this.Title.Location = new System.Drawing.Point(7, 6); Title.Location = new Point(7, 6);
this.Title.Size = new System.Drawing.Size(387, 47); Title.Size = new Size(387, 47);
this.Title.TabIndex = 8; Title.TabIndex = 8;
this.Title.Text = "Welcome to FunGame!"; Title.Text = "Welcome to FunGame!";
this.Title.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; Title.TextAlign = ContentAlignment.MiddleLeft;
// //
// ExitButton // ExitButton
// //
this.ExitButton.Anchor = System.Windows.Forms.AnchorStyles.None; ExitButton.Anchor = AnchorStyles.None;
this.ExitButton.BackColor = System.Drawing.Color.White; ExitButton.BackColor = Color.White;
this.ExitButton.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("ExitButton.BackgroundImage"))); ExitButton.BackgroundImage = (Image)resources.GetObject("ExitButton.BackgroundImage");
this.ExitButton.FlatAppearance.BorderColor = System.Drawing.Color.White; ExitButton.FlatAppearance.BorderColor = Color.White;
this.ExitButton.FlatAppearance.BorderSize = 0; ExitButton.FlatAppearance.BorderSize = 0;
this.ExitButton.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(128)))), ((int)(((byte)(128))))); ExitButton.FlatAppearance.MouseDownBackColor = Color.FromArgb(255, 128, 128);
this.ExitButton.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(192))))); ExitButton.FlatAppearance.MouseOverBackColor = Color.FromArgb(255, 192, 192);
this.ExitButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat; ExitButton.FlatStyle = FlatStyle.Flat;
this.ExitButton.Font = new System.Drawing.Font("LanaPixel", 36F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point); ExitButton.Font = new Font("LanaPixel", 36F, FontStyle.Bold, GraphicsUnit.Point);
this.ExitButton.ForeColor = System.Drawing.Color.Red; ExitButton.ForeColor = Color.Red;
this.ExitButton.Location = new System.Drawing.Point(451, 4); ExitButton.Location = new Point(451, 4);
this.ExitButton.Name = "ExitButton"; ExitButton.Name = "ExitButton";
this.ExitButton.RelativeForm = this; ExitButton.RelativeForm = this;
this.ExitButton.Size = new System.Drawing.Size(47, 47); ExitButton.Size = new Size(47, 47);
this.ExitButton.TabIndex = 7; ExitButton.TabIndex = 7;
this.ExitButton.TextAlign = System.Drawing.ContentAlignment.TopLeft; ExitButton.TextAlign = ContentAlignment.TopLeft;
this.ExitButton.UseVisualStyleBackColor = false; ExitButton.UseVisualStyleBackColor = false;
// //
// MinButton // MinButton
// //
this.MinButton.Anchor = System.Windows.Forms.AnchorStyles.None; MinButton.Anchor = AnchorStyles.None;
this.MinButton.BackColor = System.Drawing.Color.White; MinButton.BackColor = Color.White;
this.MinButton.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("MinButton.BackgroundImage"))); MinButton.BackgroundImage = (Image)resources.GetObject("MinButton.BackgroundImage");
this.MinButton.FlatAppearance.BorderColor = System.Drawing.Color.White; MinButton.FlatAppearance.BorderColor = Color.White;
this.MinButton.FlatAppearance.BorderSize = 0; MinButton.FlatAppearance.BorderSize = 0;
this.MinButton.FlatAppearance.MouseDownBackColor = System.Drawing.Color.Gray; MinButton.FlatAppearance.MouseDownBackColor = Color.Gray;
this.MinButton.FlatAppearance.MouseOverBackColor = System.Drawing.Color.DarkGray; MinButton.FlatAppearance.MouseOverBackColor = Color.DarkGray;
this.MinButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat; MinButton.FlatStyle = FlatStyle.Flat;
this.MinButton.Font = new System.Drawing.Font("LanaPixel", 36F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point); MinButton.Font = new Font("LanaPixel", 36F, FontStyle.Bold, GraphicsUnit.Point);
this.MinButton.ForeColor = System.Drawing.Color.Black; MinButton.ForeColor = Color.Black;
this.MinButton.Location = new System.Drawing.Point(398, 4); MinButton.Location = new Point(398, 4);
this.MinButton.Name = "MinButton"; MinButton.Name = "MinButton";
this.MinButton.RelativeForm = this; MinButton.RelativeForm = this;
this.MinButton.Size = new System.Drawing.Size(47, 47); MinButton.Size = new Size(47, 47);
this.MinButton.TabIndex = 6; MinButton.TabIndex = 6;
this.MinButton.TextAlign = System.Drawing.ContentAlignment.TopLeft; MinButton.TextAlign = ContentAlignment.TopLeft;
this.MinButton.UseVisualStyleBackColor = false; MinButton.UseVisualStyleBackColor = false;
// //
// Username // Username
// //
this.Username.Font = new System.Drawing.Font("LanaPixel", 15F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point); Username.Font = new Font("LanaPixel", 15F, FontStyle.Regular, GraphicsUnit.Point);
this.Username.Location = new System.Drawing.Point(56, 111); Username.Location = new Point(56, 111);
this.Username.Name = "Username"; Username.Name = "Username";
this.Username.Size = new System.Drawing.Size(75, 33); Username.Size = new Size(75, 33);
this.Username.TabIndex = 9; Username.TabIndex = 9;
this.Username.Text = "账号"; Username.Text = "账号";
this.Username.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; Username.TextAlign = ContentAlignment.MiddleCenter;
// //
// Password // Password
// //
this.Password.Font = new System.Drawing.Font("LanaPixel", 15F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point); Password.Font = new Font("LanaPixel", 15F, FontStyle.Regular, GraphicsUnit.Point);
this.Password.Location = new System.Drawing.Point(56, 144); Password.Location = new Point(56, 144);
this.Password.Name = "Password"; Password.Name = "Password";
this.Password.Size = new System.Drawing.Size(75, 33); Password.Size = new Size(75, 33);
this.Password.TabIndex = 10; Password.TabIndex = 10;
this.Password.Text = "密码"; Password.Text = "密码";
this.Password.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; Password.TextAlign = ContentAlignment.MiddleCenter;
// //
// UsernameText // UsernameText
// //
this.UsernameText.Font = new System.Drawing.Font("LanaPixel", 15F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point); UsernameText.Font = new Font("LanaPixel", 15F, FontStyle.Regular, GraphicsUnit.Point);
this.UsernameText.Location = new System.Drawing.Point(143, 114); UsernameText.Location = new Point(143, 114);
this.UsernameText.Name = "UsernameText"; UsernameText.Name = "UsernameText";
this.UsernameText.Size = new System.Drawing.Size(216, 29); UsernameText.Size = new Size(216, 29);
this.UsernameText.TabIndex = 0; UsernameText.TabIndex = 0;
// //
// PasswordText // PasswordText
// //
this.PasswordText.Font = new System.Drawing.Font("LanaPixel", 15F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point); PasswordText.Font = new Font("LanaPixel", 15F, FontStyle.Regular, GraphicsUnit.Point);
this.PasswordText.Location = new System.Drawing.Point(143, 148); PasswordText.Location = new Point(143, 148);
this.PasswordText.Name = "PasswordText"; PasswordText.Name = "PasswordText";
this.PasswordText.PasswordChar = '*'; PasswordText.PasswordChar = '*';
this.PasswordText.Size = new System.Drawing.Size(216, 29); PasswordText.Size = new Size(216, 29);
this.PasswordText.TabIndex = 1; PasswordText.TabIndex = 1;
// //
// RegButton // RegButton
// //
this.RegButton.Font = new System.Drawing.Font("LanaPixel", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point); RegButton.Font = new Font("LanaPixel", 12F, FontStyle.Regular, GraphicsUnit.Point);
this.RegButton.Location = new System.Drawing.Point(365, 113); RegButton.Location = new Point(365, 113);
this.RegButton.Name = "RegButton"; RegButton.Name = "RegButton";
this.RegButton.Size = new System.Drawing.Size(81, 33); RegButton.Size = new Size(81, 33);
this.RegButton.TabIndex = 4; RegButton.TabIndex = 4;
this.RegButton.Text = "立即注册"; RegButton.Text = "立即注册";
this.RegButton.UseVisualStyleBackColor = true; RegButton.UseVisualStyleBackColor = true;
this.RegButton.Click += new System.EventHandler(this.RegButton_Click); RegButton.Click += RegButton_Click;
// //
// GoToLogin // GoToLogin
// //
this.GoToLogin.Font = new System.Drawing.Font("LanaPixel", 18F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point); GoToLogin.Font = new Font("LanaPixel", 18F, FontStyle.Regular, GraphicsUnit.Point);
this.GoToLogin.Location = new System.Drawing.Point(277, 216); GoToLogin.Location = new Point(277, 216);
this.GoToLogin.Name = "GoToLogin"; GoToLogin.Name = "GoToLogin";
this.GoToLogin.Size = new System.Drawing.Size(128, 42); GoToLogin.Size = new Size(128, 42);
this.GoToLogin.TabIndex = 2; GoToLogin.TabIndex = 2;
this.GoToLogin.Text = "账号登录"; GoToLogin.Text = "账号登录";
this.GoToLogin.UseVisualStyleBackColor = true; GoToLogin.UseVisualStyleBackColor = true;
this.GoToLogin.Click += new System.EventHandler(this.GoToLogin_Click); GoToLogin.Click += GoToLogin_Click;
// //
// ForgetPassword // ForgetPassword
// //
this.ForgetPassword.Font = new System.Drawing.Font("LanaPixel", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point); ForgetPassword.Font = new Font("LanaPixel", 12F, FontStyle.Regular, GraphicsUnit.Point);
this.ForgetPassword.Location = new System.Drawing.Point(365, 147); ForgetPassword.Location = new Point(365, 147);
this.ForgetPassword.Name = "ForgetPassword"; ForgetPassword.Name = "ForgetPassword";
this.ForgetPassword.Size = new System.Drawing.Size(81, 32); ForgetPassword.Size = new Size(81, 32);
this.ForgetPassword.TabIndex = 5; ForgetPassword.TabIndex = 5;
this.ForgetPassword.Text = "找回密码"; ForgetPassword.Text = "忘记密码";
this.ForgetPassword.UseVisualStyleBackColor = true; ForgetPassword.UseVisualStyleBackColor = true;
this.ForgetPassword.Click += new System.EventHandler(this.ForgetPassword_Click); ForgetPassword.Click += ForgetPassword_Click;
// //
// FastLogin // FastLogin
// //
this.FastLogin.Font = new System.Drawing.Font("LanaPixel", 18F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point); FastLogin.Font = new Font("LanaPixel", 18F, FontStyle.Regular, GraphicsUnit.Point);
this.FastLogin.Location = new System.Drawing.Point(114, 216); FastLogin.Location = new Point(114, 216);
this.FastLogin.Name = "FastLogin"; FastLogin.Name = "FastLogin";
this.FastLogin.Size = new System.Drawing.Size(130, 42); FastLogin.Size = new Size(130, 42);
this.FastLogin.TabIndex = 3; FastLogin.TabIndex = 3;
this.FastLogin.Text = "快捷登录"; FastLogin.Text = "快捷登录";
this.FastLogin.UseVisualStyleBackColor = true; FastLogin.UseVisualStyleBackColor = true;
this.FastLogin.Click += new System.EventHandler(this.FastLogin_Click); FastLogin.Click += FastLogin_Click;
// //
// TransparentRect // TransparentRect
// //
this.TransparentRect.BackColor = System.Drawing.Color.WhiteSmoke; TransparentRect.BackColor = Color.WhiteSmoke;
this.TransparentRect.BorderColor = System.Drawing.Color.WhiteSmoke; TransparentRect.BorderColor = Color.WhiteSmoke;
this.TransparentRect.Controls.Add(this.Title); TransparentRect.Controls.Add(Title);
this.TransparentRect.Controls.Add(this.MinButton); TransparentRect.Controls.Add(MinButton);
this.TransparentRect.Controls.Add(this.ExitButton); TransparentRect.Controls.Add(ExitButton);
this.TransparentRect.Controls.Add(this.FastLogin); TransparentRect.Controls.Add(FastLogin);
this.TransparentRect.Controls.Add(this.UsernameText); TransparentRect.Controls.Add(UsernameText);
this.TransparentRect.Controls.Add(this.ForgetPassword); TransparentRect.Controls.Add(ForgetPassword);
this.TransparentRect.Controls.Add(this.Username); TransparentRect.Controls.Add(Username);
this.TransparentRect.Controls.Add(this.GoToLogin); TransparentRect.Controls.Add(GoToLogin);
this.TransparentRect.Controls.Add(this.Password); TransparentRect.Controls.Add(Password);
this.TransparentRect.Controls.Add(this.RegButton); TransparentRect.Controls.Add(RegButton);
this.TransparentRect.Controls.Add(this.PasswordText); TransparentRect.Controls.Add(PasswordText);
this.TransparentRect.Location = new System.Drawing.Point(0, 0); TransparentRect.Location = new Point(0, 0);
this.TransparentRect.Name = "TransparentRect"; TransparentRect.Name = "TransparentRect";
this.TransparentRect.Opacity = 125; TransparentRect.Opacity = 125;
this.TransparentRect.Radius = 20; TransparentRect.Radius = 20;
this.TransparentRect.ShapeBorderStyle = Milimoe.FunGame.Desktop.Library.Component.TransparentRect.ShapeBorderStyles.ShapeBSNone; TransparentRect.ShapeBorderStyle = Library.Component.TransparentRect.ShapeBorderStyles.ShapeBSNone;
this.TransparentRect.Size = new System.Drawing.Size(503, 289); TransparentRect.Size = new Size(503, 289);
this.TransparentRect.TabIndex = 11; TransparentRect.TabIndex = 11;
this.TransparentRect.TabStop = false; TransparentRect.TabStop = false;
this.TransparentRect.Controls.SetChildIndex(this.PasswordText, 0); TransparentRect.Controls.SetChildIndex(PasswordText, 0);
this.TransparentRect.Controls.SetChildIndex(this.RegButton, 0); TransparentRect.Controls.SetChildIndex(RegButton, 0);
this.TransparentRect.Controls.SetChildIndex(this.Password, 0); TransparentRect.Controls.SetChildIndex(Password, 0);
this.TransparentRect.Controls.SetChildIndex(this.GoToLogin, 0); TransparentRect.Controls.SetChildIndex(GoToLogin, 0);
this.TransparentRect.Controls.SetChildIndex(this.Username, 0); TransparentRect.Controls.SetChildIndex(Username, 0);
this.TransparentRect.Controls.SetChildIndex(this.ForgetPassword, 0); TransparentRect.Controls.SetChildIndex(ForgetPassword, 0);
this.TransparentRect.Controls.SetChildIndex(this.UsernameText, 0); TransparentRect.Controls.SetChildIndex(UsernameText, 0);
this.TransparentRect.Controls.SetChildIndex(this.FastLogin, 0); TransparentRect.Controls.SetChildIndex(FastLogin, 0);
this.TransparentRect.Controls.SetChildIndex(this.ExitButton, 0); TransparentRect.Controls.SetChildIndex(ExitButton, 0);
this.TransparentRect.Controls.SetChildIndex(this.MinButton, 0); TransparentRect.Controls.SetChildIndex(MinButton, 0);
this.TransparentRect.Controls.SetChildIndex(this.Title, 0); TransparentRect.Controls.SetChildIndex(Title, 0);
// //
// Login // Login
// //
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 17F); AutoScaleDimensions = new SizeF(7F, 17F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.WhiteSmoke; BackColor = Color.WhiteSmoke;
this.ClientSize = new System.Drawing.Size(503, 289); ClientSize = new Size(503, 289);
this.Controls.Add(this.TransparentRect); Controls.Add(TransparentRect);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); Icon = (Icon)resources.GetObject("$this.Icon");
this.Name = "Login"; Name = "Login";
this.Opacity = 0.9D; Opacity = 0.9D;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; StartPosition = FormStartPosition.CenterScreen;
this.Text = "Login"; Text = "Login";
this.TransparentRect.ResumeLayout(false); TransparentRect.ResumeLayout(false);
this.TransparentRect.PerformLayout(); TransparentRect.PerformLayout();
this.ResumeLayout(false); ResumeLayout(false);
} }
#endregion #endregion

View File

@ -1,10 +1,10 @@
using Milimoe.FunGame.Core.Library.Common.Event; using Milimoe.FunGame.Core.Api.Utility;
using Milimoe.FunGame.Core.Library.Common.Event;
using Milimoe.FunGame.Core.Library.Constant; using Milimoe.FunGame.Core.Library.Constant;
using Milimoe.FunGame.Core.Library.Exception; using Milimoe.FunGame.Core.Library.Exception;
using Milimoe.FunGame.Desktop.Controller; using Milimoe.FunGame.Desktop.Controller;
using Milimoe.FunGame.Desktop.Library; using Milimoe.FunGame.Desktop.Library;
using Milimoe.FunGame.Desktop.Library.Base; using Milimoe.FunGame.Desktop.Library.Base;
using Milimoe.FunGame.Desktop.Library.Component;
using Milimoe.FunGame.Desktop.Utility; using Milimoe.FunGame.Desktop.Utility;
namespace Milimoe.FunGame.Desktop.UI namespace Milimoe.FunGame.Desktop.UI
@ -16,7 +16,7 @@ namespace Milimoe.FunGame.Desktop.UI
public Login() public Login()
{ {
InitializeComponent(); InitializeComponent();
LoginController = new LoginController(); LoginController = new(this);
} }
protected override void BindEvent() protected override void BindEvent()
@ -29,11 +29,6 @@ namespace Milimoe.FunGame.Desktop.UI
SucceedLogin += SucceedLoginEvent; SucceedLogin += SucceedLoginEvent;
} }
private void Login_Disposed(object? sender, EventArgs e)
{
LoginController.Dispose();
}
private async Task<bool> Login_Handler() private async Task<bool> Login_Handler()
{ {
try try
@ -42,11 +37,11 @@ namespace Milimoe.FunGame.Desktop.UI
string password = PasswordText.Text.Trim(); string password = PasswordText.Text.Trim();
if (username == "" || password == "") if (username == "" || password == "")
{ {
ShowMessage.ErrorMessage("账号或密码不能为空!"); ShowMessage(ShowMessageType.Error, "账号或密码不能为空!");
UsernameText.Focus(); UsernameText.Focus();
return false; return false;
} }
return await LoginController.LoginAccount(username, password); return await LoginController.LoginAccountAsync(username, password);
} }
catch (Exception e) catch (Exception e)
{ {
@ -67,15 +62,27 @@ namespace Milimoe.FunGame.Desktop.UI
private void FastLogin_Click(object sender, EventArgs e) private void FastLogin_Click(object sender, EventArgs e)
{ {
ShowMessage.TipMessage("与No.16对话即可获得快速登录秘钥,快去试试吧!"); ShowMessage(ShowMessageType.Tip, "与No.16对话即可获得快速登录秘钥,快去试试吧!");
} }
private async void GoToLogin_Click(object sender, EventArgs e) private void GoToLogin_Click(object sender, EventArgs e)
{ {
GoToLogin.Enabled = false; GoToLogin.Enabled = false;
if (await Login_Handler() == false) GoToLogin.Enabled = true; bool result = false;
else Dispose(); TaskUtility.StartAndAwaitTask(async () =>
{
result = await Login_Handler();
}).OnCompleted(() =>
{
if (result) Dispose();
else GoToLogin.Enabled = true;
});
} }
private void Login_Disposed(object? sender, EventArgs e)
{
LoginController.Dispose();
}
private void ForgetPassword_Click(object sender, EventArgs e) private void ForgetPassword_Click(object sender, EventArgs e)
{ {
@ -85,8 +92,7 @@ namespace Milimoe.FunGame.Desktop.UI
public EventResult FailedLoginEvent(object sender, LoginEventArgs e) public EventResult FailedLoginEvent(object sender, LoginEventArgs e)
{ {
if (InvokeRequired) GoToLogin.Invoke(() => GoToLogin.Enabled = true); GoToLogin.Enabled = true;
else GoToLogin.Enabled = true;
RunTime.Main?.OnFailedLoginEvent(e); RunTime.Main?.OnFailedLoginEvent(e);
return EventResult.Success; return EventResult.Success;
} }

View File

@ -1,4 +1,64 @@
<root> <?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing"">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" /> <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true"> <xsd:element name="root" msdata:IsDataSet="true">

View File

@ -7,7 +7,6 @@ using Milimoe.FunGame.Core.Library.Exception;
using Milimoe.FunGame.Desktop.Controller; using Milimoe.FunGame.Desktop.Controller;
using Milimoe.FunGame.Desktop.Library; using Milimoe.FunGame.Desktop.Library;
using Milimoe.FunGame.Desktop.Library.Base; using Milimoe.FunGame.Desktop.Library.Base;
using Milimoe.FunGame.Desktop.Library.Component;
using Milimoe.FunGame.Desktop.Utility; using Milimoe.FunGame.Desktop.Utility;
namespace Milimoe.FunGame.Desktop.UI namespace Milimoe.FunGame.Desktop.UI
@ -26,7 +25,7 @@ namespace Milimoe.FunGame.Desktop.UI
/** /**
* *
*/ */
private Task? MatchFunGame = null; // 匹配线程 private Task? MatchFunGame = null; // 匹配线程(即将删除)
private MainController? MainController = null; private MainController? MainController = null;
private readonly Core.Model.RoomList Rooms = RunTime.RoomList; private readonly Core.Model.RoomList Rooms = RunTime.RoomList;
private readonly Core.Model.Session Usercfg = RunTime.Session; private readonly Core.Model.Session Usercfg = RunTime.Session;
@ -39,13 +38,13 @@ namespace Milimoe.FunGame.Desktop.UI
public Main() public Main()
{ {
InitializeComponent(); InitializeComponent();
InitAsync(); Init();
} }
/// <summary> /// <summary>
/// 所有自定义初始化的内容 /// 所有自定义初始化的内容
/// </summary> /// </summary>
public async void InitAsync() public void Init()
{ {
RunTime.Main = this; RunTime.Main = this;
SetButtonEnableIfLogon(false, ClientState.WaitConnect); SetButtonEnableIfLogon(false, ClientState.WaitConnect);
@ -55,7 +54,7 @@ namespace Milimoe.FunGame.Desktop.UI
// 创建RunTime // 创建RunTime
RunTime.Controller = new RunTimeController(this); RunTime.Controller = new RunTimeController(this);
// 窗口句柄创建后,进行委托 // 窗口句柄创建后,进行委托
await Task.Factory.StartNew(() => TaskUtility.StartAndAwaitTask(() =>
{ {
while (true) while (true)
{ {
@ -64,7 +63,7 @@ namespace Milimoe.FunGame.Desktop.UI
break; break;
} }
} }
if (Config.FunGame_isAutoConnect) RunTime.Controller?.Connect(); if (Config.FunGame_isAutoConnect) InvokeController_Connect();
}); });
} }
@ -130,7 +129,7 @@ namespace Milimoe.FunGame.Desktop.UI
if (MainController != null && Config.FunGame_isAutoConnect) if (MainController != null && Config.FunGame_isAutoConnect)
{ {
// 自动连接服务器 // 自动连接服务器
RunTime.Controller?.Connect(); InvokeController_Connect();
} }
break; break;
@ -188,7 +187,7 @@ namespace Milimoe.FunGame.Desktop.UI
if (objs[0].GetType() == typeof(string)) if (objs[0].GetType() == typeof(string))
{ {
WritelnSystemInfo((string)objs[0]); WritelnSystemInfo((string)objs[0]);
ShowMessage.Message((string)objs[0], "退出登录", 5); ShowMessage(ShowMessageType.General, (string)objs[0], "退出登录", 5);
} }
} }
break; break;
@ -250,13 +249,13 @@ namespace Milimoe.FunGame.Desktop.UI
/// </summary> /// </summary>
/// <param name="msg"></param> /// <param name="msg"></param>
/// <param name="timetype"></param> /// <param name="timetype"></param>
public void GetMessage(string? msg, TimeType timetype = TimeType.TimeOnly) public void GetMessage(string msg, TimeType timetype = TimeType.TimeOnly)
{ {
void action() void action()
{ {
try try
{ {
if (msg == null || msg == "") return; if (msg == "") return;
if (timetype != TimeType.None) if (timetype != TimeType.None)
{ {
WritelnGameInfo(DateTimeUtility.GetDateTimeToString(timetype) + " >> " + msg); WritelnGameInfo(DateTimeUtility.GetDateTimeToString(timetype) + " >> " + msg);
@ -278,16 +277,6 @@ namespace Milimoe.FunGame.Desktop.UI
#region #region
/// <summary>
/// 委托更新UI
/// </summary>
/// <param name="action"></param>
private void InvokeUpdateUI(Action action)
{
if (InvokeRequired) Invoke(action);
else action();
}
/// <summary> /// <summary>
/// 获取FunGame配置文件设定 /// 获取FunGame配置文件设定
/// </summary> /// </summary>
@ -484,7 +473,7 @@ namespace Milimoe.FunGame.Desktop.UI
else else
{ {
RoomText.Enabled = false; RoomText.Enabled = false;
ShowMessage.TipMessage("请输入房间号。"); ShowMessage(ShowMessageType.Tip, "请输入房间号。");
RoomText.Enabled = true; RoomText.Enabled = true;
RoomText.Focus(); RoomText.Focus();
return false; return false;
@ -505,15 +494,15 @@ namespace Milimoe.FunGame.Desktop.UI
{ {
if (MainController != null) if (MainController != null)
{ {
await MainController.UpdateRoom(); await MainController.UpdateRoomAsync();
if (CheckRoomIDExist(roomid)) if (CheckRoomIDExist(roomid))
{ {
if (Usercfg.InRoom.Roomid == "-1") if (Usercfg.InRoom.Roomid == "-1")
{ {
if (ShowMessage.YesNoMessage("已找到房间 -> [ " + roomid + " ]\n是否加入", "已找到房间") == MessageResult.Yes) if (ShowMessage(ShowMessageType.YesNo, "已找到房间 -> [ " + roomid + " ]\n是否加入", "已找到房间") == MessageResult.Yes)
{ {
Room r = GetRoom(roomid); Room r = GetRoom(roomid);
if (MainController != null && await MainController.IntoRoom(r)) if (MainController != null && await MainController.IntoRoomAsync(r))
{ {
SetRoomid(r); SetRoomid(r);
InRoom(); InRoom();
@ -524,12 +513,12 @@ namespace Milimoe.FunGame.Desktop.UI
} }
else else
{ {
ShowMessage.TipMessage("你需要先退出房间才可以加入新的房间。"); ShowMessage(ShowMessageType.Tip, "你需要先退出房间才可以加入新的房间。");
return false; return false;
} }
} }
} }
ShowMessage.WarningMessage("未找到此房间!"); ShowMessage(ShowMessageType.Warning, "未找到此房间!");
return false; return false;
} }
@ -661,7 +650,7 @@ namespace Milimoe.FunGame.Desktop.UI
Logout.Visible = true; Logout.Visible = true;
UpdateUI(MainInvokeType.SetGreenAndPing); UpdateUI(MainInvokeType.SetGreenAndPing);
string welcome = $"欢迎回来, {Usercfg.LoginUserName}"; string welcome = $"欢迎回来, {Usercfg.LoginUserName}";
ShowMessage.Message(welcome, "登录成功", 5); ShowMessage(ShowMessageType.General, welcome, "登录成功", 5);
WritelnSystemInfo(welcome); WritelnSystemInfo(welcome);
} }
@ -702,7 +691,7 @@ namespace Milimoe.FunGame.Desktop.UI
/// 发送消息实现 /// 发送消息实现
/// </summary> /// </summary>
/// <param name="isLeave">是否离开焦点</param> /// <param name="isLeave">是否离开焦点</param>
private async Task SendTalkText_Click(bool isLeave) private void SendTalkText_Click(bool isLeave)
{ {
// 向消息队列发送消息 // 向消息队列发送消息
string text = TalkText.Text; string text = TalkText.Text;
@ -718,17 +707,23 @@ namespace Milimoe.FunGame.Desktop.UI
msg = DateTimeUtility.GetNowShortTime() + " [ " + Usercfg.LoginUserName + " ] 说: " + text; msg = DateTimeUtility.GetNowShortTime() + " [ " + Usercfg.LoginUserName + " ] 说: " + text;
} }
WritelnGameInfo(msg); WritelnGameInfo(msg);
if (Usercfg.LoginUser.Id != 0 && !await SwitchTalkMessage(text))
{
MainController?.Chat(" [ " + Usercfg.LoginUserName + " ] 说: " + text);
}
TalkText.Text = ""; TalkText.Text = "";
if (isLeave) TalkText_Leave(); // 回车不离开焦点 if (isLeave) TalkText_Leave(); // 回车不离开焦点
if (MainController != null && Usercfg.LoginUser.Id != 0 && !SwitchTalkMessage(text))
{
TaskUtility.StartAndAwaitTask(async () =>
{
if (!await MainController.ChatAsync(" [ " + Usercfg.LoginUserName + " ] 说: " + text))
{
WritelnGameInfo("联网消息发送失败。");
}
});
}
} }
else else
{ {
TalkText.Enabled = false; TalkText.Enabled = false;
ShowMessage.TipMessage("消息不能为空,请重新输入。"); ShowMessage(ShowMessageType.Tip, "消息不能为空,请重新输入。");
TalkText.Enabled = true; TalkText.Enabled = true;
TalkText.Focus(); TalkText.Focus();
} }
@ -744,26 +739,26 @@ namespace Milimoe.FunGame.Desktop.UI
{ {
if (Usercfg.InRoom.Roomid != "-1") if (Usercfg.InRoom.Roomid != "-1")
{ {
ShowMessage.WarningMessage("已在房间中,无法创建房间。"); ShowMessage(ShowMessageType.Warning, "已在房间中,无法创建房间。");
return; return;
} }
if (MainController != null) if (MainController != null)
{ {
string roomid = (await MainController.CreateRoom(RoomType, Password)).Trim(); string roomid = await MainController.CreateRoomAsync(RoomType, Password);
if (roomid != "" && roomid != "-1") if (roomid != "" && roomid != "-1")
{ {
await MainController.UpdateRoom(); await MainController.UpdateRoomAsync();
Room r = GetRoom(roomid); Room r = GetRoom(roomid);
await MainController.IntoRoom(r); await InvokeController_IntoRoom(r);
SetRoomid(r); SetRoomid(r);
InRoom(); InRoom();
WritelnGameInfo(DateTimeUtility.GetNowShortTime() + " 创建" + RoomType + "房间"); WritelnGameInfo(DateTimeUtility.GetNowShortTime() + " 创建" + RoomType + "房间");
WritelnGameInfo(">> 创建" + RoomType + "房间成功!房间号: " + roomid); WritelnGameInfo(">> 创建" + RoomType + "房间成功!房间号: " + roomid);
ShowMessage.Message("创建" + RoomType + "房间成功!\n房间号是 -> [ " + roomid + " ]", "创建成功"); ShowMessage(ShowMessageType.General, "创建" + RoomType + "房间成功!\n房间号是 -> [ " + roomid + " ]", "创建成功");
return; return;
} }
} }
ShowMessage.Message("创建" + RoomType + "房间失败!", "创建失败"); ShowMessage(ShowMessageType.General, "创建" + RoomType + "房间失败!", "创建失败");
} }
/// <summary> /// <summary>
@ -796,9 +791,9 @@ namespace Milimoe.FunGame.Desktop.UI
if (MainController != null) if (MainController != null)
{ {
// 获取在线的房间列表 // 获取在线的房间列表
await MainController.UpdateRoom(); await MainController.UpdateRoomAsync();
// 接入-1号房间聊天室 // 接入-1号房间聊天室
await MainController.IntoRoom((Room)Rooms["-1"]!); await InvokeController_IntoRoom(Rooms["-1"] ?? General.HallInstance);
} }
} }
@ -867,10 +862,11 @@ namespace Milimoe.FunGame.Desktop.UI
/// </summary> /// </summary>
private async Task ExitFunGame() private async Task ExitFunGame()
{ {
if (ShowMessage.OKCancelMessage("你确定关闭游戏?", "退出") == (int)MessageResult.OK) if (ShowMessage(ShowMessageType.OKCancel, "你确定关闭游戏?", "退出") == MessageResult.OK)
{ {
if (MainController != null) await MainController.LogOut(); if (MainController != null) await LogOut();
RunTime.Controller?.Close(); RunTime.Controller?.Close();
RunTime.Controller?.Dispose();
Environment.Exit(0); Environment.Exit(0);
} }
} }
@ -884,9 +880,9 @@ namespace Milimoe.FunGame.Desktop.UI
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private async void Exit_Click(object sender, EventArgs e) private void Exit_Click(object sender, EventArgs e)
{ {
await ExitFunGame(); TaskUtility.StartAndAwaitTask(ExitFunGame);
} }
/// <summary> /// <summary>
@ -931,29 +927,29 @@ namespace Milimoe.FunGame.Desktop.UI
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private async void CreateRoom_Click(object sender, EventArgs e) private void CreateRoom_Click(object sender, EventArgs e)
{ {
string password = ""; string password = "";
if (CheckMix.Checked && CheckTeam.Checked) if (CheckMix.Checked && CheckTeam.Checked)
{ {
ShowMessage.WarningMessage("创建房间不允许同时勾选混战和团队!"); ShowMessage(ShowMessageType.Warning, "创建房间不允许同时勾选混战和团队!");
return; return;
} }
if (CheckHasPass.Checked) if (CheckHasPass.Checked)
{ {
password = ShowMessage.InputMessage("请输入该房间的密码:", "创建密码房间").Trim(); password = ShowInputMessage("请输入该房间的密码:", "创建密码房间").Trim();
if (password == "" || password.Length > 10) if (password == "" || password.Length > 10)
{ {
ShowMessage.WarningMessage("密码无效密码不能为空或大于10个字符。"); ShowMessage(ShowMessageType.Warning, "密码无效密码不能为空或大于10个字符。");
return; return;
} }
} }
if (Config.FunGame_GameMode.Equals("")) if (Config.FunGame_GameMode.Equals(""))
{ {
ShowMessage.WarningMessage("请勾选你要创建的房间类型!"); ShowMessage(ShowMessageType.Warning, "请勾选你要创建的房间类型!");
return; return;
} }
await CreateRoom_Handler(Config.FunGame_GameMode, password); TaskUtility.StartAndAwaitTask(() => CreateRoom_Handler(Config.FunGame_GameMode, password));
} }
/// <summary> /// <summary>
@ -961,22 +957,25 @@ namespace Milimoe.FunGame.Desktop.UI
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private async void QuitRoom_Click(object sender, EventArgs e) private void QuitRoom_Click(object sender, EventArgs e)
{
if (MainController != null)
{ {
string roomid = Usercfg.InRoom.Roomid; string roomid = Usercfg.InRoom.Roomid;
bool isMaster = Usercfg.InRoom.RoomMaster?.Id == Usercfg.LoginUser.Id; bool isMaster = Usercfg.InRoom.RoomMaster?.Id == Usercfg.LoginUser.Id;
if (await MainController.QuitRoom(Usercfg.InRoom, isMaster)) bool result = false;
TaskUtility.StartAndAwaitTask(async () =>
{
if (await InvokeController_QuitRoom(Usercfg.InRoom, isMaster))
{ {
WritelnGameInfo(DateTimeUtility.GetNowShortTime() + " 离开房间"); WritelnGameInfo(DateTimeUtility.GetNowShortTime() + " 离开房间");
WritelnGameInfo("[ " + Usercfg.LoginUserName + " ] 已离开房间 -> [ " + roomid + " ]"); WritelnGameInfo("[ " + Usercfg.LoginUserName + " ] 已离开房间 -> [ " + roomid + " ]");
InMain(); InMain();
_ = MainController.UpdateRoom(); _ = MainController?.UpdateRoomAsync();
return; result = true;
} }
} }).OnCompleted(() =>
ShowMessage.ErrorMessage("无法退出房间!", "退出房间"); {
if (!result) ShowMessage(ShowMessageType.Error, "无法退出房间!", "退出房间");
});
} }
/// <summary> /// <summary>
@ -997,7 +996,7 @@ namespace Milimoe.FunGame.Desktop.UI
private void CopyRoomID_Click(object sender, EventArgs e) private void CopyRoomID_Click(object sender, EventArgs e)
{ {
Clipboard.SetDataObject(Usercfg.InRoom.Roomid); Clipboard.SetDataObject(Usercfg.InRoom.Roomid);
ShowMessage.TipMessage("已复制房间号到剪贴板"); ShowMessage(ShowMessageType.Tip, "已复制房间号到剪贴板");
} }
/// <summary> /// <summary>
@ -1005,9 +1004,9 @@ namespace Milimoe.FunGame.Desktop.UI
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private async void QueryRoom_Click(object sender, EventArgs e) private void QueryRoom_Click(object sender, EventArgs e)
{ {
await JoinRoom(false, RoomText.Text); TaskUtility.StartAndAwaitTask(async() => await JoinRoom(false, RoomText.Text));
} }
/// <summary> /// <summary>
@ -1015,13 +1014,16 @@ namespace Milimoe.FunGame.Desktop.UI
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private async void Logout_Click(object sender, EventArgs e) private void Logout_Click(object sender, EventArgs e)
{ {
if (ShowMessage.OKCancelMessage("你确定要退出登录吗?", "退出登录") == MessageResult.OK) TaskUtility.StartAndAwaitTask(async () =>
{ {
if (MainController == null || !await MainController.LogOut()) if (ShowMessage(ShowMessageType.OKCancel, "你确定要退出登录吗?", "退出登录") == MessageResult.OK)
ShowMessage.WarningMessage("请求无效:退出登录失败!"); {
if (MainController == null || !await LogOut())
ShowMessage(ShowMessageType.Warning, "请求无效:退出登录失败!");
} }
});
} }
/// <summary> /// <summary>
@ -1034,7 +1036,7 @@ namespace Milimoe.FunGame.Desktop.UI
if (MainController != null && Config.FunGame_isConnected) if (MainController != null && Config.FunGame_isConnected)
OpenForm.SingleForm(FormType.Login, OpenFormType.Dialog); OpenForm.SingleForm(FormType.Login, OpenFormType.Dialog);
else else
ShowMessage.WarningMessage("请先连接服务器!"); ShowMessage(ShowMessageType.Warning, "请先连接服务器!");
} }
/// <summary> /// <summary>
@ -1052,11 +1054,11 @@ namespace Milimoe.FunGame.Desktop.UI
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private async void RoomList_MouseDoubleClick(object sender, MouseEventArgs e) private void RoomList_MouseDoubleClick(object sender, MouseEventArgs e)
{ {
if (RoomList.SelectedItem != null) if (RoomList.SelectedItem != null)
{ {
await JoinRoom(true, RoomList.SelectedItem.ToString() ?? ""); TaskUtility.StartAndAwaitTask(async() => await JoinRoom(true, RoomList.SelectedItem.ToString() ?? ""));
} }
} }
@ -1065,9 +1067,9 @@ namespace Milimoe.FunGame.Desktop.UI
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private async void SendTalkText_Click(object sender, EventArgs e) private void SendTalkText_Click(object sender, EventArgs e)
{ {
await SendTalkText_Click(true); SendTalkText_Click(true);
} }
/// <summary> /// <summary>
@ -1122,13 +1124,13 @@ namespace Milimoe.FunGame.Desktop.UI
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private async void RoomText_KeyUp(object sender, KeyEventArgs e) private void RoomText_KeyUp(object sender, KeyEventArgs e)
{ {
RoomText.ForeColor = Color.Black; RoomText.ForeColor = Color.Black;
if (e.KeyCode.Equals(Keys.Enter)) if (e.KeyCode.Equals(Keys.Enter))
{ {
// 按下回车加入房间 // 按下回车加入房间
await JoinRoom(false, RoomText.Text); TaskUtility.StartAndAwaitTask(async() => await JoinRoom(false, RoomText.Text));
} }
} }
@ -1161,13 +1163,13 @@ namespace Milimoe.FunGame.Desktop.UI
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private async void TalkText_KeyUp(object sender, KeyEventArgs e) private void TalkText_KeyUp(object sender, KeyEventArgs e)
{ {
TalkText.ForeColor = Color.Black; TalkText.ForeColor = Color.Black;
if (e.KeyCode.Equals(Keys.Enter)) if (e.KeyCode.Equals(Keys.Enter))
{ {
// 按下回车发送 // 按下回车发送
await SendTalkText_Click(false); SendTalkText_Click(false);
} }
} }
@ -1187,14 +1189,14 @@ namespace Milimoe.FunGame.Desktop.UI
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
private async void PresetText_SelectedIndexChanged(object sender, EventArgs e) private void PresetText_SelectedIndexChanged(object sender, EventArgs e)
{ {
// 发送快捷消息并执行功能 // 发送快捷消息并执行功能
if (PresetText.SelectedIndex != 0) if (PresetText.SelectedIndex != 0)
{ {
string s = PresetText.SelectedItem.ToString() ?? ""; string s = PresetText.SelectedItem.ToString() ?? "";
SendTalkText_Click(s); SendTalkText_Click(s);
await SwitchTalkMessage(s); SwitchTalkMessage(s);
PresetText.SelectedIndex = 0; PresetText.SelectedIndex = 0;
} }
} }
@ -1223,7 +1225,7 @@ namespace Milimoe.FunGame.Desktop.UI
Task.Run(() => Task.Run(() =>
{ {
Thread.Sleep(5000); Thread.Sleep(5000);
if (Config.FunGame_isConnected && Config.FunGame_isAutoRetry) RunTime.Controller?.Connect(); // 再次判断是否开启自动重连 if (Config.FunGame_isConnected && Config.FunGame_isAutoRetry) InvokeController_Connect(); // 再次判断是否开启自动重连
}); });
GetMessage("连接服务器失败5秒后自动尝试重连。"); GetMessage("连接服务器失败5秒后自动尝试重连。");
} }
@ -1244,7 +1246,7 @@ namespace Milimoe.FunGame.Desktop.UI
if (MainController != null && Config.FunGame_isAutoLogin && Config.FunGame_AutoLoginUser != "" && Config.FunGame_AutoLoginPassword != "" && Config.FunGame_AutoLoginKey != "") if (MainController != null && Config.FunGame_isAutoLogin && Config.FunGame_AutoLoginUser != "" && Config.FunGame_AutoLoginPassword != "" && Config.FunGame_AutoLoginKey != "")
{ {
// 自动登录 // 自动登录
_ = RunTime.Controller?.AutoLogin(Config.FunGame_AutoLoginUser, Config.FunGame_AutoLoginPassword, Config.FunGame_AutoLoginKey); RunTime.Controller?.AutoLogin(Config.FunGame_AutoLoginUser, Config.FunGame_AutoLoginPassword, Config.FunGame_AutoLoginKey);
} }
return EventResult.Success; return EventResult.Success;
} }
@ -1257,7 +1259,7 @@ namespace Milimoe.FunGame.Desktop.UI
/// <returns></returns> /// <returns></returns>
private EventResult SucceedLoginEvent(object sender, GeneralEventArgs e) private EventResult SucceedLoginEvent(object sender, GeneralEventArgs e)
{ {
_ = SucceedLoginEvent_Handler(); TaskUtility.StartAndAwaitTask(SucceedLoginEvent_Handler);
return EventResult.Success; return EventResult.Success;
} }
@ -1287,7 +1289,7 @@ namespace Milimoe.FunGame.Desktop.UI
/// 判断快捷消息 /// 判断快捷消息
/// </summary> /// </summary>
/// <param name="s"></param> /// <param name="s"></param>
private async Task<bool> SwitchTalkMessage(string s) private bool SwitchTalkMessage(string s)
{ {
switch (s) switch (s)
{ {
@ -1303,10 +1305,10 @@ namespace Milimoe.FunGame.Desktop.UI
GameInfo.Clear(); GameInfo.Clear();
break; break;
case Constant.FunGame_CreateMix: case Constant.FunGame_CreateMix:
await CreateRoom_Handler(GameMode.GameMode_Mix); TaskUtility.StartAndAwaitTask(() => CreateRoom_Handler(GameMode.GameMode_Mix));
break; break;
case Constant.FunGame_CreateTeam: case Constant.FunGame_CreateTeam:
await CreateRoom_Handler(GameMode.GameMode_Team); TaskUtility.StartAndAwaitTask(() => CreateRoom_Handler(GameMode.GameMode_Team));
break; break;
case Constant.FunGame_StartGame: case Constant.FunGame_StartGame:
break; break;
@ -1323,7 +1325,7 @@ namespace Milimoe.FunGame.Desktop.UI
{ {
CurrentRetryTimes = -1; CurrentRetryTimes = -1;
Config.FunGame_isAutoRetry = true; Config.FunGame_isAutoRetry = true;
RunTime.Controller?.Connect(); InvokeController_Connect();
} }
else else
WritelnGameInfo(">> 你不能在连接服务器的同时重试连接!"); WritelnGameInfo(">> 你不能在连接服务器的同时重试连接!");
@ -1333,24 +1335,31 @@ namespace Milimoe.FunGame.Desktop.UI
{ {
CurrentRetryTimes = -1; CurrentRetryTimes = -1;
Config.FunGame_isAutoRetry = true; Config.FunGame_isAutoRetry = true;
RunTime.Controller?.Connect(); InvokeController_Connect();
} }
break; break;
case Constant.FunGame_Disconnect: case Constant.FunGame_Disconnect:
if (Config.FunGame_isConnected && MainController != null) if (Config.FunGame_isConnected && MainController != null)
{ {
// 先退出登录再断开连接 // 先退出登录再断开连接
if (MainController != null && await MainController.LogOut()) RunTime.Controller?.Disconnect(); bool SuccessLogOut = false;
TaskUtility.StartAndAwaitTask(async() =>
{
if (await LogOut()) SuccessLogOut = true;
}).OnCompleted(() =>
{
if (SuccessLogOut) InvokeController_Disconnect();
});
} }
break; break;
case Constant.FunGame_DisconnectWhenNotLogin: case Constant.FunGame_DisconnectWhenNotLogin:
if (Config.FunGame_isConnected && MainController != null) if (Config.FunGame_isConnected && MainController != null)
{ {
RunTime.Controller?.Disconnect(); InvokeController_Disconnect();
} }
break; break;
case Constant.FunGame_ConnectTo: case Constant.FunGame_ConnectTo:
string msg = ShowMessage.InputMessage("请输入服务器IP地址和端口号如: 127.0.0.1:22222。", "连接指定服务器"); string msg = ShowInputMessage("请输入服务器IP地址和端口号如: 127.0.0.1:22222。", "连接指定服务器");
if (msg.Equals("")) return true; if (msg.Equals("")) return true;
string[] addr = msg.Split(':'); string[] addr = msg.Split(':');
string ip; string ip;
@ -1367,7 +1376,7 @@ namespace Milimoe.FunGame.Desktop.UI
} }
else else
{ {
ShowMessage.ErrorMessage("格式错误!\n这不是一个服务器地址。"); ShowMessage(ShowMessageType.Error, "格式错误!\n这不是一个服务器地址。");
return true; return true;
} }
ErrorIPAddressType ErrorType = NetworkUtility.IsServerAddress(ip, port); ErrorIPAddressType ErrorType = NetworkUtility.IsServerAddress(ip, port);
@ -1377,11 +1386,11 @@ namespace Milimoe.FunGame.Desktop.UI
RunTime.Session.Server_Port = port; RunTime.Session.Server_Port = port;
CurrentRetryTimes = -1; CurrentRetryTimes = -1;
Config.FunGame_isAutoRetry = true; Config.FunGame_isAutoRetry = true;
RunTime.Controller?.Connect(); InvokeController_Connect();
} }
else if (ErrorType == Core.Library.Constant.ErrorIPAddressType.IsNotIP) ShowMessage.ErrorMessage("这不是一个IP地址"); else if (ErrorType == Core.Library.Constant.ErrorIPAddressType.IsNotIP) ShowMessage(ShowMessageType.Error, "这不是一个IP地址");
else if (ErrorType == Core.Library.Constant.ErrorIPAddressType.IsNotPort) ShowMessage.ErrorMessage("这不是一个端口号!\n正确范围1~65535"); else if (ErrorType == Core.Library.Constant.ErrorIPAddressType.IsNotPort) ShowMessage(ShowMessageType.Error, "这不是一个端口号!\n正确范围1~65535");
else ShowMessage.ErrorMessage("格式错误!\n这不是一个服务器地址。"); else ShowMessage(ShowMessageType.Error, "格式错误!\n这不是一个服务器地址。");
break; break;
default: default:
break; break;
@ -1390,5 +1399,157 @@ namespace Milimoe.FunGame.Desktop.UI
} }
#endregion #endregion
#region
/// <summary>
/// 连接服务器,并处理事件
/// </summary>
/// <returns></returns>
private void InvokeController_Connect()
{
try
{
ConnectEventArgs EventArgs = new(RunTime.Session.Server_IP, RunTime.Session.Server_Port);
ConnectResult result = ConnectResult.CanNotConnect;
TaskUtility.StartAndAwaitTask(() =>
{
if (OnBeforeConnectEvent(EventArgs) == EventResult.Fail) return;
result = RunTime.Controller?.Connect() ?? result;
EventArgs.ConnectResult = result;
}).OnCompleted(() =>
{
if (result == ConnectResult.Success) OnSucceedConnectEvent(EventArgs);
else OnFailedConnectEvent(EventArgs);
OnAfterConnectEvent(EventArgs);
});
}
catch (Exception e)
{
GetMessage(e.GetErrorInfo(), TimeType.None);
}
}
/// <summary>
/// 断开服务器的连接,并处理事件
/// </summary>
/// <returns></returns>
public void InvokeController_Disconnect()
{
try
{
bool result = false;
TaskUtility.StartAndAwaitTask(() =>
{
if (OnBeforeDisconnectEvent(new GeneralEventArgs()) == EventResult.Fail) return;
result = RunTime.Controller?.Disconnect() ?? false;
}).OnCompleted(() =>
{
if (result) OnSucceedDisconnectEvent(new GeneralEventArgs());
else OnFailedDisconnectEvent(new GeneralEventArgs());
OnAfterDisconnectEvent(new GeneralEventArgs());
});
}
catch (Exception e)
{
GetMessage(e.GetErrorInfo(), TimeType.None);
}
}
/// <summary>
/// 进入房间
/// </summary>
/// <param name="room"></param>
/// <returns></returns>
public async Task<bool> InvokeController_IntoRoom(Room room)
{
bool result = false;
try
{
RoomEventArgs EventArgs = new(room);
if (OnBeforeIntoRoomEvent(EventArgs) == EventResult.Fail) return result;
result = MainController is not null && await MainController.IntoRoomAsync(room);
if (result) OnSucceedIntoRoomEvent(EventArgs);
else OnFailedIntoRoomEvent(EventArgs);
OnAfterIntoRoomEvent(EventArgs);
}
catch (Exception e)
{
GetMessage(e.GetErrorInfo(), TimeType.None);
}
return result;
}
/// <summary>
/// 退出房间
/// </summary>
/// <param name="roomid"></param>
/// <returns></returns>
public async Task<bool> InvokeController_QuitRoom(Room room, bool isMaster)
{
bool result = false;
try
{
RoomEventArgs EventArgs = new(room);
if (OnBeforeIntoRoomEvent(EventArgs) == EventResult.Fail) return result;
result = MainController is not null && await MainController.QuitRoomAsync(room.Roomid, isMaster);
if (result) OnSucceedIntoRoomEvent(EventArgs);
else OnFailedIntoRoomEvent(EventArgs);
OnAfterIntoRoomEvent(EventArgs);
}
catch (Exception e)
{
GetMessage(e.GetErrorInfo(), TimeType.None);
}
return result;
}
/// <summary>
/// 退出登录
/// </summary>
/// <returns></returns>
public async Task<bool> LogOut()
{
bool result = false;
try
{
GeneralEventArgs EventArgs = new();
if (OnBeforeLogoutEvent(EventArgs) == EventResult.Fail) return result;
if (Usercfg.LoginUser.Id == 0) return result;
if (Usercfg.InRoom.Roomid != "-1")
{
string roomid = Usercfg.InRoom.Roomid;
bool isMaster = Usercfg.InRoom.RoomMaster?.Id == Usercfg.LoginUser?.Id;
MainController?.QuitRoomAsync(roomid, isMaster);
}
result = MainController is not null && await MainController.LogOutAsync();
if (result) OnSucceedLogoutEvent(EventArgs);
else OnFailedLogoutEvent(EventArgs);
OnAfterLogoutEvent(EventArgs);
}
catch (Exception e)
{
GetMessage(e.GetErrorInfo(), TimeType.None);
}
return result;
}
#endregion
} }
} }

View File

@ -5,7 +5,6 @@ using Milimoe.FunGame.Core.Library.Exception;
using Milimoe.FunGame.Desktop.Controller; using Milimoe.FunGame.Desktop.Controller;
using Milimoe.FunGame.Desktop.Library; using Milimoe.FunGame.Desktop.Library;
using Milimoe.FunGame.Desktop.Library.Base; using Milimoe.FunGame.Desktop.Library.Base;
using Milimoe.FunGame.Desktop.Library.Component;
namespace Milimoe.FunGame.Desktop.UI namespace Milimoe.FunGame.Desktop.UI
{ {
@ -14,25 +13,21 @@ namespace Milimoe.FunGame.Desktop.UI
public bool CheckReg { get; set; } = false; public bool CheckReg { get; set; } = false;
private readonly RegisterController RegController; private readonly RegisterController RegController;
private readonly LoginController LoginController;
public Register() public Register()
{ {
InitializeComponent(); InitializeComponent();
RegController = new RegisterController(this); RegController = new RegisterController(this);
LoginController = new(this);
} }
protected override void BindEvent() protected override void BindEvent()
{ {
base.BindEvent(); base.BindEvent();
Disposed += Register_Disposed;
SucceedReg += SucceedRegEvent; SucceedReg += SucceedRegEvent;
} }
private void Register_Disposed(object? sender, EventArgs e)
{
RegController.Dispose();
}
private async Task<bool> Reg_Handler() private async Task<bool> Reg_Handler()
{ {
try try
@ -50,21 +45,21 @@ namespace Milimoe.FunGame.Desktop.UI
{ {
if (password != checkpassword) if (password != checkpassword)
{ {
ShowMessage.ErrorMessage("两个密码不相同,请重新输入!"); ShowMessage(ShowMessageType.Error, "两个密码不相同,请重新输入!");
CheckPasswordText.Focus(); CheckPasswordText.Focus();
return false; return false;
} }
} }
else else
{ {
ShowMessage.ErrorMessage("账号名长度不符合要求最多6个中文字符或12个英文字符"); ShowMessage(ShowMessageType.Error, "账号名长度不符合要求最多6个中文字符或12个英文字符");
UsernameText.Focus(); UsernameText.Focus();
return false; return false;
} }
} }
else else
{ {
ShowMessage.ErrorMessage("账号名不符合要求:不能包含特殊字符"); ShowMessage(ShowMessageType.Error, "账号名不符合要求:不能包含特殊字符");
UsernameText.Focus(); UsernameText.Focus();
return false; return false;
} }
@ -74,30 +69,30 @@ namespace Milimoe.FunGame.Desktop.UI
int length = password.Length; int length = password.Length;
if (length < 6 || length > 15) // 字节范围 3~12 if (length < 6 || length > 15) // 字节范围 3~12
{ {
ShowMessage.ErrorMessage("密码长度不符合要求6~15个字符数"); ShowMessage(ShowMessageType.Error, "密码长度不符合要求6~15个字符数");
PasswordText.Focus(); PasswordText.Focus();
return false; return false;
} }
} }
if (username == "" || password == "" || checkpassword == "") if (username == "" || password == "" || checkpassword == "")
{ {
ShowMessage.ErrorMessage("请将账号和密码填写完整!"); ShowMessage(ShowMessageType.Error, "请将账号和密码填写完整!");
UsernameText.Focus(); UsernameText.Focus();
return false; return false;
} }
if (email == "") if (email == "")
{ {
ShowMessage.ErrorMessage("邮箱不能为空!"); ShowMessage(ShowMessageType.Error, "邮箱不能为空!");
EmailText.Focus(); EmailText.Focus();
return false; return false;
} }
if (!NetworkUtility.IsEmail(email)) if (!NetworkUtility.IsEmail(email))
{ {
ShowMessage.ErrorMessage("这不是一个邮箱地址!"); ShowMessage(ShowMessageType.Error, "这不是一个邮箱地址!");
EmailText.Focus(); EmailText.Focus();
return false; return false;
} }
return await RegController.Reg(username, password, email); return await RegController.RegAsync(username, password, email);
} }
catch (Exception e) catch (Exception e)
{ {
@ -120,7 +115,7 @@ namespace Milimoe.FunGame.Desktop.UI
{ {
string username = ((RegisterEventArgs)e).Username; string username = ((RegisterEventArgs)e).Username;
string password = ((RegisterEventArgs)e).Password; string password = ((RegisterEventArgs)e).Password;
_ = LoginController.LoginAccount(username, password); TaskUtility.StartAndAwaitTask(async () => await LoginController.LoginAccountAsync(username, password)).OnCompleted(LoginController.Dispose);
RunTime.Login?.Close(); RunTime.Login?.Close();
return EventResult.Success; return EventResult.Success;
} }