From c24ec3076ffc9637dab8c664b2309fb8287c3ff7 Mon Sep 17 00:00:00 2001 From: sheychen Date: Sun, 30 Oct 2016 15:15:27 +0100 Subject: [PATCH 01/11] Add Common project and AssemblyInfo --- AssemblyInfoCommon.cs | 23 +++++++ Galactic Colors Control Common/Common.cs | 13 ++++ .../Galactic Colors Control Common.csproj | 61 +++++++++++++++++++ .../Properties/AssemblyInfo.cs | 21 +++++++ .../Galactic Colors Control Console.csproj | 3 + .../Properties/AssemblyInfo.cs | 15 ----- .../Galactic Colors Control GUI.csproj | 3 + .../Properties/AssemblyInfo.cs | 15 ----- .../Commands/ConnectCommand.cs | 9 +-- .../Commands/ExitCommand.cs | 5 +- .../Commands/KickCommand.cs | 7 ++- .../Galactic Colors Control Server.csproj | 9 +++ Galactic Colors Control Server/Program.cs | 19 +++--- .../Properties/AssemblyInfo.cs | 15 ----- Galactic Colors Control Server/Utilities.cs | 15 +++-- Galactic Colors Control.sln | 21 +++++++ .../Galactic Colors Control.csproj | 9 +++ Galactic Colors Control/Program.cs | 21 +++---- .../Properties/AssemblyInfo.cs | 17 +----- 19 files changed, 203 insertions(+), 98 deletions(-) create mode 100644 AssemblyInfoCommon.cs create mode 100644 Galactic Colors Control Common/Common.cs create mode 100644 Galactic Colors Control Common/Galactic Colors Control Common.csproj create mode 100644 Galactic Colors Control Common/Properties/AssemblyInfo.cs diff --git a/AssemblyInfoCommon.cs b/AssemblyInfoCommon.cs new file mode 100644 index 0000000..611a11f --- /dev/null +++ b/AssemblyInfoCommon.cs @@ -0,0 +1,23 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +//Common AssemblyInfo +// Les informations générales relatives à un assembly dépendent de +// l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations +// associées à un assembly. +[assembly: AssemblyCompany("sheychen")] +[assembly: AssemblyCopyright("Copyright © 2016")] + +// Les informations de version pour un assembly se composent des quatre valeurs suivantes : +// +// Version principale +// Version secondaire +// Numéro de build +// Révision +// +// Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de build et de révision par défaut +// en utilisant '*', comme indiqué ci-dessous : +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.1.1")] +[assembly: AssemblyFileVersion("1.0.1.1")] \ No newline at end of file diff --git a/Galactic Colors Control Common/Common.cs b/Galactic Colors Control Common/Common.cs new file mode 100644 index 0000000..97708c3 --- /dev/null +++ b/Galactic Colors Control Common/Common.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Galactic_Colors_Control_Common +{ + public static class Common + { + public enum dataType { message, data }; + } +} diff --git a/Galactic Colors Control Common/Galactic Colors Control Common.csproj b/Galactic Colors Control Common/Galactic Colors Control Common.csproj new file mode 100644 index 0000000..1c29985 --- /dev/null +++ b/Galactic Colors Control Common/Galactic Colors Control Common.csproj @@ -0,0 +1,61 @@ + + + + + Debug + AnyCPU + {022A69CE-22B5-4934-BE9F-A9C6DF9557ED} + Library + Properties + Galactic_Colors_Control_Common + Galactic Colors Control Common + v4.5 + 512 + + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + Properties\AssemblyInfoCommon.cs + + + + + + + \ No newline at end of file diff --git a/Galactic Colors Control Common/Properties/AssemblyInfo.cs b/Galactic Colors Control Common/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..93e8d18 --- /dev/null +++ b/Galactic Colors Control Common/Properties/AssemblyInfo.cs @@ -0,0 +1,21 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// Les informations générales relatives à un assembly dépendent de +// l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations +// associées à un assembly. +[assembly: AssemblyTitle("Galactic Colors Control Common")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyProduct("Galactic Colors Control Common")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly +// aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de +// COM, affectez la valeur true à l'attribut ComVisible sur ce type. +[assembly: ComVisible(false)] + +// Le GUID suivant est pour l'ID de la typelib si ce projet est exposé à COM +[assembly: Guid("022a69ce-22b5-4934-be9f-a9c6df9557ed")] diff --git a/Galactic Colors Control Console/Galactic Colors Control Console.csproj b/Galactic Colors Control Console/Galactic Colors Control Console.csproj index 276d774..7f677b3 100644 --- a/Galactic Colors Control Console/Galactic Colors Control Console.csproj +++ b/Galactic Colors Control Console/Galactic Colors Control Console.csproj @@ -44,6 +44,9 @@ + + Properties\AssemblyInfoCommon.cs + diff --git a/Galactic Colors Control Console/Properties/AssemblyInfo.cs b/Galactic Colors Control Console/Properties/AssemblyInfo.cs index 4a2e9d8..c85bccf 100644 --- a/Galactic Colors Control Console/Properties/AssemblyInfo.cs +++ b/Galactic Colors Control Console/Properties/AssemblyInfo.cs @@ -8,9 +8,7 @@ using System.Runtime.InteropServices; [assembly: AssemblyTitle("Galactic Colors Control Console")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("sheychen")] [assembly: AssemblyProduct("Galactic Colors Control Console")] -[assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] @@ -21,16 +19,3 @@ using System.Runtime.InteropServices; // Le GUID suivant est pour l'ID de la typelib si ce projet est exposé à COM [assembly: Guid("5d6a09d1-dcab-4fd8-b4e6-62d9f41ae8f0")] - -// Les informations de version pour un assembly se composent des quatre valeurs suivantes : -// -// Version principale -// Version secondaire -// Numéro de build -// Révision -// -// Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de build et de révision par défaut -// en utilisant '*', comme indiqué ci-dessous : -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.1.1")] -[assembly: AssemblyFileVersion("1.0.1.1")] diff --git a/Galactic Colors Control GUI/Galactic Colors Control GUI.csproj b/Galactic Colors Control GUI/Galactic Colors Control GUI.csproj index 8a5784c..fb69eef 100644 --- a/Galactic Colors Control GUI/Galactic Colors Control GUI.csproj +++ b/Galactic Colors Control GUI/Galactic Colors Control GUI.csproj @@ -41,6 +41,9 @@ + + Properties\AssemblyInfoCommon.cs + diff --git a/Galactic Colors Control GUI/Properties/AssemblyInfo.cs b/Galactic Colors Control GUI/Properties/AssemblyInfo.cs index 66c2d21..1ad66d6 100644 --- a/Galactic Colors Control GUI/Properties/AssemblyInfo.cs +++ b/Galactic Colors Control GUI/Properties/AssemblyInfo.cs @@ -9,8 +9,6 @@ using System.Runtime.InteropServices; [assembly: AssemblyProduct("Galactic Colors Control GUI")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyDescription("")] -[assembly: AssemblyCompany("sheychen")] -[assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] @@ -21,16 +19,3 @@ using System.Runtime.InteropServices; // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("606d35be-02e8-4a7e-978e-04c2aca6ccd7")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.1.1")] -[assembly: AssemblyFileVersion("1.0.1.1")] diff --git a/Galactic Colors Control Server/Commands/ConnectCommand.cs b/Galactic Colors Control Server/Commands/ConnectCommand.cs index 03e36ce..a23009c 100644 --- a/Galactic Colors Control Server/Commands/ConnectCommand.cs +++ b/Galactic Colors Control Server/Commands/ConnectCommand.cs @@ -1,6 +1,7 @@ using System; using System.Net; using System.Net.Sockets; +using Galactic_Colors_Control_Common; namespace Galactic_Colors_Control_Server.Commands { @@ -31,18 +32,18 @@ namespace Galactic_Colors_Control_Server.Commands Program.clients[soc].status = 0; //args[1] = args[1][0].ToString().ToUpper()[0] + args[1].Substring(1); Program.clients[soc].pseudo = args[1]; - Utilities.Send(soc, "/connected", Utilities.dataType.message); - Utilities.Broadcast(args[1] + " joined the server", Utilities.dataType.message); + Utilities.Send(soc, "/connected", Common.dataType.message); + Utilities.Broadcast(args[1] + " joined the server", Common.dataType.message); Logger.Write("Identified as " + Utilities.GetName(soc) + " form " + ((IPEndPoint)soc.LocalEndPoint).Address.ToString(), Logger.logType.info); } else { - Utilities.Send(soc, "/allreadytaken", Utilities.dataType.message); + Utilities.Send(soc, "/allreadytaken", Common.dataType.message); } } else { - Utilities.Send(soc, "You are allready " + Utilities.GetName(soc), Utilities.dataType.message); + Utilities.Send(soc, "You are allready " + Utilities.GetName(soc), Common.dataType.message); } } } diff --git a/Galactic Colors Control Server/Commands/ExitCommand.cs b/Galactic Colors Control Server/Commands/ExitCommand.cs index 55be0bb..7c9e617 100644 --- a/Galactic Colors Control Server/Commands/ExitCommand.cs +++ b/Galactic Colors Control Server/Commands/ExitCommand.cs @@ -1,4 +1,5 @@ -using System; +using Galactic_Colors_Control_Common; +using System; using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands @@ -30,7 +31,7 @@ namespace Galactic_Colors_Control_Server.Commands bool connected = Program.clients[soc].status != -1; soc.Close(); Program.clients.Remove(soc); - if (connected) { Utilities.Broadcast(username + " leave the server", Utilities.dataType.message); } + if (connected) { Utilities.Broadcast(username + " leave the server", Common.dataType.message); } Logger.Write("Size: " + Program.clients.Count + "/" + Program.config.size, Logger.logType.debug); } } diff --git a/Galactic Colors Control Server/Commands/KickCommand.cs b/Galactic Colors Control Server/Commands/KickCommand.cs index ac7a75b..2c3e0f7 100644 --- a/Galactic Colors Control Server/Commands/KickCommand.cs +++ b/Galactic Colors Control Server/Commands/KickCommand.cs @@ -1,4 +1,5 @@ -using System; +using Galactic_Colors_Control_Common; +using System; using System.Collections.Generic; using System.Linq; using System.Net.Sockets; @@ -29,11 +30,11 @@ namespace Galactic_Colors_Control_Server.Commands Logger.Write(args[1] + " was kick by server.", Logger.logType.info); if (args.Length > 2) { - Utilities.Send(target, "/kick " + args[2], Utilities.dataType.message); + Utilities.Send(target, "/kick " + args[2], Common.dataType.message); Logger.Write("because" + args[1], Logger.logType.debug); } else { - Utilities.Send(target, "/kick", Utilities.dataType.message); + Utilities.Send(target, "/kick", Common.dataType.message); } } else diff --git a/Galactic Colors Control Server/Galactic Colors Control Server.csproj b/Galactic Colors Control Server/Galactic Colors Control Server.csproj index 3845bbe..5fab29b 100644 --- a/Galactic Colors Control Server/Galactic Colors Control Server.csproj +++ b/Galactic Colors Control Server/Galactic Colors Control Server.csproj @@ -53,6 +53,9 @@ + + Properties\AssemblyInfoCommon.cs + @@ -94,6 +97,12 @@ false + + + {022a69ce-22b5-4934-be9f-a9c6df9557ed} + Galactic Colors Control Common + + - - - - - - - + + + + + + + \ No newline at end of file diff --git a/Galactic Colors Control GUI/Program.cs b/Galactic Colors Control GUI/Program.cs index 7360770..2a68843 100644 --- a/Galactic Colors Control GUI/Program.cs +++ b/Galactic Colors Control GUI/Program.cs @@ -11,10 +11,10 @@ namespace Galactic_Colors_Control_GUI /// The main entry point for the application. /// [STAThread] - static void Main() + private static void Main() { using (var game = new Game1()) game.Run(); } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control GUI/Properties/AssemblyInfo.cs b/Galactic Colors Control GUI/Properties/AssemblyInfo.cs index 1ad66d6..a5affe2 100644 --- a/Galactic Colors Control GUI/Properties/AssemblyInfo.cs +++ b/Galactic Colors Control GUI/Properties/AssemblyInfo.cs @@ -1,8 +1,7 @@ using System.Reflection; -using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -// General Information about an assembly is controlled through the following +// General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Galactic Colors Control GUI")] @@ -12,10 +11,10 @@ using System.Runtime.InteropServices; [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("606d35be-02e8-4a7e-978e-04c2aca6ccd7")] +[assembly: Guid("606d35be-02e8-4a7e-978e-04c2aca6ccd7")] \ No newline at end of file diff --git a/Galactic Colors Control GUI/Utilities.cs b/Galactic Colors Control GUI/Utilities.cs index c4f6be1..40ae3b0 100644 --- a/Galactic Colors Control GUI/Utilities.cs +++ b/Galactic Colors Control GUI/Utilities.cs @@ -4,7 +4,7 @@ using System.IO; namespace Galactic_Colors_Control_GUI { - static class Utilities + internal static class Utilities { /// /// Load Texture2D from files @@ -38,4 +38,4 @@ namespace Galactic_Colors_Control_GUI } } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/App.config b/Galactic Colors Control Server/App.config index d1428ad..5035d4f 100644 --- a/Galactic Colors Control Server/App.config +++ b/Galactic Colors Control Server/App.config @@ -1,6 +1,6 @@ - - - - + + + + \ No newline at end of file diff --git a/Galactic Colors Control Server/Client.cs b/Galactic Colors Control Server/Client.cs index 12a0522..b20ad5f 100644 --- a/Galactic Colors Control Server/Client.cs +++ b/Galactic Colors Control Server/Client.cs @@ -1,6 +1,4 @@ -using System.Net.Sockets; - -namespace Galactic_Colors_Control_Server +namespace Galactic_Colors_Control_Server { public class Client { diff --git a/Galactic Colors Control Server/Commands/BroadcastCommand.cs b/Galactic Colors Control Server/Commands/BroadcastCommand.cs new file mode 100644 index 0000000..b3df2ff --- /dev/null +++ b/Galactic Colors Control Server/Commands/BroadcastCommand.cs @@ -0,0 +1,26 @@ +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System.Net.Sockets; + +namespace Galactic_Colors_Control_Server.Commands +{ + public class BroadcastCommand : ICommand + { + public string DescText { get { return "Sends message to all clients."; } } + public Manager.CommandGroup Group { get { return Manager.CommandGroup.root; } } + public string HelpText { get { return "Use 'broadcast [text]' to send message to all clients."; } } + public bool IsClient { get { return false; } } + public bool IsClientSide { get { return false; } } + public bool IsNoConnect { get { return false; } } + public bool IsServer { get { return true; } } + public int maxArgs { get { return 1; } } + public int minArgs { get { return 1; } } + public string Name { get { return "broadcast"; } } + + public RequestResult Execute(string[] args, Socket soc, bool server = false) + { + Utilities.Broadcast(new EventData(EventTypes.ChatMessage, Common.Strings("Server : " + args[1]))); + return new RequestResult(ResultTypes.OK); + } + } +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/ClearCommand.cs b/Galactic Colors Control Server/Commands/ClearCommand.cs index 9d204d1..d423891 100644 --- a/Galactic Colors Control Server/Commands/ClearCommand.cs +++ b/Galactic Colors Control Server/Commands/ClearCommand.cs @@ -1,4 +1,6 @@ -using System; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System; using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands @@ -7,7 +9,7 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "clear"; } } public string DescText { get { return "Clears the console screen."; } } - public string HelpText { get { return "Use /clear to execute Console.Clear()."; } } + public string HelpText { get { return "Use 'clear' to execute Console.Clear()."; } } public Manager.CommandGroup Group { get { return Manager.CommandGroup.root; } } public bool IsServer { get { return true; } } public bool IsClient { get { return true; } } @@ -16,10 +18,18 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 0; } } public int maxArgs { get { return 0; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { - Console.Clear(); - Console.Write(">"); + if (server) + { + Console.Clear(); + Console.Write(">"); + return new RequestResult(ResultTypes.OK); + } + else + { + return new RequestResult(ResultTypes.Error, Common.Strings("Client Side")); + } } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Client/CountCommand.cs b/Galactic Colors Control Server/Commands/Client/CountCommand.cs index 54e5d3e..1a32726 100644 --- a/Galactic Colors Control Server/Commands/Client/CountCommand.cs +++ b/Galactic Colors Control Server/Commands/Client/CountCommand.cs @@ -1,4 +1,5 @@ -using System; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands @@ -7,7 +8,7 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "count"; } } public string DescText { get { return "Counts connected clients."; } } - public string HelpText { get { return "Use /client count to show connected clients count and size"; } } + public string HelpText { get { return "Use 'client count' to show connected clients count and size"; } } public Manager.CommandGroup Group { get { return Manager.CommandGroup.client; } } public bool IsServer { get { return true; } } public bool IsClient { get { return true; } } @@ -16,9 +17,9 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 0; } } public int maxArgs { get { return 0; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { - Utilities.Return(Program.clients.Count + "/" + Program.config.size, soc, server); + return new RequestResult(ResultTypes.OK, Common.Strings(Program.clients.Count.ToString(), Program.config.size.ToString())); } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Client/KickCommand.cs b/Galactic Colors Control Server/Commands/Client/KickCommand.cs index 58d1256..6b1e0aa 100644 --- a/Galactic Colors Control Server/Commands/Client/KickCommand.cs +++ b/Galactic Colors Control Server/Commands/Client/KickCommand.cs @@ -1,7 +1,5 @@ using Galactic_Colors_Control_Common; -using System; -using System.Collections.Generic; -using System.Linq; +using Galactic_Colors_Control_Common.Protocol; using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands @@ -10,7 +8,7 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "kick"; } } public string DescText { get { return "Kicks selected client."; } } - public string HelpText { get { return "Use /client kick [username] to kick client from server."; } } + public string HelpText { get { return "Use 'client kick [username] ' to kick client from server."; } } public Manager.CommandGroup Group { get { return Manager.CommandGroup.client; } } public bool IsServer { get { return true; } } public bool IsClient { get { return false; } } @@ -19,29 +17,27 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 1; } } public int maxArgs { get { return 2; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { Socket target = null; - foreach(Socket client in Program.clients.Keys) + foreach (Socket client in Program.clients.Keys) { - if(Utilities.GetName(client) == args[2]) { target = client; } + if (Utilities.GetName(client) == args[2]) { target = client; } } - if (target != null) + if (target == null) + return new RequestResult(ResultTypes.Error, Common.Strings("Can't find")); + + Logger.Write(args[2] + " was kick by server.", Logger.logType.info, Logger.logConsole.show); + if (args.Length > 2) { - Logger.Write(args[2] + " was kick by server.", Logger.logType.info); - if (args.Length > 2) - { - Utilities.Send(target, "/kick " + args[3], Common.dataType.message); - Logger.Write("because" + args[2], Logger.logType.debug); - } - else { - Utilities.Send(target, "/kick", Common.dataType.message); - } + Utilities.Send(target, new EventData(EventTypes.ServerKick, Common.Strings(args[3]))); + Logger.Write("because" + args[3], Logger.logType.debug); } else { - Utilities.Return("Can't find " + args[2], soc, server); + Utilities.Send(target, new EventData(EventTypes.ServerKick)); } + return new RequestResult(ResultTypes.OK); } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Client/ListCommand.cs b/Galactic Colors Control Server/Commands/Client/ListCommand.cs index 2b97c76..dbea879 100644 --- a/Galactic Colors Control Server/Commands/Client/ListCommand.cs +++ b/Galactic Colors Control Server/Commands/Client/ListCommand.cs @@ -1,4 +1,5 @@ -using System; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands @@ -7,7 +8,7 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "list"; } } public string DescText { get { return "Lists connected clients."; } } - public string HelpText { get { return "Use /client list to display all connected client username or IP."; } } + public string HelpText { get { return "Use 'client list' to display all connected client username or IP."; } } public Manager.CommandGroup Group { get { return Manager.CommandGroup.client; } } public bool IsServer { get { return true; } } public bool IsClient { get { return true; } } @@ -16,15 +17,29 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 0; } } public int maxArgs { get { return 0; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { - string text = " "; - foreach (Socket socket in Program.clients.Keys) + if (server) { - text += (Utilities.GetName(socket) + ", "); + string text = " "; + foreach (Socket socket in Program.clients.Keys) + { + text += (Utilities.GetName(socket) + ", "); + } + text = text.Remove(text.Length - 2, 2); + return new RequestResult(ResultTypes.OK, Common.Strings(text)); + } + else + { + string[] data = new string[Program.clients.Count]; + int i = 0; + foreach (Socket socket in Program.clients.Keys) + { + data[i] = (Utilities.GetName(socket) + ", "); + i++; + } + return new RequestResult(ResultTypes.OK, data); } - text = text.Remove(text.Length - 2, 2); - Utilities.Return(text, soc, server); } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Client/StatusCommand.cs b/Galactic Colors Control Server/Commands/Client/StatusCommand.cs index e6a3271..54ef8dc 100644 --- a/Galactic Colors Control Server/Commands/Client/StatusCommand.cs +++ b/Galactic Colors Control Server/Commands/Client/StatusCommand.cs @@ -1,4 +1,5 @@ using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; using System; using System.Net; using System.Net.Sockets; @@ -9,37 +10,33 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "status"; } } public string DescText { get { return "Get client status."; } } - public string HelpText { get { return "Use /client status [username] to show client status."; } } + public string HelpText { get { return "Use 'client status [username]' to show client status."; } } public Manager.CommandGroup Group { get { return Manager.CommandGroup.client; } } public bool IsServer { get { return true; } } public bool IsClient { get { return false; } } public bool IsClientSide { get { return false; } } - public bool IsNoConnect { get { return true; } } + public bool IsNoConnect { get { return false; } } public int minArgs { get { return 1; } } public int maxArgs { get { return 1; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { Socket target = null; foreach (Socket client in Program.clients.Keys) { if (Utilities.GetName(client) == args[2]) { target = client; } } - if (target != null) + if (target == null) + return new RequestResult(ResultTypes.Error, Common.Strings("Can't find")); + + string text = ""; + text += ("Name : " + Utilities.GetName(target) + Environment.NewLine); + text += ("IP : " + ((IPEndPoint)target.LocalEndPoint).Address.ToString() + Environment.NewLine); + if (Program.clients[target].party != null) { - string text = ""; - text += ("Name : " + Utilities.GetName(target) + Environment.NewLine); - text += ("IP : " + ((IPEndPoint)target.LocalEndPoint).Address.ToString() + Environment.NewLine); - if(Program.clients[target].party != null) - { - text += ("Party : " + Program.clients[target].party + Environment.NewLine); - } - Utilities.ConsoleWrite(text); - } - else - { - Utilities.Return("Can't find " + args[2], soc, server); + text += ("Party : " + Program.clients[target].party + Environment.NewLine); } + return new RequestResult(ResultTypes.OK, Common.Strings(text)); } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/ConnectCommand.cs b/Galactic Colors Control Server/Commands/ConnectCommand.cs index 8de0284..7e2ed4d 100644 --- a/Galactic Colors Control Server/Commands/ConnectCommand.cs +++ b/Galactic Colors Control Server/Commands/ConnectCommand.cs @@ -1,7 +1,7 @@ -using System; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; using System.Net; using System.Net.Sockets; -using Galactic_Colors_Control_Common; namespace Galactic_Colors_Control_Server.Commands { @@ -9,7 +9,7 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "connect"; } } public string DescText { get { return "Gets an username."; } } - public string HelpText { get { return "Use /connect [username] to start identification"; } } + public string HelpText { get { return "Use 'connect [username]' to start identification"; } } public Manager.CommandGroup Group { get { return Manager.CommandGroup.root; } } public bool IsServer { get { return false; } } public bool IsClient { get { return true; } } @@ -18,34 +18,29 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 1; } } public int maxArgs { get { return 1; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { - if (!Utilities.IsConnect(soc)) + if (Utilities.IsConnect(soc)) + return new RequestResult(ResultTypes.Error, Common.Strings("Connected")); + + if (args[1].Length < 3) + return new RequestResult(ResultTypes.Error, Common.Strings("Too Short")); + + Logger.Write("Identifiaction request from " + Utilities.GetName(soc), Logger.logType.debug); + bool allreadyconnected = false; + args[1] = args[1][0].ToString().ToUpper()[0] + args[1].Substring(1); + foreach (Client client in Program.clients.Values) { - Logger.Write("Identifiaction request from " + Utilities.GetName(soc), Logger.logType.debug); - bool allreadyconnected = false; - foreach(Client client in Program.clients.Values) - { - if(client.pseudo == args[1]) { allreadyconnected = true; break; } - } - if (!allreadyconnected) - { - Program.clients[soc].status = 0; - //args[1] = args[1][0].ToString().ToUpper()[0] + args[1].Substring(1); - Program.clients[soc].pseudo = args[1]; - Utilities.Send(soc, "/connected", Common.dataType.message); - Utilities.Broadcast(args[1] + " joined the server", Common.dataType.message); - Logger.Write("Identified as " + Utilities.GetName(soc) + " form " + ((IPEndPoint)soc.LocalEndPoint).Address.ToString(), Logger.logType.info); - } - else - { - Utilities.Send(soc, "/allreadytaken", Common.dataType.message); - } - } - else - { - Utilities.Send(soc, "You are allready " + Utilities.GetName(soc), Common.dataType.message); + if (client.pseudo == args[1]) { allreadyconnected = true; break; } } + if (allreadyconnected) + return new RequestResult(ResultTypes.Error, Common.Strings("Taken")); + + Program.clients[soc].status = 0; + Program.clients[soc].pseudo = args[1]; + Utilities.Broadcast(new EventData(EventTypes.ServerJoin, Common.Strings(args[1]))); + Logger.Write("Identified as " + Utilities.GetName(soc) + " form " + ((IPEndPoint)soc.LocalEndPoint).Address.ToString(), Logger.logType.info); + return new RequestResult(ResultTypes.OK, Common.Strings(args[1])); } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/ExitCommand.cs b/Galactic Colors Control Server/Commands/ExitCommand.cs index cea265e..b473af9 100644 --- a/Galactic Colors Control Server/Commands/ExitCommand.cs +++ b/Galactic Colors Control Server/Commands/ExitCommand.cs @@ -1,5 +1,5 @@ using Galactic_Colors_Control_Common; -using System; +using Galactic_Colors_Control_Common.Protocol; using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands @@ -8,7 +8,7 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "exit"; } } public string DescText { get { return "Leave the server."; } } - public string HelpText { get { return "Use /exit to stop actual program."; } } + public string HelpText { get { return "Use 'exit' to stop actual program."; } } public Manager.CommandGroup Group { get { return Manager.CommandGroup.root; } } public bool IsServer { get { return false; } } public bool IsClient { get { return true; } } @@ -17,7 +17,7 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 0; } } public int maxArgs { get { return 0; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { soc.Shutdown(SocketShutdown.Both); Logger.Write("Client disconnected from " + Utilities.GetName(soc), Logger.logType.info); @@ -25,8 +25,9 @@ namespace Galactic_Colors_Control_Server.Commands bool connected = Program.clients[soc].status != -1; soc.Close(); Program.clients.Remove(soc); - if (connected) { Utilities.Broadcast(username + " leave the server", Common.dataType.message); } + if (connected) { Utilities.Broadcast(new EventData(EventTypes.ServerLeave, Common.Strings(username))); } Logger.Write("Size: " + Program.clients.Count + "/" + Program.config.size, Logger.logType.debug); + return new RequestResult(ResultTypes.OK); } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/HelpCommand.cs b/Galactic Colors Control Server/Commands/HelpCommand.cs index 9b3c502..b410a07 100644 --- a/Galactic Colors Control Server/Commands/HelpCommand.cs +++ b/Galactic Colors Control Server/Commands/HelpCommand.cs @@ -1,4 +1,6 @@ -using System; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System; using System.Collections.Generic; using System.Linq; using System.Net.Sockets; @@ -9,7 +11,7 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "help"; } } public string DescText { get { return "Shows the help."; } } - public string HelpText { get { return "Use /help [command] to display command help. (-all for full help)"; } } + public string HelpText { get { return "Use 'help [command]' to display command help. ('hell -all' for full help)"; } } public Manager.CommandGroup Group { get { return Manager.CommandGroup.root; } } public bool IsServer { get { return true; } } public bool IsClient { get { return true; } } @@ -18,7 +20,7 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 0; } } public int maxArgs { get { return 2; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { bool isGroup = false; bool isAll = false; @@ -33,7 +35,7 @@ namespace Galactic_Colors_Control_Server.Commands List list = new List(); foreach (ICommand com in Manager.commands) { - if(Manager.CanAccess(com, soc, server)) + if (Manager.CanAccess(com, soc, server)) { if (!isGroup || (isGroup && com.Group == (Manager.CommandGroup)Enum.Parse(typeof(Manager.CommandGroup), args[1]))) { @@ -42,14 +44,14 @@ namespace Galactic_Colors_Control_Server.Commands } } } - list.Sort((x,y) => x.Group.CompareTo(y.Group)); - string text = "Use /help [command] for more informations." + Environment.NewLine + "Available commands:" + Environment.NewLine; + list.Sort((x, y) => x.Group.CompareTo(y.Group)); + string text = "Use 'help [command]' for more informations." + Environment.NewLine + "Available commands:" + Environment.NewLine; Manager.CommandGroup actualGroup = 0; foreach (ICommand com in list) { - if(com.Group != actualGroup) + if (com.Group != actualGroup) { - text += (Environment.NewLine + " " + com.Group.ToString() + Environment.NewLine + ((isGroup || isAll) ? "" : (" Use /help " + com.Group.ToString()))); + text += (Environment.NewLine + " " + com.Group.ToString() + Environment.NewLine + ((isGroup || isAll) ? "" : (" Use 'help " + com.Group.ToString() + "'"))); actualGroup = com.Group; } if ((!(isGroup || isAll) && com.Group == 0) || (isGroup || isAll)) @@ -57,28 +59,20 @@ namespace Galactic_Colors_Control_Server.Commands text += (" " + (com.Group != 0 ? new string(' ', 4) : "") + com.Name + new string(' ', maxLen - com.Name.Length - (com.Group == 0 ? 0 : 4)) + " : " + com.DescText + Environment.NewLine); } } - Utilities.Return(text, soc, server); + return new RequestResult(ResultTypes.OK, Common.Strings(text)); } else { ICommand command = null; args = args.Skip(1).ToArray(); - if (Manager.TryGetCommand(args, ref command)) - { - if (Manager.CanAccess(command, soc, server)) - { - Utilities.Return(command.HelpText, soc, server); - } - else - { - Utilities.Return("Any help for " + Manager.CommandToString(args), soc, server); - } - } - else - { - Utilities.Return("Any help for " + Manager.CommandToString(args), soc, server); - } + if (!Manager.TryGetCommand(args, ref command)) + return new RequestResult(ResultTypes.Error, Common.Strings("Any Command")); + + if (!Manager.CanAccess(command, soc, server)) + return new RequestResult(ResultTypes.Error, Common.Strings("Any Command")); + + return new RequestResult(ResultTypes.OK, Common.Strings(command.HelpText)); } } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/ICommand.cs b/Galactic Colors Control Server/Commands/ICommand.cs index d7fbffb..f68f293 100644 --- a/Galactic Colors Control Server/Commands/ICommand.cs +++ b/Galactic Colors Control Server/Commands/ICommand.cs @@ -1,4 +1,5 @@ -using System.Net.Sockets; +using Galactic_Colors_Control_Common.Protocol; +using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands { @@ -15,6 +16,6 @@ namespace Galactic_Colors_Control_Server.Commands int minArgs { get; } int maxArgs { get; } - void Execute(string[] args, Socket soc = null, bool server = false); + RequestResult Execute(string[] args, Socket soc = null, bool server = false); } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/LogLevelCommand.cs b/Galactic Colors Control Server/Commands/LogLevelCommand.cs index 9244ba4..f5cb6ed 100644 --- a/Galactic Colors Control Server/Commands/LogLevelCommand.cs +++ b/Galactic Colors Control Server/Commands/LogLevelCommand.cs @@ -1,4 +1,6 @@ -using System; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System; using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands @@ -7,7 +9,7 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "loglevel"; } } public string DescText { get { return "Change console loglevel."; } } - public string HelpText { get { return "Use /loglevel [loglevel] to change Loglevel."; } } + public string HelpText { get { return "Use 'loglevel [loglevel]' to change Loglevel. (dev ,debug, info, warm, error, fatal)"; } } public Manager.CommandGroup Group { get { return Manager.CommandGroup.root; } } public bool IsServer { get { return true; } } public bool IsClient { get { return false; } } @@ -16,16 +18,16 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 1; } } public int maxArgs { get { return 1; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { if (Enum.TryParse(args[1], true, out Program.config.logLevel)) { - Utilities.ConsoleWrite("LogLevel: " + Program.config.logLevel.ToString()); + return new RequestResult(ResultTypes.OK, Common.Strings(Program.config.logLevel.ToString())); } else { - Utilities.ConsoleWrite("Incorrect argument (debug, info, important, error, fatal)"); + return new RequestResult(ResultTypes.Error, Common.Strings("Incorrect argument")); } } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Manager.cs b/Galactic Colors Control Server/Commands/Manager.cs index 1554015..a0defc2 100644 --- a/Galactic Colors Control Server/Commands/Manager.cs +++ b/Galactic Colors Control Server/Commands/Manager.cs @@ -1,4 +1,6 @@ -using System; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System; using System.Collections.Generic; using System.Linq; using System.Net.Sockets; @@ -9,7 +11,10 @@ namespace Galactic_Colors_Control_Server.Commands public class Manager { public static List commands { get; private set; } = new List(); - public enum CommandGroup { root, server, party, client} + + public enum CommandGroup { root, server, party, client } + + private static RequestResult AnyCommand = new RequestResult(ResultTypes.Error, Common.Strings("Any Command")); /// /// Find all ICommand and add them to commands @@ -31,52 +36,39 @@ namespace Galactic_Colors_Control_Server.Commands /// command with args /// Sender socket /// Is server? - public static void Execute(string[] args, Socket soc = null, bool server = false) + public static RequestResult Execute(string[] args, Socket soc = null, bool server = false) { ICommand command = null; - if (TryGetCommand(args, ref command)) - { - if (CanAccess(command, soc, server)) - { - if (!server && command.IsClientSide) - { - Utilities.Return("It's a client side command", soc, server); - } - else - { - if (args.Length - (command.Group == 0 ? 0 : 1) > command.minArgs) - { - if (args.Length - (command.Group == 0 ? 1 : 2) <= command.maxArgs) - { - command.Execute(args, soc, server); - } - else - { - Utilities.Return("Command " + CommandToString(command) + " require at most " + command.maxArgs + " argument(s).", soc, server); - } - } + if (!TryGetCommand(args, ref command)) + return AnyCommand; - else - { - Utilities.Return("Command " + CommandToString(command) + " require at least " + command.minArgs + " argument(s).", soc, server); - } - } - } - else - { - Utilities.Return("Unknown command : " + CommandToString(args), soc, server); - } - } - else + if (!CanAccess(command, soc, server)) + return AnyCommand; + + if (!server && command.IsClientSide) + return new RequestResult(ResultTypes.Error, Common.Strings("Client Side")); + + if (args.Length - (command.Group == 0 ? 0 : 1) <= command.minArgs) + return new RequestResult(ResultTypes.Error, new string[2] { "Too Short", command.minArgs.ToString() }); + + if (args.Length - (command.Group == 0 ? 1 : 2) > command.maxArgs) + return new RequestResult(ResultTypes.Error, new string[2] { "Too Long", command.maxArgs.ToString() }); + + try { - Utilities.Return("Unknown command : " + CommandToString(args), soc, server); + return command.Execute(args, soc, server); + } + catch (Exception e) + { + Logger.Write("Command " + args[0] + " Exception : " + e.Message, Logger.logType.error); + return new RequestResult(ResultTypes.Error, Common.Strings("Execute Exception")); } } public static string CommandToString(ICommand command) { string text = ""; - if(command.Group != 0) { text += (command.Group.ToString() + " "); } + if (command.Group != 0) { text += (command.Group.ToString() + " "); } text += command.Name; return text; } @@ -90,7 +82,7 @@ namespace Galactic_Colors_Control_Server.Commands if (args.Length > 0) { string text = ""; - foreach(string arg in args) + foreach (string arg in args) { text += (arg + " "); } @@ -151,7 +143,7 @@ namespace Galactic_Colors_Control_Server.Commands { if (command.IsClient) { - if(!Utilities.IsConnect(soc)) + if (!Utilities.IsConnect(soc)) { return command.IsNoConnect; } @@ -167,4 +159,4 @@ namespace Galactic_Colors_Control_Server.Commands } } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Party/PartyClientCommand.cs b/Galactic Colors Control Server/Commands/Party/PartyClientCommand.cs index ac60f20..4077030 100644 --- a/Galactic Colors Control Server/Commands/Party/PartyClientCommand.cs +++ b/Galactic Colors Control Server/Commands/Party/PartyClientCommand.cs @@ -1,4 +1,5 @@ -using System; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands @@ -7,7 +8,7 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "client"; } } public string DescText { get { return "Lists party clients."; } } - public string HelpText { get { return "Use /party client to show party clients list."; } } + public string HelpText { get { return "Use 'party client' to show party clients list."; } } public Manager.CommandGroup Group { get { return Manager.CommandGroup.party; } } public bool IsServer { get { return true; } } public bool IsClient { get { return true; } } @@ -16,18 +17,20 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 0; } } public int maxArgs { get { return 0; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { int partyId = -1; - if (Utilities.AccessParty(ref partyId, false, soc, server)) + if (!Utilities.AccessParty(ref partyId, args, false, soc, server)) + return new RequestResult(ResultTypes.Error, Common.Strings("Access")); + + string[] data = new string[Program.parties[partyId].clients.Count]; + int i = 0; + foreach (Socket client in Program.parties[partyId].clients) { - string text = " "; - foreach(Socket client in Program.parties[partyId].clients) - { - text += (Utilities.GetName(client) + Environment.NewLine + " "); - } - Utilities.Return(text, soc, server); + data[i] = Utilities.GetName(client); + i++; } + return new RequestResult(ResultTypes.OK, data); } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Party/PartyCloseCommand.cs b/Galactic Colors Control Server/Commands/Party/PartyCloseCommand.cs index 5591d62..a0f71c5 100644 --- a/Galactic Colors Control Server/Commands/Party/PartyCloseCommand.cs +++ b/Galactic Colors Control Server/Commands/Party/PartyCloseCommand.cs @@ -1,4 +1,6 @@ -using System.Net.Sockets; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands { @@ -6,7 +8,7 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "close"; } } public string DescText { get { return "Closes party."; } } - public string HelpText { get { return "Use /party close to close party for join."; } } + public string HelpText { get { return "Use 'party close' to close party for join."; } } public Manager.CommandGroup Group { get { return Manager.CommandGroup.party; } } public bool IsServer { get { return true; } } public bool IsClient { get { return true; } } @@ -15,21 +17,17 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 0; } } public int maxArgs { get { return 0; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { int partyId = -1; - if (Utilities.AccessParty(ref partyId, true,soc, server)) - { - if (Program.parties[partyId].open) - { - Program.parties[partyId].open = false; - Utilities.Return("Party closed", soc, server); - } - else - { - Utilities.Return("Party allready close", soc, server); - } - } + if (!Utilities.AccessParty(ref partyId, args, true, soc, server)) + return new RequestResult(ResultTypes.Error, Common.Strings("Access")); + + if (!Program.parties[partyId].open) + return new RequestResult(ResultTypes.Error, Common.Strings("Allready")); + + Program.parties[partyId].open = false; + return new RequestResult(ResultTypes.OK); } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Party/PartyCreateCommand.cs b/Galactic Colors Control Server/Commands/Party/PartyCreateCommand.cs index a194712..f37a2f5 100644 --- a/Galactic Colors Control Server/Commands/Party/PartyCreateCommand.cs +++ b/Galactic Colors Control Server/Commands/Party/PartyCreateCommand.cs @@ -1,4 +1,6 @@ -using System.Net.Sockets; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands { @@ -6,7 +8,7 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "create"; } } public string DescText { get { return "Create new party."; } } - public string HelpText { get { return "Use /party create [name] [size] to create new party."; } } + public string HelpText { get { return "Use 'party create [name] [size]' to create new party."; } } public Manager.CommandGroup Group { get { return Manager.CommandGroup.party; } } public bool IsServer { get { return true; } } public bool IsClient { get { return true; } } @@ -15,48 +17,32 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 2; } } public int maxArgs { get { return 2; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { - if (server || (!server && Program.clients[soc].partyID == -1)) + if (!server && Program.clients[soc].partyID != -1) + return new RequestResult(ResultTypes.Error, Common.Strings("Allready")); + + int size; + if (!int.TryParse(args[3], out size)) + return new RequestResult(ResultTypes.Error, Common.Strings("Format")); + + if (size < 1) + return new RequestResult(ResultTypes.Error, Common.Strings("Too Small")); + + if (size > Program.config.size) + return new RequestResult(ResultTypes.Error, Common.Strings("Too Big")); + + Program.AddParty(new Party(args[2], size, Utilities.GetName(soc))); + Logger.Write("Party " + args[2] + " create with " + size + " slots as " + Program.GetPartyID(false), Logger.logType.info); + if (server) { - int size; - if (int.TryParse(args[3], out size)) - { - if (size > 0) - { - if (size <= Program.config.size) - { - Logger.Write("Party " + args[2] + " create with " + size + " slots as " + Program.partyID, Logger.logType.info); - Program.AddParty(new Party(args[2], size, Utilities.GetName(soc))); - if (server) - { - Program.selectedParty = Program.partyID-1; - } - else - { - Program.clients[soc].partyID = Program.partyID-1; - Utilities.Return("Party " + args[2] + " create with " + size + " slots as " + (Program.partyID-1), soc, server); - } - } - else - { - Utilities.Return("Too big size", soc, server); - } - } - else - { - Utilities.Return("Too small size", soc, server); - } - } - else - { - Utilities.Return("Incorrect argument " + args[3], soc, server); - } + Program.selectedParty = Program.GetPartyID(false); } else { - Utilities.Return("Allready in a party.", soc, server); + Program.clients[soc].partyID = Program.GetPartyID(false); } + return new RequestResult(ResultTypes.OK, new string[3] { args[2], size.ToString(), (Program.GetPartyID(false)).ToString() }); } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Party/PartyJoinCommand.cs b/Galactic Colors Control Server/Commands/Party/PartyJoinCommand.cs index c259c51..f072f4b 100644 --- a/Galactic Colors Control Server/Commands/Party/PartyJoinCommand.cs +++ b/Galactic Colors Control Server/Commands/Party/PartyJoinCommand.cs @@ -1,4 +1,6 @@ -using System; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System; using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands @@ -7,7 +9,7 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "join"; } } public string DescText { get { return "Join a party."; } } - public string HelpText { get { return "Use /party join [id] to join a party."; } } + public string HelpText { get { return "Use 'party join [id] ' to join a party."; } } public Manager.CommandGroup Group { get { return Manager.CommandGroup.party; } } public bool IsServer { get { return true; } } public bool IsClient { get { return true; } } @@ -16,66 +18,44 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 1; } } public int maxArgs { get { return 2; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { if ((server && Program.selectedParty == -1) || (!server && Program.clients[soc].partyID == -1)) + return new RequestResult(ResultTypes.Error, Common.Strings("Allready")); + + int id; + if (!int.TryParse(args[2], out id)) + return new RequestResult(ResultTypes.Error, Common.Strings("Any Party")); + + if (!Program.parties.ContainsKey(id)) + return new RequestResult(ResultTypes.Error, Common.Strings("Can't Find")); + + Party party = Program.parties[id]; + if (args.Length == 3) { - int id; - if (int.TryParse(args[2], out id)) - { - if (Program.parties.ContainsKey(id)) - { - Party party = Program.parties[id]; - if (args.Length == 3) - { - Array.Resize(ref args, 4); - args[3] = ""; - } - if (server || (!server && party.TestPassword(args[3]))) - { - if(server) - { - Program.selectedParty = id; - } - else - { - if(party.open) - { - if (party.clients.Count < party.size) - { - Program.clients[soc].partyID = id; - Utilities.BroadcastParty(Utilities.GetName(soc) + " join the party", Galactic_Colors_Control_Common.Common.dataType.message, id); - } - else - { - Utilities.Return("Party is full", soc, server); - } - } - else - { - Utilities.Return("Party close", soc, server); - } - } - } - else - { - Utilities.Return("Wrong party password", soc, server); - } - } - else - { - Utilities.Return("Can't find party " + id, soc, server); - } - } - else - { - Utilities.Return("Incorrect argument " + args[3], soc, server); - } + Array.Resize(ref args, 4); + args[3] = ""; + } + if (!server && !party.TestPassword(args[3])) + return new RequestResult(ResultTypes.Error, Common.Strings("Password")); + + if (server) + { + Program.selectedParty = id; + return new RequestResult(ResultTypes.OK); } else { - Utilities.Return("Allready in a party.", soc, server); + if (!party.open) + return new RequestResult(ResultTypes.Error, Common.Strings("Close")); + + if (party.clients.Count + 1 > party.size) + return new RequestResult(ResultTypes.Error, Common.Strings("Full")); + + Program.clients[soc].partyID = id; + Utilities.BroadcastParty(new EventData(EventTypes.PartyJoin, Common.Strings(Utilities.GetName(soc))), id); + return new RequestResult(ResultTypes.OK); } } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Party/PartyKickCommand.cs b/Galactic Colors Control Server/Commands/Party/PartyKickCommand.cs index 7d76903..2b85bf3 100644 --- a/Galactic Colors Control Server/Commands/Party/PartyKickCommand.cs +++ b/Galactic Colors Control Server/Commands/Party/PartyKickCommand.cs @@ -1,4 +1,5 @@ using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands @@ -7,7 +8,7 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "kick"; } } public string DescText { get { return "Kick player from party."; } } - public string HelpText { get { return "Use /party kick [name] to kick palyer from party"; } } + public string HelpText { get { return "Use 'party kick [name] ' to kick palyer from party"; } } public Manager.CommandGroup Group { get { return Manager.CommandGroup.party; } } public bool IsServer { get { return true; } } public bool IsClient { get { return true; } } @@ -16,34 +17,22 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 1; } } public int maxArgs { get { return 2; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { int partyId = -1; - if (Utilities.AccessParty(ref partyId, true, soc, server)) + if (Utilities.AccessParty(ref partyId, args, true, soc, server)) + return new RequestResult(ResultTypes.Error, Common.Strings("Access")); + + Socket target = null; + foreach (Socket client in Program.parties[partyId].clients) { - Socket target = null; - foreach (Socket client in Program.parties[partyId].clients) - { - if (Utilities.GetName(client) == args[2]) { target = client; } - } - if (target != null) - { - Utilities.BroadcastParty(args[2] + " was kick", Common.dataType.message, partyId); - if (args.Length > 3) - { - Utilities.Send(target, "/party kick " + args[3], Common.dataType.message); - } - else - { - Utilities.Send(target, "/party kick", Common.dataType.message); - } - Manager.Execute(new string[2] { "party", "leave" },target,false); - } - else - { - Utilities.Return("Can't find " + args[2] + "in party", soc, server); - } + if (Utilities.GetName(client) == args[2]) { target = client; } } + if (target == null) + return new RequestResult(ResultTypes.Error, Common.Strings("Can't find")); + + Utilities.Send(target, new EventData(EventTypes.PartyKick, args.Length > 3 ? Common.Strings(args[2]) : null)); + return Manager.Execute(new string[2] { "party", "leave" }, target, false); } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Party/PartyLeaveCommand.cs b/Galactic Colors Control Server/Commands/Party/PartyLeaveCommand.cs index aa65bf7..8bfe734 100644 --- a/Galactic Colors Control Server/Commands/Party/PartyLeaveCommand.cs +++ b/Galactic Colors Control Server/Commands/Party/PartyLeaveCommand.cs @@ -1,4 +1,6 @@ -using System.Net.Sockets; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands { @@ -6,7 +8,7 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "leave"; } } public string DescText { get { return "Leave party."; } } - public string HelpText { get { return "Use /party leave to leave current party"; } } + public string HelpText { get { return "Use 'party leave' to leave current party"; } } public Manager.CommandGroup Group { get { return Manager.CommandGroup.party; } } public bool IsServer { get { return true; } } public bool IsClient { get { return true; } } @@ -15,28 +17,26 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 0; } } public int maxArgs { get { return 0; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { if (server) { Program.selectedParty = -1; + return new RequestResult(ResultTypes.OK); } else { int partyId = -1; - if (Utilities.AccessParty(ref partyId, false, soc, server)) - { - if (!Program.parties[partyId].IsOwner(Utilities.GetName(soc))) - { - Utilities.BroadcastParty(Utilities.GetName(soc) + " leave the party", Galactic_Colors_Control_Common.Common.dataType.message, partyId); - Program.clients[soc].partyID = -1; - } - else - { - Utilities.Return("Owner can't leave party. Look for /party stop", soc, server); - } - } + if (Utilities.AccessParty(ref partyId, args, false, soc, server)) + return new RequestResult(ResultTypes.Error, Common.Strings("Access")); + + if (Program.parties[partyId].IsOwner(Utilities.GetName(soc))) + return new RequestResult(ResultTypes.Error, Common.Strings("Owner")); + + Program.clients[soc].partyID = -1; + Utilities.BroadcastParty(new EventData(EventTypes.PartyLeave, Common.Strings(Utilities.GetName(soc))), partyId); + return new RequestResult(ResultTypes.OK); } } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Party/PartyListCommand.cs b/Galactic Colors Control Server/Commands/Party/PartyListCommand.cs index 27c486c..5f259fd 100644 --- a/Galactic Colors Control Server/Commands/Party/PartyListCommand.cs +++ b/Galactic Colors Control Server/Commands/Party/PartyListCommand.cs @@ -1,4 +1,5 @@ -using System; +using Galactic_Colors_Control_Common.Protocol; +using System; using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands @@ -7,7 +8,7 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "list"; } } public string DescText { get { return "Shows parties list."; } } - public string HelpText { get { return "Use /party list to show parties list."; } } + public string HelpText { get { return "Use 'party list' to show parties list."; } } public Manager.CommandGroup Group { get { return Manager.CommandGroup.party; } } public bool IsServer { get { return true; } } public bool IsClient { get { return true; } } @@ -16,15 +17,17 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 0; } } public int maxArgs { get { return 0; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { - string text = " "; + string[] text = new string[Program.parties.Keys.Count]; + int i = 0; foreach (int key in Program.parties.Keys) { Party party = Program.parties[key]; - text += (key + " : " + party.name + " : " + party.count + "/" + party.size + " : " + (party.open ? (party.isPrivate ? "private" : "open") : "close") + Environment.NewLine + " "); + text[i] = (key + " : " + party.name + " : " + party.count + "/" + party.size + " : " + (party.open ? (party.isPrivate ? "private" : "open") : "close") + Environment.NewLine + " "); + i++; } - Utilities.Return(text, soc, server); + return new RequestResult(ResultTypes.OK, text); } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Party/PartyOpenCommand.cs b/Galactic Colors Control Server/Commands/Party/PartyOpenCommand.cs index 627b9c2..8a08c3b 100644 --- a/Galactic Colors Control Server/Commands/Party/PartyOpenCommand.cs +++ b/Galactic Colors Control Server/Commands/Party/PartyOpenCommand.cs @@ -1,4 +1,6 @@ -using System.Net.Sockets; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands { @@ -6,7 +8,7 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "open"; } } public string DescText { get { return "Opens party."; } } - public string HelpText { get { return "Use /party open to open party for join."; } } + public string HelpText { get { return "Use 'party open' to open party for join."; } } public Manager.CommandGroup Group { get { return Manager.CommandGroup.party; } } public bool IsServer { get { return true; } } public bool IsClient { get { return true; } } @@ -15,21 +17,17 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 0; } } public int maxArgs { get { return 0; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { int partyId = -1; - if (Utilities.AccessParty(ref partyId, true, soc, server)) - { - if (!Program.parties[partyId].open) - { - Program.parties[partyId].open = true; - Utilities.Return("Party opened", soc, server); - } - else - { - Utilities.Return("Party allready open", soc, server); - } - } + if (Utilities.AccessParty(ref partyId, args, true, soc, server)) + return new RequestResult(ResultTypes.Error, Common.Strings("Access")); + + if (Program.parties[partyId].open) + return new RequestResult(ResultTypes.Error, Common.Strings("Allready")); + + Program.parties[partyId].open = true; + return new RequestResult(ResultTypes.OK); } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Party/PartyPasswordCommand.cs b/Galactic Colors Control Server/Commands/Party/PartyPasswordCommand.cs index e613d65..7ed01a1 100644 --- a/Galactic Colors Control Server/Commands/Party/PartyPasswordCommand.cs +++ b/Galactic Colors Control Server/Commands/Party/PartyPasswordCommand.cs @@ -1,4 +1,6 @@ -using System; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System; using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands @@ -7,7 +9,7 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "password"; } } public string DescText { get { return "Set party password."; } } - public string HelpText { get { return "Use /party password [newPass] [oldPass] to set party private with password."; } } + public string HelpText { get { return "Use 'party password [newPass] ' to set party private with password."; } } public Manager.CommandGroup Group { get { return Manager.CommandGroup.party; } } public bool IsServer { get { return true; } } public bool IsClient { get { return true; } } @@ -16,25 +18,22 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 1; } } public int maxArgs { get { return 2; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { int partyId = -1; - if (Utilities.AccessParty(ref partyId, true, soc, server)) + if (Utilities.AccessParty(ref partyId, args, true, soc, server)) + return new RequestResult(ResultTypes.Error, Common.Strings("Access")); + + if (args.Length == 3) { - if (args.Length == 3) - { - Array.Resize(ref args, 4); - args[3] = ""; - } - if (Program.parties[partyId].SetPassword(args[2],args[3])) - { - Utilities.Return("Password changed", soc, server); - } - else - { - Utilities.Return("Can't change password", soc, server); - } + Array.Resize(ref args, 4); + args[3] = ""; } + + if (!Program.parties[partyId].SetPassword(args[2], args[3])) + return new RequestResult(ResultTypes.Error, Common.Strings("Can't Change")); + + return new RequestResult(ResultTypes.OK); } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Party/PartyStatusCommand.cs b/Galactic Colors Control Server/Commands/Party/PartyStatusCommand.cs index c4cfa92..cde3708 100644 --- a/Galactic Colors Control Server/Commands/Party/PartyStatusCommand.cs +++ b/Galactic Colors Control Server/Commands/Party/PartyStatusCommand.cs @@ -1,4 +1,6 @@ -using System; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System; using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands @@ -7,7 +9,7 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "status"; } } public string DescText { get { return "Shows party status."; } } - public string HelpText { get { return "Use /party status to show party status."; } } + public string HelpText { get { return "Use 'party status' to show party status."; } } public Manager.CommandGroup Group { get { return Manager.CommandGroup.party; } } public bool IsServer { get { return true; } } public bool IsClient { get { return true; } } @@ -16,18 +18,25 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 0; } } public int maxArgs { get { return 0; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { int partyId = -1; - if (Utilities.AccessParty(ref partyId, false, soc, server)) + if (!Utilities.AccessParty(ref partyId, args, false, soc, server)) + return new RequestResult(ResultTypes.Error, Common.Strings("Access")); + + Party party = Program.parties[partyId]; + if (server) { - Party party = Program.parties[partyId]; string text = ""; text += ("Name: " + party.name + Environment.NewLine); text += ("Count: " + party.count + "/" + party.size + Environment.NewLine); text += ("Status: " + (party.isPrivate ? "private" : (party.open ? "open" : "close"))); - Utilities.Return(text,soc,server); + return new RequestResult(ResultTypes.OK, Common.Strings(text)); + } + else + { + return new RequestResult(ResultTypes.OK, new string[4] { party.name, party.count.ToString(), party.size.ToString(), (party.isPrivate ? "private" : (party.open ? "open" : "close")) }); } } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Party/PartyStopCommand.cs b/Galactic Colors Control Server/Commands/Party/PartyStopCommand.cs index 1a9d7fe..dfd5d52 100644 --- a/Galactic Colors Control Server/Commands/Party/PartyStopCommand.cs +++ b/Galactic Colors Control Server/Commands/Party/PartyStopCommand.cs @@ -1,4 +1,6 @@ -using System.Net.Sockets; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands { @@ -6,7 +8,7 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "stop"; } } public string DescText { get { return "Stop party."; } } - public string HelpText { get { return "Use /party stop to stop current party"; } } + public string HelpText { get { return "Use 'party stop' to stop current party"; } } public Manager.CommandGroup Group { get { return Manager.CommandGroup.party; } } public bool IsServer { get { return true; } } public bool IsClient { get { return true; } } @@ -15,19 +17,20 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 0; } } public int maxArgs { get { return 0; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { int partyId = -1; - if (Utilities.AccessParty(ref partyId, true, soc, server)) + if (!Utilities.AccessParty(ref partyId, args, true, soc, server)) + return new RequestResult(ResultTypes.Error, Common.Strings("Access")); + + foreach (Socket client in Program.parties[partyId].clients) { - foreach(Socket client in Program.parties[partyId].clients) - { - Manager.Execute(new string[4] { "party","kick",Utilities.GetName(client),"stop_party" } ,soc,server); - } - Logger.Write("Party " + Program.parties[partyId].name + " closed", Logger.logType.info); - if(Program.selectedParty == partyId) { Program.selectedParty = -1; } - Program.parties.Remove(partyId); + Manager.Execute(new string[4] { "party", "kick", Utilities.GetName(client), "stop_party" }, soc, server); } + Logger.Write("Party " + Program.parties[partyId].name + " closed", Logger.logType.info, server ? Logger.logConsole.show : Logger.logConsole.normal); + if (Program.selectedParty == partyId) { Program.selectedParty = -1; } + Program.parties.Remove(partyId); + return new RequestResult(ResultTypes.OK); } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/PingCommand.cs b/Galactic Colors Control Server/Commands/PingCommand.cs index 6f1ed09..6f7b0ee 100644 --- a/Galactic Colors Control Server/Commands/PingCommand.cs +++ b/Galactic Colors Control Server/Commands/PingCommand.cs @@ -1,4 +1,6 @@ -using System.Net.Sockets; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands { @@ -6,7 +8,7 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "ping"; } } public string DescText { get { return "Clears the console screen."; } } - public string HelpText { get { return "Use /ping to display our ping."; } } + public string HelpText { get { return "Use 'ping' to display our ping."; } } public Manager.CommandGroup Group { get { return Manager.CommandGroup.root; } } public bool IsServer { get { return false; } } public bool IsClient { get { return true; } } @@ -15,9 +17,9 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 0; } } public int maxArgs { get { return 0; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { - + return new RequestResult(ResultTypes.Error, Common.Strings("Client Side")); } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/SayCommand.cs b/Galactic Colors Control Server/Commands/SayCommand.cs new file mode 100644 index 0000000..14008d8 --- /dev/null +++ b/Galactic Colors Control Server/Commands/SayCommand.cs @@ -0,0 +1,34 @@ +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System.Net.Sockets; + +namespace Galactic_Colors_Control_Server.Commands +{ + public class SayCommand : ICommand + { + public string Name { get { return "say"; } } + public string DescText { get { return "Said something."; } } + public string HelpText { get { return "Use 'say [text]' to said something."; } } + public Manager.CommandGroup Group { get { return Manager.CommandGroup.root; } } + public bool IsServer { get { return true; } } + public bool IsClient { get { return true; } } + public bool IsClientSide { get { return false; } } + public bool IsNoConnect { get { return false; } } + public int minArgs { get { return 1; } } + public int maxArgs { get { return 1; } } + + public RequestResult Execute(string[] args, Socket soc, bool server = false) + { + if (args[1].Length == 0) + return new RequestResult(ResultTypes.Error, Common.Strings("Any Message")); + + if (!Utilities.IsConnect(soc)) + return new RequestResult(ResultTypes.Error, Common.Strings("Must Be Connected")); + + int party = -1; + party = Utilities.GetParty(soc); + Utilities.BroadcastParty(new EventData(EventTypes.ChatMessage, Common.Strings(Utilities.GetName(soc) + " : " + args[1])), party); + return new RequestResult(ResultTypes.OK); + } + } +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Server/ServerCloseCommand.cs b/Galactic Colors Control Server/Commands/Server/ServerCloseCommand.cs index 0b5d95e..9cd624f 100644 --- a/Galactic Colors Control Server/Commands/Server/ServerCloseCommand.cs +++ b/Galactic Colors Control Server/Commands/Server/ServerCloseCommand.cs @@ -1,4 +1,5 @@ -using System; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands @@ -7,7 +8,7 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "close"; } } public string DescText { get { return "Close server."; } } - public string HelpText { get { return "Use /server close to close server for connections"; } } + public string HelpText { get { return "Use 'server close' to close server for connections"; } } public Manager.CommandGroup Group { get { return Manager.CommandGroup.server; } } public bool IsServer { get { return true; } } public bool IsClient { get { return false; } } @@ -16,17 +17,14 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 0; } } public int maxArgs { get { return 0; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { - if (Program._open) - { - Program._open = false; - Logger.Write("Server closed", Logger.logType.warm); - } - else - { - Utilities.ConsoleWrite("Server allready close"); - } + if (!Program._open) + return new RequestResult(ResultTypes.Error, Common.Strings("Allready")); + + Program._open = false; + Logger.Write("Server closed", Logger.logType.warm, Logger.logConsole.show); + return new RequestResult(ResultTypes.OK); } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Server/ServerOpenCommand.cs b/Galactic Colors Control Server/Commands/Server/ServerOpenCommand.cs index 4d26763..aef73bc 100644 --- a/Galactic Colors Control Server/Commands/Server/ServerOpenCommand.cs +++ b/Galactic Colors Control Server/Commands/Server/ServerOpenCommand.cs @@ -1,4 +1,5 @@ -using System; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands @@ -7,7 +8,7 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "open"; } } public string DescText { get { return "Open server."; } } - public string HelpText { get { return "Use /server open to open server for connections"; } } + public string HelpText { get { return "Use 'server open' to open server for connections"; } } public Manager.CommandGroup Group { get { return Manager.CommandGroup.server; } } public bool IsServer { get { return true; } } public bool IsClient { get { return false; } } @@ -16,17 +17,14 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 0; } } public int maxArgs { get { return 0; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { - if (!Program._open) - { - Program._open = true; - Logger.Write("Server opened", Logger.logType.warm); - } - else - { - Utilities.ConsoleWrite("Server allready open"); - } + if (Program._open) + return new RequestResult(ResultTypes.Error, Common.Strings("Allready")); + + Program._open = true; + Logger.Write("Server opened", Logger.logType.warm, Logger.logConsole.show); + return new RequestResult(ResultTypes.OK); } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Server/ServerStatusCommand.cs b/Galactic Colors Control Server/Commands/Server/ServerStatusCommand.cs index a7ecc9e..947a515 100644 --- a/Galactic Colors Control Server/Commands/Server/ServerStatusCommand.cs +++ b/Galactic Colors Control Server/Commands/Server/ServerStatusCommand.cs @@ -1,4 +1,5 @@ -using System; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands @@ -7,7 +8,7 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "status"; } } public string DescText { get { return "Shows server status."; } } - public string HelpText { get { return "Use /server status to display server actual status."; } } + public string HelpText { get { return "Use 'server status' to display server actual status."; } } public Manager.CommandGroup Group { get { return Manager.CommandGroup.server; } } public bool IsServer { get { return true; } } public bool IsClient { get { return false; } } @@ -16,18 +17,13 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 0; } } public int maxArgs { get { return 0; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { - if (Program._open) - { - Utilities.ConsoleWrite("Server : open", ConsoleColor.Green); - } - else - { - Utilities.ConsoleWrite("Server : close", ConsoleColor.Red); - } - Utilities.ConsoleWrite("Clients : " + Program.clients.Count + "/" + Program.config.size); - Utilities.ConsoleWrite("Parties : " + Program.parties.Count); + string text = ""; + text += "Server : " + (Program._open ? "open" : "close"); + text += "Clients : " + Program.clients.Count + "/" + Program.config.size; + text += "Parties : " + Program.parties.Count; + return new RequestResult(ResultTypes.OK, Common.Strings(text)); } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/Server/ServerStopCommand.cs b/Galactic Colors Control Server/Commands/Server/ServerStopCommand.cs index 73550b0..02ef516 100644 --- a/Galactic Colors Control Server/Commands/Server/ServerStopCommand.cs +++ b/Galactic Colors Control Server/Commands/Server/ServerStopCommand.cs @@ -1,5 +1,4 @@ -using Galactic_Colors_Control_Common; -using System; +using Galactic_Colors_Control_Common.Protocol; using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands @@ -8,7 +7,7 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "stop"; } } public string DescText { get { return "Stop the server."; } } - public string HelpText { get { return "Use /server stop to completly stop server."; } } + public string HelpText { get { return "Use 'server stop' to completly stop server."; } } public Manager.CommandGroup Group { get { return Manager.CommandGroup.server; } } public bool IsServer { get { return true; } } public bool IsClient { get { return false; } } @@ -17,10 +16,10 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 0; } } public int maxArgs { get { return 0; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { Program._run = false; - Utilities.ConsoleWrite("Stop server"); + return new RequestResult(ResultTypes.OK); } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Commands/TimeCommand.cs b/Galactic Colors Control Server/Commands/TimeCommand.cs index fd307f7..4a34ab2 100644 --- a/Galactic Colors Control Server/Commands/TimeCommand.cs +++ b/Galactic Colors Control Server/Commands/TimeCommand.cs @@ -1,4 +1,6 @@ -using System; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using System; using System.Net.Sockets; namespace Galactic_Colors_Control_Server.Commands @@ -7,7 +9,7 @@ namespace Galactic_Colors_Control_Server.Commands { public string Name { get { return "time"; } } public string DescText { get { return "Gives server time."; } } - public string HelpText { get { return "Use /time to display server time. (format is server dependent)"; } } + public string HelpText { get { return "Use 'time' to display server time."; } } public Manager.CommandGroup Group { get { return Manager.CommandGroup.root; } } public bool IsServer { get { return true; } } public bool IsClient { get { return true; } } @@ -16,9 +18,9 @@ namespace Galactic_Colors_Control_Server.Commands public int minArgs { get { return 0; } } public int maxArgs { get { return 0; } } - public void Execute(string[] args, Socket soc, bool server = false) + public RequestResult Execute(string[] args, Socket soc, bool server = false) { - Utilities.Return(DateTime.Now.ToLongTimeString(), soc, server); + return new RequestResult(ResultTypes.OK, Common.Strings(DateTime.Now.ToLongTimeString())); } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/Config.cs b/Galactic Colors Control Server/Config.cs index af16ae7..948647f 100644 --- a/Galactic Colors Control Server/Config.cs +++ b/Galactic Colors Control Server/Config.cs @@ -1,9 +1,5 @@ using System; -using System.Collections.Generic; using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using System.Xml; using System.Xml.Serialization; @@ -16,8 +12,8 @@ namespace Galactic_Colors_Control_Server public Logger.logType logLevel = Logger.logType.info; public int port = 25001; public int size = 20; - public ConsoleColor[] logForeColor = new ConsoleColor[5] {ConsoleColor.Gray , ConsoleColor.White, ConsoleColor.Yellow, ConsoleColor.Red, ConsoleColor.White}; - public ConsoleColor[] logBackColor = new ConsoleColor[5] { ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Red }; + public ConsoleColor[] logForeColor = new ConsoleColor[6] { ConsoleColor.DarkGray, ConsoleColor.Gray, ConsoleColor.White, ConsoleColor.Yellow, ConsoleColor.Red, ConsoleColor.White }; + public ConsoleColor[] logBackColor = new ConsoleColor[6] { ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Red }; /// /// Load config from xml file @@ -41,6 +37,7 @@ namespace Galactic_Colors_Control_Server else { Logger.Write("Old config in Config.xml.old", Logger.logType.warm); + File.Delete(AppDomain.CurrentDomain.BaseDirectory + "Config.xml.old"); File.Move(AppDomain.CurrentDomain.BaseDirectory + "Config.xml", AppDomain.CurrentDomain.BaseDirectory + "Config.xml.old"); config.Save(); } @@ -51,6 +48,7 @@ namespace Galactic_Colors_Control_Server config.Save(); } if (Program._debug) { config.logLevel = Logger.logType.debug; } + if (Program._dev) { config.logLevel = Logger.logType.dev; } return config; } @@ -60,12 +58,13 @@ namespace Galactic_Colors_Control_Server public void Save() { XmlSerializer xs = new XmlSerializer(typeof(Config)); - if (Program._debug) { logLevel = Logger.logType.info; } + if (Program._debug || Program._dev) { logLevel = Logger.logType.info; } using (StreamWriter st = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "Config.xml")) { - xs.Serialize(st,this); + xs.Serialize(st, this); }; if (Program._debug) { logLevel = Logger.logType.debug; } + if (Program._dev) { logLevel = Logger.logType.dev; } } /// @@ -114,4 +113,4 @@ namespace Galactic_Colors_Control_Server return isCorrect; } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control Server/ConfigSchema.xsd b/Galactic Colors Control Server/ConfigSchema.xsd index 7e1457f..80af477 100644 --- a/Galactic Colors Control Server/ConfigSchema.xsd +++ b/Galactic Colors Control Server/ConfigSchema.xsd @@ -24,4 +24,4 @@ - + \ No newline at end of file diff --git a/Galactic Colors Control Server/Galactic Colors Control Server.csproj b/Galactic Colors Control Server/Galactic Colors Control Server.csproj index 7243d67..b89d988 100644 --- a/Galactic Colors Control Server/Galactic Colors Control Server.csproj +++ b/Galactic Colors Control Server/Galactic Colors Control Server.csproj @@ -59,6 +59,8 @@ + + diff --git a/Galactic Colors Control Server/Logger.cs b/Galactic Colors Control Server/Logger.cs index fb66c4b..3c84d79 100644 --- a/Galactic Colors Control Server/Logger.cs +++ b/Galactic Colors Control Server/Logger.cs @@ -4,14 +4,16 @@ using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; -using System.Reflection; using System.Threading; namespace Galactic_Colors_Control_Server { public class Logger { - public enum logType { debug, info, warm, error, fatal } + public enum logType { dev, debug, info, warm, error, fatal } + + public enum logConsole { normal, show, hide } + private static List toWriteLogs = new List(); private static string logPath; public static Thread Updater; @@ -21,11 +23,13 @@ namespace Galactic_Colors_Control_Server { public string text; public logType type; + public logConsole console; - public Log(string p1, logType p2) + public Log(string p1, logType p2, logConsole p3 = logConsole.normal) { text = p1; type = p2; + console = p3; } } @@ -34,15 +38,16 @@ namespace Galactic_Colors_Control_Server /// public static void Initialise() { - if (!Directory.Exists(Program.config.logPath)) { + if (!Directory.Exists(Program.config.logPath)) + { Directory.CreateDirectory(Program.config.logPath); - Write("Log Directory Created" ,logType.info); + Write("Log Directory Created", logType.info); } else { //Sort old logs string[] files = Directory.GetFiles(Program.config.logPath); - foreach(string file in files) + foreach (string file in files) { if (Path.GetExtension(file) == ".log") { @@ -55,7 +60,7 @@ namespace Galactic_Colors_Control_Server int y; int m; int d; - if(int.TryParse(new string(name.Take(4).ToArray()), out y) && int.TryParse(new string(name.Skip(5).Take(2).ToArray()), out m) && int.TryParse(new string(name.Skip(8).Take(2).ToArray()), out d)) + if (int.TryParse(new string(name.Take(4).ToArray()), out y) && int.TryParse(new string(name.Skip(5).Take(2).ToArray()), out m) && int.TryParse(new string(name.Skip(8).Take(2).ToArray()), out d)) { if (!Directory.Exists(Program.config.logPath + "/" + y + "/" + m + "/" + d)) { @@ -69,7 +74,7 @@ namespace Galactic_Colors_Control_Server } } int i = 0; - while(File.Exists(Program.config.logPath + "/" + DateTime.UtcNow.ToString("yyyy-MM-dd-", CultureInfo.InvariantCulture) + i + ".log")) { i++; } + while (File.Exists(Program.config.logPath + "/" + DateTime.UtcNow.ToString("yyyy-MM-dd-", CultureInfo.InvariantCulture) + i + ".log")) { i++; } logPath = Program.config.logPath + "/" + DateTime.UtcNow.ToString("yyyy-MM-dd-", CultureInfo.InvariantCulture) + i + ".log"; Write("Log path:" + logPath, logType.debug); Updater = new Thread(new ThreadStart(UpdaterLoop)); @@ -81,9 +86,10 @@ namespace Galactic_Colors_Control_Server /// /// Log text /// Log status - public static void Write(string text, logType type) + /// Server display modifier + public static void Write(string text, logType type, logConsole console = logConsole.normal) { - Write(new Log(text, type)); + Write(new Log(text, type, console)); } /// @@ -92,15 +98,12 @@ namespace Galactic_Colors_Control_Server /// Log struct public static void Write(Log log) { - if (log.type != logType.debug || Program.config.logLevel == logType.debug) + if (Program.config.logLevel == logType.debug || Program.config.logLevel == logType.dev) { - if(Program._debug) - { - //Add Source Method - log.text = "[" + new StackTrace().GetFrame(2).GetMethod().Name + "]: " + log.text; - } - toWriteLogs.Add(log); + //Add Source Method + log.text = "[" + new StackTrace().GetFrame(2).GetMethod().Name + "]: " + log.text; } + toWriteLogs.Add(log); } /// @@ -110,18 +113,36 @@ namespace Galactic_Colors_Control_Server { while (_run || toWriteLogs.Count > 0) { - while(toWriteLogs.Count > 0) + while (toWriteLogs.Count > 0) { Log log = toWriteLogs[0]; - File.AppendAllText(logPath,DateTime.UtcNow.ToString("[yyyy-MM-dd]", CultureInfo.InvariantCulture) + " [" + log.type.ToString().ToUpper() + "]: " + log.text + Environment.NewLine); - if(log.type >= Program.config.logLevel) { - Console.BackgroundColor = Program.config.logBackColor[(int)log.type]; - Console.ForegroundColor = Program.config.logForeColor[(int)log.type]; - Console.Write("\b"); - Console.WriteLine(DateTime.UtcNow.ToString("[yyyy-MM-dd]", CultureInfo.InvariantCulture) + ": " + log.text); - Utilities.ConsoleResetColor(); - Console.Write(">"); + if (log.type >= Program.config.logLevel) + { + File.AppendAllText(logPath, DateTime.UtcNow.ToString("[yyyy-MM-dd]", CultureInfo.InvariantCulture) + " [" + log.type.ToString().ToUpper() + "]: " + log.text + Environment.NewLine); + if (log.console != logConsole.hide) + { + Console.BackgroundColor = Program.config.logBackColor[(int)log.type]; + Console.ForegroundColor = Program.config.logForeColor[(int)log.type]; + Console.Write("\b"); + Console.WriteLine(DateTime.UtcNow.ToString("[yyyy-MM-dd]", CultureInfo.InvariantCulture) + ": " + log.text); + Utilities.ConsoleResetColor(); + Console.Write(">"); + } } + //TODO reactive show logger + /* + else + { + if(log.console == logConsole.show) + { + Console.BackgroundColor = Program.config.logBackColor[(int)log.type]; + Console.ForegroundColor = Program.config.logForeColor[(int)log.type]; + Console.Write("\b"); + Console.WriteLine(DateTime.UtcNow.ToString("[yyyy-MM-dd]", CultureInfo.InvariantCulture) + ": " + log.text); + Utilities.ConsoleResetColor(); + Console.Write(">"); + } + }*/ toWriteLogs.Remove(log); } Thread.Sleep(200); diff --git a/Galactic Colors Control Server/Party.cs b/Galactic Colors Control Server/Party.cs index 37b2c2d..70f5846 100644 --- a/Galactic Colors Control Server/Party.cs +++ b/Galactic Colors Control Server/Party.cs @@ -28,7 +28,7 @@ namespace Galactic_Colors_Control_Server { if (isPrivate) { - return (password == pass) ; + return (password == pass); } else { @@ -62,9 +62,9 @@ namespace Galactic_Colors_Control_Server get { List list = new List(); - foreach(Socket soc in Program.clients.Keys) + foreach (Socket soc in Program.clients.Keys) { - if(Program.clients[soc].party == this) { list.Add(soc); } + if (Program.clients[soc].party == this) { list.Add(soc); } } return list; } diff --git a/Galactic Colors Control Server/Program.cs b/Galactic Colors Control Server/Program.cs index aec660d..b8d26dc 100644 --- a/Galactic Colors Control Server/Program.cs +++ b/Galactic Colors Control Server/Program.cs @@ -1,274 +1,258 @@ using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Reflection; -using System.Text; +using System.Threading; namespace Galactic_Colors_Control_Server { - internal class Program - { - private const int BUFFER_SIZE = 2048; - private static readonly Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); - public static bool _debug = false; - public static bool _run = true; - public static bool _open = true; - private static readonly byte[] buffer = new byte[BUFFER_SIZE]; + internal class Program + { + private const int BUFFER_SIZE = 2048; + private static readonly Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); - public static Dictionary clients { get; private set; } = new Dictionary(); + public static bool _debug = false; + public static bool _dev = false; - public static int partyID = 0; - public static Dictionary parties { get; private set; } = new Dictionary(); - public static int selectedParty = -1; + public static bool _run = true; + public static bool _open = true; + private static readonly byte[] buffer = new byte[BUFFER_SIZE]; - public static Config config = new Config(); + public static Dictionary clients { get; private set; } = new Dictionary(); - /// - /// Server Main thread - /// - private static void Main(string[] args) - { - Console.Title = "Galactic Colors Control Server"; - Logger.Write("Galactic Colors Control Server " + Assembly.GetEntryAssembly().GetName().Version.ToString(), Logger.logType.fatal); - if (args.Length > 0) - { - switch (args[0]) - { - case "--debug": - _debug = true; - Logger.Write("SERVER IS IN DEBUG MODE !", Logger.logType.error); - break; + private static int partyID = 0; - default: - Utilities.ConsoleWrite("Use --debug or any argument"); - break; - } - } - if(Type.GetType("Mono.Runtime") != null) { Logger.Write("Using Mono", Logger.logType.warm); } - Console.Write(">"); - SetupServer(); - ConsoleLoop(); - CloseAllSockets(); - } + public static Dictionary parties { get; private set; } = new Dictionary(); + public static int selectedParty = -1; - /// - /// Initialise server and start threads. - /// - private static void SetupServer() - { - config = config.Load(); - Logger.Initialise(); - Commands.Manager.Load(); - Logger.Write("Setting up server on *:" + config.port, Logger.logType.warm); - Logger.Write("Size:" + config.size, Logger.logType.debug); - serverSocket.Bind(new IPEndPoint(IPAddress.Any, config.port)); - serverSocket.Listen(0); - serverSocket.BeginAccept(AcceptCallback, null); - Logger.Write("Server setup complete", Logger.logType.info); - } + public static Config config = new Config(); + public static Thread CheckConnected = new Thread(CheckConnectedLoop); - /// - /// Wait console commands and execute them. - /// - private static void ConsoleLoop() - { - while (_run) - { - string ConsoleInput = Console.ReadLine(); - Console.Write(">"); - ExecuteMessage(ConsoleInput, null, true); - ConsoleInput = null; - } - } + /// + /// Server Main thread + /// + private static void Main(string[] args) + { + Console.Title = "Galactic Colors Control Server"; + Logger.Write("Galactic Colors Control Server " + Assembly.GetEntryAssembly().GetName().Version.ToString(), Logger.logType.fatal); + if (args.Length > 0) + { + switch (args[0]) + { + case "--debug": + _debug = true; + Logger.Write("SERVER IS IN DEBUG MODE !", Logger.logType.error, Logger.logConsole.show); + break; - /// - /// Close all connected client. - /// - private static void CloseAllSockets() - { - Logger.Write("Stoping server", Logger.logType.warm); - config.Save(); - foreach (Socket socket in clients.Keys) - { - socket.Shutdown(SocketShutdown.Both); - Logger.Write("Shutdown " + Utilities.GetName(socket),Logger.logType.debug); - } - serverSocket.Close(); - Logger.Write("Server stoped", Logger.logType.info); - Logger._run = false; - Logger.Updater.Join(); - } + case "--dev": + _dev = true; + Logger.Write("SERVER IS IN DEV MODE !", Logger.logType.error, Logger.logConsole.show); + break; - /// - /// Wait a client and check if is correct - /// - private static void AcceptCallback(IAsyncResult AR) - { - Socket socket; + default: + Utilities.ConsoleWrite("Use --debug or --dev"); + break; + } + } + if (Type.GetType("Mono.Runtime") != null) { Logger.Write("Using Mono", Logger.logType.warm); } + Console.Write(">"); + SetupServer(); + ConsoleLoop(); + CloseAllSockets(); + } - try - { - socket = serverSocket.EndAccept(AR); - } - catch (ObjectDisposedException) // I cannot seem to avoid this (on exit when properly closing sockets) - { - return; - } - if (_open) - { - if (clients.Count < config.size) - { - AddClient(socket); - } - else - { - Logger.Write("Client can't join from " + ((IPEndPoint)socket.LocalEndPoint).Address.ToString() + " no more space", Logger.logType.warm); - Utilities.Send(socket, "/kick can't_join_no_more_space", Common.dataType.message); - socket.Close(); - } - } - else - { - Logger.Write("Client can't join from " + ((IPEndPoint)socket.LocalEndPoint).Address.ToString() + " server closed", Logger.logType.info); - Utilities.Send(socket, "/kick can't_join_server_closed", Common.dataType.message); - socket.Close(); - } - serverSocket.BeginAccept(AcceptCallback, null); - } + /// + /// Initialise server and start threads. + /// + private static void SetupServer() + { + config = config.Load(); + Logger.Initialise(); + Commands.Manager.Load(); + Logger.Write("Setting up server on *:" + config.port, Logger.logType.warm); + Logger.Write("Size:" + config.size, Logger.logType.debug); + serverSocket.Bind(new IPEndPoint(IPAddress.Any, config.port)); + serverSocket.Listen(0); + serverSocket.BeginAccept(AcceptCallback, null); + CheckConnected.Start(); + Logger.Write("Server setup complete", Logger.logType.info); + } - /// - /// Add client and initialise receive - /// - private static void AddClient(Socket socket) - { - Client client = new Client(); - clients.Add(socket, client); - socket.BeginReceive(buffer, 0, BUFFER_SIZE, SocketFlags.None, ReceiveCallback, socket); - Logger.Write("Client connection from " + Utilities.GetName(socket), Logger.logType.info); - Logger.Write("Size: " + clients.Count + "/" + config.size, Logger.logType.debug); - if (clients.Count >= config.size) - { - Logger.Write("Server full", Logger.logType.warm); - } - } + /// + /// Wait console commands and execute them. + /// + private static void ConsoleLoop() + { + while (_run) + { + string ConsoleInput = Console.ReadLine(); + Console.Write(">"); + string[] args = Common.SplitArgs(ConsoleInput); + Utilities.ConsoleWrite(new ResultData(-1, Commands.Manager.Execute(args, null, true)).ToSmallString()); + ConsoleInput = null; + } + } - /// - /// Wait a client commands and execute them - /// - private static void ReceiveCallback(IAsyncResult AR) - { - Socket current = (Socket)AR.AsyncState; - int received; + /// + /// Close all connected client. + /// + private static void CloseAllSockets() + { + Logger.Write("Stoping server", Logger.logType.warm, Logger.logConsole.show); + Utilities.Broadcast(new EventData(EventTypes.ServerKick, Common.Strings("Close"))); + config.Save(); + foreach (Socket socket in clients.Keys) + { + socket.Shutdown(SocketShutdown.Both); + Logger.Write("Shutdown " + Utilities.GetName(socket), Logger.logType.debug); + } + serverSocket.Close(); + CheckConnected.Join(2000); + Logger.Write("Server stoped", Logger.logType.info); + Logger._run = false; + Logger.Updater.Join(); + } - try - { - received = current.EndReceive(AR); - } - catch (SocketException) - { - Logger.Write("Client forcefully disconnected from " + Utilities.GetName(current) + " : SocketException", Logger.logType.info); - string username = Utilities.GetName(current); - bool connected = clients[current].status != -1; - Logger.Write("Size: " + clients.Count + "/" + config.size, Logger.logType.debug); - current.Close(); // Don't shutdown because the socket may be disposed and its disconnected anyway. - clients.Remove(current); - if (connected) { Utilities.Broadcast(username + " leave the server", Common.dataType.message); } - return; - } + /// + /// Wait a client and check if is correct + /// + private static void AcceptCallback(IAsyncResult AR) + { + Socket socket; + try + { + socket = serverSocket.EndAccept(AR); + } + catch (ObjectDisposedException) + { + return; + } + if (_open) + { + if (clients.Count < config.size) + { + AddClient(socket); + } + else + { + Logger.Write("Client can't join from " + ((IPEndPoint)socket.LocalEndPoint).Address.ToString() + " no more space", Logger.logType.warm); + Utilities.Send(socket, new EventData(EventTypes.ServerKick, Common.Strings("Space"))); + socket.Close(); + } + } + else + { + Logger.Write("Client can't join from " + ((IPEndPoint)socket.LocalEndPoint).Address.ToString() + " server closed", Logger.logType.info); + Utilities.Send(socket, new EventData(EventTypes.ServerKick, Common.Strings("Close"))); + socket.Close(); + } + serverSocket.BeginAccept(AcceptCallback, null); + } - var data = new byte[received]; - Array.Copy(buffer, data, received); + /// + /// Add client and initialise receive + /// + private static void AddClient(Socket socket) + { + Client client = new Client(); + clients.Add(socket, client); + socket.BeginReceive(buffer, 0, BUFFER_SIZE, SocketFlags.None, ReceiveCallback, socket); + Logger.Write("Client connection from " + Utilities.GetName(socket), Logger.logType.info); + Logger.Write("Size: " + clients.Count + "/" + config.size, Logger.logType.dev); + if (clients.Count >= config.size) + { + Logger.Write("Server full", Logger.logType.warm, Logger.logConsole.show); + } + } - //Server crash on command Exception - //try { - byte[] type = new byte[4]; - type = data.Take(4).ToArray(); - type.Reverse(); - Common.dataType dtype = (Common.dataType)BitConverter.ToInt32(type, 0); - byte[] bytes = null; - bytes = data.Skip(4).ToArray(); - switch (dtype) - { - case Common.dataType.message: - string text = Encoding.ASCII.GetString(bytes); - ExecuteMessage(text, current); - break; + /// + /// Wait a client commands and execute them + /// + private static void ReceiveCallback(IAsyncResult AR) + { + Socket current = (Socket)AR.AsyncState; + int received; - case Common.dataType.data: - Console.WriteLine("data"); - break; + try + { + received = current.EndReceive(AR); + } + catch (SocketException) + { + Logger.Write("Client forcefully disconnected from " + Utilities.GetName(current) + " : SocketException", Logger.logType.info); + string username = Utilities.GetName(current); + bool connected = clients[current].status != -1; + Logger.Write("Size: " + clients.Count + "/" + config.size, Logger.logType.debug); + current.Close(); // Don't shutdown because the socket may be disposed and its disconnected anyway. + clients.Remove(current); + if (connected) { Utilities.Broadcast(new EventData(EventTypes.ServerLeave, Common.Strings(username))); } + return; + } - default: - Logger.Write("Unknow type data form" + Utilities.GetName(current), Logger.logType.error); - break; - } + var data = new byte[received]; + Array.Copy(buffer, data, received); - if (clients.ContainsKey(current)) { current.BeginReceive(buffer, 0, BUFFER_SIZE, SocketFlags.None, ReceiveCallback, current); } - /*} - catch (Exception) { - Logger.Write(Utilities.GetName(current) + " : ReceiveException", Logger.logType.info); - //if (clients.ContainsKey(current)) { clients.Remove(current); } - }*/ - } + Data packet = Data.FromBytes(ref data); + if (packet != null) + { + switch (packet.GetType().Name) + { + case "RequestData": + RequestData req = (RequestData)packet; + Utilities.Send(current, new ResultData(req.id, Commands.Manager.Execute(req.args, current))); + break; - /// - /// Execute send command - /// Command - /// Sender socket - /// Is sender server? - /// - private static void ExecuteMessage(string text, Socket soc = null, bool server = false) - { - if (text.Length > 0) - { - if (text[0] == '/') - { - text = text.Substring(1); - text = text.ToLower(); - string[] array = text.Split(new char[1] { ' ' }, 4, StringSplitOptions.RemoveEmptyEntries); - if (array.Length > 0) - { - Commands.Manager.Execute(array, soc, server); - } - else - { - Utilities.Return("Any command",soc , server); - } - } - else - { - if (!Utilities.IsConnect(soc)) - { - Utilities.Send(soc, "Only identified clients can talk.", Common.dataType.message); - } - else - { - int party = -1; - if (server) - { - party = selectedParty; - } - else - { - party = clients[soc].partyID; - } - Utilities.BroadcastParty(Utilities.GetName(soc) + " : " + text, Common.dataType.message, party); - } - } - } - } + default: + Logger.Write("Wrong packet from " + Utilities.GetName(current), Logger.logType.error); + break; + } + } + else + { + Logger.Write("Wrong packet from " + Utilities.GetName(current), Logger.logType.error); + } - /// - /// Add new party with index - /// - /// Party to add - public static void AddParty(Party party) - { - parties.Add(partyID, party); - partyID++; - } - } + if (clients.ContainsKey(current)) { current.BeginReceive(buffer, 0, BUFFER_SIZE, SocketFlags.None, ReceiveCallback, current); } + } + + private static void CheckConnectedLoop() + { + while (_run) + { + foreach (Socket current in clients.Keys.ToArray()) + { + if ((current.Poll(10, SelectMode.SelectRead) && current.Available == 0) || !current.Connected) + { + string username = Utilities.GetName(current); + Logger.Write("Client forcefully disconnected from " + username + " : NotConnected", Logger.logType.info); + bool connected = clients[current].status != -1; + Logger.Write("Size: " + clients.Count + "/" + config.size, Logger.logType.debug); + current.Close(); // Don't shutdown because the socket may be disposed and its disconnected anyway. + clients.Remove(current); + if (connected) { Utilities.Broadcast(new EventData(EventTypes.ServerLeave, Common.Strings(username))); } + } + Thread.Sleep(200); + } + } + } + + /// + /// Add new party with index + /// + /// Party to add + public static void AddParty(Party party) + { + parties.Add(GetPartyID(), party); + } + + public static int GetPartyID(bool indent = true) + { + if (indent) { partyID++; } + return partyID; + } + } } \ No newline at end of file diff --git a/Galactic Colors Control Server/Properties/AssemblyInfo.cs b/Galactic Colors Control Server/Properties/AssemblyInfo.cs index 044e06f..de5bf71 100644 --- a/Galactic Colors Control Server/Properties/AssemblyInfo.cs +++ b/Galactic Colors Control Server/Properties/AssemblyInfo.cs @@ -1,8 +1,7 @@ using System.Reflection; -using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -// Les informations générales relatives à un assembly dépendent de +// Les informations générales relatives à un assembly dépendent de // l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations // associées à un assembly. [assembly: AssemblyTitle("Galactic Colors Control Server")] @@ -12,10 +11,10 @@ using System.Runtime.InteropServices; [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] -// L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly -// aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de +// L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly +// aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de // COM, affectez la valeur true à l'attribut ComVisible sur ce type. [assembly: ComVisible(false)] // Le GUID suivant est pour l'ID de la typelib si ce projet est exposé à COM -[assembly: Guid("9e3af4e1-88c6-4139-a15c-b4f633e80612")] +[assembly: Guid("9e3af4e1-88c6-4139-a15c-b4f633e80612")] \ No newline at end of file diff --git a/Galactic Colors Control Server/Utilities.cs b/Galactic Colors Control Server/Utilities.cs index da89b06..78d4bae 100644 --- a/Galactic Colors Control Server/Utilities.cs +++ b/Galactic Colors Control Server/Utilities.cs @@ -1,14 +1,11 @@ -using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; using System; -using System.IO; using System.Net; using System.Net.Sockets; -using System.Runtime.Serialization.Formatters.Binary; -using System.Text; namespace Galactic_Colors_Control_Server { - class Utilities + internal class Utilities { /// /// Check if socket is connect @@ -16,22 +13,14 @@ namespace Galactic_Colors_Control_Server /// Client socket public static bool IsConnect(Socket soc) { - if(soc == null) - { + if (soc == null) return true; - } - else - { - if (Program.clients.ContainsKey(soc)) - { - return Program.clients[soc].status != -1; - } - else - { - Logger.Write("IsConnect : Unknown client", Logger.logType.error); - return true; - } - } + + if (Program.clients.ContainsKey(soc)) + return Program.clients[soc].status != -1; + + Logger.Write("IsConnect : Unknown client", Logger.logType.error); + return false; } /// @@ -41,23 +30,23 @@ namespace Galactic_Colors_Control_Server /// Name public static string GetName(Socket soc) { - if (soc != null) - { - if (Program.clients.ContainsKey(soc)) - { - string res = Program.clients[soc].pseudo; - if (res == "") { res = ((IPEndPoint)soc.LocalEndPoint).Address.ToString(); } - return res; - } - else - { - return "?"; - } - } - else - { + if (soc == null) return "Server"; - } + + if (!Program.clients.ContainsKey(soc)) + return "?"; + + string res = Program.clients[soc].pseudo; + if (res == "") { res = ((IPEndPoint)soc.LocalEndPoint).Address.ToString(); } + return res; + } + + public static int GetParty(Socket soc) + { + if (soc == null) + return Program.selectedParty; + + return Program.clients[soc].partyID; } /// @@ -91,40 +80,23 @@ namespace Galactic_Colors_Control_Server /// /// Target socket /// Data to send - /// Type of data - public static void Send(Socket soc, object data, Common.dataType dtype) + public static void Send(Socket soc, Data packet) { - /* - Format: - 0-3: dataType - 4-x: data - */ - byte[] type = new byte[4]; - type = BitConverter.GetBytes((int)dtype); - byte[] bytes = null; - switch (dtype) + if (soc.Connected) { - case Common.dataType.message: - bytes = Encoding.ASCII.GetBytes((string)data); - break; - - case Common.dataType.data: - BinaryFormatter bf = new BinaryFormatter(); - using (MemoryStream ms = new MemoryStream()) + try + { + soc.Send(packet.ToBytes()); + if (Program.config.logLevel == Logger.logType.dev) { - bf.Serialize(ms, data); - bytes = ms.ToArray(); + Logger.Write("Send to " + GetName(soc) + " : " + packet.ToLongString(), Logger.logType.dev); } - break; - - default: - bytes = new byte[] { 1 }; - break; + } + catch (Exception e) + { + Logger.Write("Send exception to " + GetName(soc) + " : " + e.Message, Logger.logType.error); + } } - byte[] final = new byte[type.Length + bytes.Length]; - type.CopyTo(final, 0); - bytes.CopyTo(final, type.Length); - soc.Send(final); } /// @@ -132,13 +104,14 @@ namespace Galactic_Colors_Control_Server /// /// Data to send /// Type of data - public static void Broadcast(object data, Common.dataType dtype) + /// Message to display for server + public static void Broadcast(Data packet) { foreach (Socket soc in Program.clients.Keys) { - Send(soc, data, dtype); + Send(soc, packet); } - if (dtype == Common.dataType.message) { ConsoleWrite((string)data); } + ConsoleWrite(packet.ToSmallString()); } /// @@ -147,33 +120,38 @@ namespace Galactic_Colors_Control_Server /// Data to send /// Type of data /// Id of the party - public static void BroadcastParty(object data, Common.dataType dtype, int party) + /// Message to display for server + public static void BroadcastParty(Data data, int party) { - foreach(Socket soc in Program.clients.Keys) + foreach (Socket soc in Program.clients.Keys) { if (Program.clients[soc].partyID == party) { - Send(soc, data, dtype); + Send(soc, data); } } - if (dtype == Common.dataType.message) { if (Program.selectedParty == party) { ConsoleWrite((string)data); } } + if (Program.selectedParty == party) + { + ConsoleWrite(data.ToSmallString()); + } } /// /// Send or display if server /// - /// Text to send + /// Text to display if server + /// Data to send if client /// Target socket /// Is server? - public static void Return(string message, Socket soc = null, bool server = false) + public static void Return(Data data, Socket soc = null, bool server = false) { if (server) { - ConsoleWrite(message); + ConsoleWrite(data.ToSmallString()); } else { - Send(soc, message, Common.dataType.message); + Send(soc, data); } } @@ -185,60 +163,39 @@ namespace Galactic_Colors_Control_Server /// Target socket /// Is server? /// Can access? - public static bool AccessParty(ref int partyId, bool needOwn, Socket soc = null, bool server = false) + public static bool AccessParty(ref int partyId, string[] args, bool needOwn, Socket soc = null, bool server = false) { if (server) { - if(Program.selectedParty != -1) + if (Program.selectedParty == -1) + return false; + + if (Program.parties.ContainsKey(Program.selectedParty)) { - if (Program.parties.ContainsKey(Program.selectedParty)) - { - partyId = Program.selectedParty; - return true; - } - else - { - Logger.Write("Can't find party " + Program.selectedParty, Logger.logType.error); - Program.selectedParty = -1; - return false; - } + partyId = Program.selectedParty; + return true; } else { - ConsoleWrite("Join a party before"); + Program.selectedParty = -1; return false; } } else { - if(Program.clients[soc].partyID != -1) - { - if (Program.parties.ContainsKey(Program.clients[soc].partyID)) - { - if (Program.parties[Program.clients[soc].partyID].IsOwner(GetName(soc)) || !needOwn) - { - partyId = Program.clients[soc].partyID; - return true; - } - else - { - Send(soc, "You are not owner", Common.dataType.message); - return false; - } - } - else - { - Send(soc, "Can't find party " + Program.clients[soc].partyID, Common.dataType.message); - Program.clients[soc].partyID = -1; - return false; - } - } - else - { - Send(soc, "Join a party before", Common.dataType.message); + if (Program.clients[soc].partyID == -1) return false; + + if (!Program.parties.ContainsKey(Program.clients[soc].partyID)) + return false; + + if (Program.parties[Program.clients[soc].partyID].IsOwner(GetName(soc)) || !needOwn) + { + partyId = Program.clients[soc].partyID; + return true; } + else { return false; } } } } -} +} \ No newline at end of file diff --git a/Galactic Colors Control.sln b/Galactic Colors Control.sln index 2b7c6f0..89b466b 100644 --- a/Galactic Colors Control.sln +++ b/Galactic Colors Control.sln @@ -27,6 +27,12 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Common", "Common", "{75A0AD AssemblyInfoCommon.cs = AssemblyInfoCommon.cs EndProjectSection EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{4E46A1CB-6F9C-4E4E-8A9A-D62DAB09FF64}" + ProjectSection(SolutionItems) = preProject + License.md = License.md + Readme.md = Readme.md + EndProjectSection +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -35,8 +41,8 @@ Global Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {9E3AF4E1-88C6-4139-A15C-B4F633E80612}.Debug|Any CPU.ActiveCfg = Release|Any CPU - {9E3AF4E1-88C6-4139-A15C-B4F633E80612}.Debug|Any CPU.Build.0 = Release|Any CPU + {9E3AF4E1-88C6-4139-A15C-B4F633E80612}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9E3AF4E1-88C6-4139-A15C-B4F633E80612}.Debug|Any CPU.Build.0 = Debug|Any CPU {9E3AF4E1-88C6-4139-A15C-B4F633E80612}.Debug|x86.ActiveCfg = Debug|Any CPU {9E3AF4E1-88C6-4139-A15C-B4F633E80612}.Debug|x86.Build.0 = Debug|Any CPU {9E3AF4E1-88C6-4139-A15C-B4F633E80612}.Release|Any CPU.ActiveCfg = Release|Any CPU diff --git a/Galactic Colors Control/App.config b/Galactic Colors Control/App.config index d1428ad..5035d4f 100644 --- a/Galactic Colors Control/App.config +++ b/Galactic Colors Control/App.config @@ -1,6 +1,6 @@ - - - - + + + + \ No newline at end of file diff --git a/Galactic Colors Control/Program.cs b/Galactic Colors Control/Program.cs index 20cb0f4..52f66b7 100644 --- a/Galactic Colors Control/Program.cs +++ b/Galactic Colors Control/Program.cs @@ -1,13 +1,10 @@ -using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; using System; using System.Collections.Generic; -using System.IO; using System.Linq; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; -using System.Runtime.Serialization.Formatters.Binary; -using System.Text; using System.Threading; namespace Galactic_Colors_Control @@ -25,6 +22,7 @@ namespace Galactic_Colors_Control public bool isRunning { get { return _run; } } public List Output = new List(); + private int RequestId = 0; private Thread RecieveThread; @@ -66,14 +64,14 @@ namespace Galactic_Colors_Control } catch (Exception e) { - Output.Add(e.Message); PORT = 0; + Output.Add(e.Message); return null; } } else { - Output.Add("Incorrect port"); + Output.Add("Incorrect Port"); return null; } } @@ -129,9 +127,9 @@ namespace Galactic_Colors_Control /// public void ExitHost() { - Send("/exit", Common.dataType.message); // Tell the server we are exiting + Send(new RequestData(GetRequestId(), new string[1] { "exit" }));// Tell the server we are exiting _run = false; - RecieveThread.Join(); + RecieveThread.Join(2000); ClientSocket.Shutdown(SocketShutdown.Both); ClientSocket.Close(); Output.Add("Bye"); @@ -155,7 +153,27 @@ namespace Galactic_Colors_Control break; default: - Send(request, Common.dataType.message); + //TODO add key and send error here + if (request.Length > 0) + { + if (request[0] == '/') + { + request = request.Substring(1); + string[] array = request.Split(new char[1] { ' ' }, 4, StringSplitOptions.RemoveEmptyEntries); + if (array.Length > 0) + { + Send(new RequestData(GetRequestId(), array)); + } + else + { + Output.Add("Any Command"); + } + } + else + { + Send(new RequestData(GetRequestId(), new string[2] { "say", request })); + } + } break; } } @@ -177,32 +195,11 @@ namespace Galactic_Colors_Control } } - private void Send(object data, Common.dataType dtype) + private void Send(Data packet) { - byte[] type = new byte[4]; - type = BitConverter.GetBytes((int)dtype); - byte[] bytes = null; - switch (dtype) - { - case Common.dataType.message: - bytes = Encoding.ASCII.GetBytes((string)data); - break; - - case Common.dataType.data: - BinaryFormatter bf = new BinaryFormatter(); - using (MemoryStream ms = new MemoryStream()) - { - bf.Serialize(ms, data); - bytes = ms.ToArray(); - } - break; - } - byte[] final = new byte[type.Length + bytes.Length]; - type.CopyTo(final, 0); - bytes.CopyTo(final, type.Length); try { - ClientSocket.Send(final); + ClientSocket.Send(packet.ToBytes()); } catch { @@ -234,79 +231,40 @@ namespace Galactic_Colors_Control _errorCount = 0; var data = new byte[received]; Array.Copy(buffer, data, received); - byte[] type = new byte[4]; - type = data.Take(4).ToArray(); - type.Reverse(); - Common.dataType dtype = (Common.dataType)BitConverter.ToInt32(type, 0); - byte[] bytes = null; - bytes = data.Skip(4).ToArray(); - switch (dtype) + + Data packet = Data.FromBytes(ref data); + if (packet != null) { - case Common.dataType.message: - string text = Encoding.ASCII.GetString(bytes); - if (text[0] == '/') - { - text = text.Substring(1); - text = text.ToLower(); - string[] array = text.Split(new char[1] { ' ' }, 4, StringSplitOptions.RemoveEmptyEntries); - switch (array[0]) - { - case "connected": - Output.Add("Identifiaction succes"); - break; + switch (packet.GetType().Name) + { + case "EventData": + EventData eve = (EventData)packet; + Output.Add(eve.ToSmallString()); + break; - case "allreadytaken": - Output.Add("Username Allready Taken"); - break; + case "ResultData": + ResultData res = (ResultData)packet; + Output.Add(res.ToSmallString()); + break; - case "kick": - if (array.Length > 1) - { - Output.Add("Kick : " + array[1]); - } - else - { - Output.Add("Kick by server"); - } - _run = false; - break; - - case "party": - if (array[1] == "kick") - { - if (array.Length > 2) - { - Output.Add("Kick from party : " + array[2]); - } - else - { - Output.Add("Kick from party"); - } - } - else - { - Output.Add("Unknown action from server"); - } - break; - - default: - Output.Add("Unknown action from server"); - break; - } - } - else - { - Output.Add(text); - } - break; - - case Common.dataType.data: - Console.WriteLine("data"); - break; + default: + Output.Add("Wrong packet"); + break; + } + } + else + { + Output.Add("Wrong packet"); } Thread.Sleep(200); } Output.Add("/*exit*/"); } + + public int GetRequestId(bool indent = true) + { + if (indent) { RequestId++; } + return RequestId; + } } } \ No newline at end of file diff --git a/Galactic Colors Control/Properties/AssemblyInfo.cs b/Galactic Colors Control/Properties/AssemblyInfo.cs index 3e1c97a..f868a8a 100644 --- a/Galactic Colors Control/Properties/AssemblyInfo.cs +++ b/Galactic Colors Control/Properties/AssemblyInfo.cs @@ -1,8 +1,7 @@ using System.Reflection; -using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -// Les informations générales relatives à un assembly dépendent de +// Les informations générales relatives à un assembly dépendent de // l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations // associées à un assembly. [assembly: AssemblyTitle("Galactic Colors Control")] @@ -12,8 +11,8 @@ using System.Runtime.InteropServices; [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] -// L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly -// aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de +// L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly +// aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de // COM, affectez la valeur true à l'attribut ComVisible sur ce type. [assembly: ComVisible(false)] diff --git a/Readme.md b/Readme.md index 5374633..84cb47f 100644 --- a/Readme.md +++ b/Readme.md @@ -21,7 +21,7 @@ sudo apt-get install libopenal-dev mono-runtime * Galactic_Colors_Control_Console.exe => Client without GUI * Galactic_Colors_Control_GUI.exe => Client -* Galactic_Colors_Control_Server.exe => Server (Use --debug for DEBUG MODE) +* Galactic_Colors_Control_Server.exe => Server (Use --debug for DEBUG MODE or --dev at your risks) Linux ``` From 4476963f4a7382158b404ce11dacaba10431084b Mon Sep 17 00:00:00 2001 From: sheychen Date: Sun, 13 Nov 2016 01:26:03 +0100 Subject: [PATCH 05/11] ClientCore Rework and Comment --- Galactic Colors Control Common/Binary.cs | 6 + Galactic Colors Control Common/Common.cs | 33 ++- .../Galactic Colors Control Common.csproj | 1 + .../Protocol/Data.cs | 18 +- .../Protocol/EventData.cs | 22 +- .../Protocol/EventDataArgs.cs | 23 ++ .../Protocol/RequestData.cs | 11 +- .../Protocol/RequestResult.cs | 4 + .../Protocol/ResultData.cs | 21 +- .../Galactic Colors Control Console.csproj | 4 + Galactic Colors Control Console/Program.cs | 83 +++---- Galactic Colors Control GUI/Game1.cs | 32 +-- Galactic Colors Control Server/Logger.cs | 5 +- Galactic Colors Control Server/Program.cs | 4 +- Galactic Colors Control Server/Utilities.cs | 35 +-- Galactic Colors Control/Program.cs | 219 ++++++++++-------- 16 files changed, 307 insertions(+), 214 deletions(-) create mode 100644 Galactic Colors Control Common/Protocol/EventDataArgs.cs diff --git a/Galactic Colors Control Common/Binary.cs b/Galactic Colors Control Common/Binary.cs index 0de67f7..9d9b905 100644 --- a/Galactic Colors Control Common/Binary.cs +++ b/Galactic Colors Control Common/Binary.cs @@ -4,6 +4,9 @@ using System.Text; namespace Galactic_Colors_Control_Common { + /// + /// All used types - byte[] convertions + /// public static class Binary { public static bool ToBool(ref byte[] bytes) @@ -14,6 +17,7 @@ namespace Galactic_Colors_Control_Common return data[1] == 1 ? true : false; } + ///1 byte public static byte[] FromBool(bool x) { return x ? new byte[1] { 1 } : new byte[1] { 0 }; @@ -27,6 +31,7 @@ namespace Galactic_Colors_Control_Common return text; } + ///len(in bytes) + string public static byte[] FromString(string text) { byte[] data = Encoding.ASCII.GetBytes(text); @@ -48,6 +53,7 @@ namespace Galactic_Colors_Control_Common return BitConverter.ToInt32(data, 0); } + ///4 bytes public static byte[] FromInt(int x) { byte[] data = new byte[4]; diff --git a/Galactic Colors Control Common/Common.cs b/Galactic Colors Control Common/Common.cs index 8c63ca2..8bf281f 100644 --- a/Galactic Colors Control Common/Common.cs +++ b/Galactic Colors Control Common/Common.cs @@ -5,6 +5,35 @@ namespace Galactic_Colors_Control_Common { public static class Common { + /// + /// Write line in console with correct colors + /// + /// Text to write + /// Foreground color + /// Background color + public static void ConsoleWrite(string v, ConsoleColor Fore = ConsoleColor.White, ConsoleColor Back = ConsoleColor.Black) + { + Console.Write("\b"); + Console.ForegroundColor = Fore; + Console.BackgroundColor = Back; + Console.WriteLine(v); + ConsoleResetColor(); + Console.Write(">"); + } + + /// + /// Reset Console Colors + /// For non black background console as Ubuntu + /// + public static void ConsoleResetColor() + { + Console.ResetColor(); + Console.BackgroundColor = ConsoleColor.Black; + } + + /// + /// Simpler string array creation + /// public static string[] Strings(params string[] args) { return args; @@ -17,7 +46,7 @@ namespace Galactic_Colors_Control_Common { foreach (string str in array) { - text += (str + Environment.NewLine); + text += ((text == "" ? "" : Environment.NewLine) + str); } } return text; @@ -28,7 +57,7 @@ namespace Galactic_Colors_Control_Common string text = ""; foreach (int i in array) { - text += (i.ToString() + Environment.NewLine); + text += ((text == "" ? "" : Environment.NewLine) + i.ToString()); } return text; } diff --git a/Galactic Colors Control Common/Galactic Colors Control Common.csproj b/Galactic Colors Control Common/Galactic Colors Control Common.csproj index 3455210..293857c 100644 --- a/Galactic Colors Control Common/Galactic Colors Control Common.csproj +++ b/Galactic Colors Control Common/Galactic Colors Control Common.csproj @@ -52,6 +52,7 @@ + diff --git a/Galactic Colors Control Common/Protocol/Data.cs b/Galactic Colors Control Common/Protocol/Data.cs index 6d91be8..951f671 100644 --- a/Galactic Colors Control Common/Protocol/Data.cs +++ b/Galactic Colors Control Common/Protocol/Data.cs @@ -1,9 +1,16 @@ namespace Galactic_Colors_Control_Common.Protocol { + /// + /// Packet Master Class + /// public class Data { public enum DataType { Request, Result, Event }; - + + /// + /// Create Packet from bytes + /// + /// row bytes (remove used bytes) public static Data FromBytes(ref byte[] bytes) { switch ((DataType)Binary.ToInt(ref bytes)) @@ -22,16 +29,25 @@ } } + /// + /// Small readable text + /// public virtual string ToSmallString() { return null; } + /// + /// Long readble text + /// public virtual string ToLongString() { return null; } + /// + /// Generate bytes to send + /// public virtual byte[] ToBytes() { return new byte[0]; diff --git a/Galactic Colors Control Common/Protocol/EventData.cs b/Galactic Colors Control Common/Protocol/EventData.cs index 57c6175..7918063 100644 --- a/Galactic Colors Control Common/Protocol/EventData.cs +++ b/Galactic Colors Control Common/Protocol/EventData.cs @@ -1,16 +1,28 @@ namespace Galactic_Colors_Control_Common.Protocol { - public enum EventTypes { ChatMessage, ServerJoin, ServerLeave, ServerKick, PartyJoin, PartyLeave, PartyKick } + public enum EventTypes + { + ChatMessage, //To displat in chatbox + ServerJoin, //A player join server + ServerLeave, //A player leave server + ServerKick, //You are kick from server + PartyJoin, //A player join your party + PartyLeave, //A player leave your party + PartyKick //Tou are jick from your party + } + /// + /// Server to Client Packet + /// public class EventData : Data { public EventTypes type; - public string[] data; + public string[] data; //EventArgs like - public EventData(EventTypes p1, string[] p2 = null) + public EventData(EventTypes Type, string[] Data = null) { - type = p1; - data = p2; + type = Type; + data = Data; } public EventData(ref byte[] bytes) diff --git a/Galactic Colors Control Common/Protocol/EventDataArgs.cs b/Galactic Colors Control Common/Protocol/EventDataArgs.cs new file mode 100644 index 0000000..e17413b --- /dev/null +++ b/Galactic Colors Control Common/Protocol/EventDataArgs.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Galactic_Colors_Control_Common.Protocol +{ + /// + /// Hide EventData in EventArgs + /// for OnEvent Handler + /// + public class EventDataArgs : EventArgs + { + private EventData m_Data; + public EventDataArgs(EventData _myData) + { + m_Data = _myData; + } + + public EventData Data { get { return m_Data; } } + } +} diff --git a/Galactic Colors Control Common/Protocol/RequestData.cs b/Galactic Colors Control Common/Protocol/RequestData.cs index 6ceb701..d686c05 100644 --- a/Galactic Colors Control Common/Protocol/RequestData.cs +++ b/Galactic Colors Control Common/Protocol/RequestData.cs @@ -1,14 +1,17 @@ namespace Galactic_Colors_Control_Common.Protocol { + /// + /// Client to Server Data request packet 'allways' return ResultData + /// public class RequestData : Data { - public int id; + public int id; //Client Size autoindent id public string[] args; - public RequestData(int p1, string[] p2) + public RequestData(int Id, string[] Args) { - id = p1; - args = p2; + id = Id; + args = Args; } public RequestData(ref byte[] bytes) diff --git a/Galactic Colors Control Common/Protocol/RequestResult.cs b/Galactic Colors Control Common/Protocol/RequestResult.cs index 9a97914..ac90e00 100644 --- a/Galactic Colors Control Common/Protocol/RequestResult.cs +++ b/Galactic Colors Control Common/Protocol/RequestResult.cs @@ -1,5 +1,9 @@ namespace Galactic_Colors_Control_Common.Protocol { + /// + /// Part of RequestData + /// Commands return + /// public class RequestResult { public ResultTypes type; diff --git a/Galactic Colors Control Common/Protocol/ResultData.cs b/Galactic Colors Control Common/Protocol/ResultData.cs index 58c9f4e..137891e 100644 --- a/Galactic Colors Control Common/Protocol/ResultData.cs +++ b/Galactic Colors Control Common/Protocol/ResultData.cs @@ -2,24 +2,27 @@ { public enum ResultTypes { Error, OK } + /// + /// Server to Client Result from RequestData + /// public class ResultData : Data { - public int id; + public int id; //Client Side Autoindent public ResultTypes type; public string[] result; - public ResultData(int p1, ResultTypes p2, string[] p3 = null) + public ResultData(int Id, ResultTypes Type, string[] Result = null) { - id = p1; - type = p2; - result = p3; + id = Id; + type = Type; + result = Result; } - public ResultData(int p1, RequestResult p2) + public ResultData(int Id, RequestResult Result) { - id = p1; - type = p2.type; - result = p2.result; + id = Id; + type = Result.type; + result = Result.result; } public ResultData(ref byte[] bytes) diff --git a/Galactic Colors Control Console/Galactic Colors Control Console.csproj b/Galactic Colors Control Console/Galactic Colors Control Console.csproj index 7f677b3..50b8893 100644 --- a/Galactic Colors Control Console/Galactic Colors Control Console.csproj +++ b/Galactic Colors Control Console/Galactic Colors Control Console.csproj @@ -51,6 +51,10 @@ + + {022A69CE-22B5-4934-BE9F-A9C6DF9557ED} + Galactic Colors Control Common + {93582ce8-c8c8-4e19-908b-d671ecbade25} Galactic Colors Control diff --git a/Galactic Colors Control Console/Program.cs b/Galactic Colors Control Console/Program.cs index fd0dce0..9b1a550 100644 --- a/Galactic Colors Control Console/Program.cs +++ b/Galactic Colors Control Console/Program.cs @@ -1,40 +1,43 @@ using Galactic_Colors_Control; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; using System; using System.Reflection; using System.Threading; namespace Galactic_Colors_Control_Console { + /// + /// Console Client + /// internal class Program { private static Client client; private static bool run = true; - private static Thread Writer; + private static char commandChar = '/'; private static void Main() { client = new Client(); - Console.Title = "Galactic Colors Control Client"; + client.OnEvent += new EventHandler(OnEvent); //Set OnEvent function + Console.Title = "Galactic Colors Control Client"; //Start display Console.Write(">"); - Write("Galactic Colors Control Client"); - Write("Console " + Assembly.GetEntryAssembly().GetName().Version.ToString()); + Common.ConsoleWrite("Galactic Colors Control Client", ConsoleColor.Red); + Common.ConsoleWrite("Console " + Assembly.GetEntryAssembly().GetName().Version.ToString(), ConsoleColor.DarkYellow); bool hostSet = false; - while (!hostSet) + while (!hostSet) //Request hostname { - Write("Enter server host:"); + Common.ConsoleWrite("Enter server host:"); string host = client.ValidateHost(Console.ReadLine()); - if (host == null) + if (host[0] == '*') { - foreach (string output in client.Output.ToArray()) - { - Write(output); - } - client.Output.Clear(); + host = host.Substring(1); + Common.ConsoleWrite(host, ConsoleColor.Red); client.ResetHost(); } else { - Write("Use " + host + "? y/n"); + Common.ConsoleWrite("Use " + host + "? y/n"); ConsoleKeyInfo c = new ConsoleKeyInfo(); while (c.Key != ConsoleKey.Y && c.Key != ConsoleKey.N) { @@ -50,58 +53,48 @@ namespace Galactic_Colors_Control_Console } } } - if (client.ConnectHost()) + if (client.ConnectHost()) //Try connection { run = true; - Writer = new Thread(OutputWriter); - Writer.Start(); while (run) { - client.SendRequest(Console.ReadLine()); + Execute(Console.ReadLine()); //Process console input if (!client.isRunning) { run = false; } } - Writer.Join(); Console.Read(); } else { - foreach (string output in client.Output.ToArray()) - { - Write(output); - } - client.Output.Clear(); + Common.ConsoleWrite("Can't connect sorry. Bye", ConsoleColor.Red); Console.Read(); } } - private static void OutputWriter() + private static void Execute(string input) { - while (run || client.Output.Count > 0) - { - if (client.Output.Count > 0) - { - string text = client.Output[0]; - switch (text) - { - case "/clear": - Console.Clear(); - break; + if (input == null) + return; - default: - Write(text); - break; - } - client.Output.Remove(text); - } - Thread.Sleep(200); + if (input.Length == 0) + return; + + string[] req; + if(input[0] == commandChar) + { + input = input.Substring(1); + req = Common.SplitArgs(input); } + else + { + req = Common.Strings("say", input); + } + Common.ConsoleWrite(client.Request(req).ToSmallString()); //Add processing (common) } - private static void Write(string text) + private static void OnEvent(object sender, EventArgs e) { - Console.Write("\b"); - Console.WriteLine(text); - Console.Write(">"); + EventData eve = ((EventDataArgs)e).Data; + Common.ConsoleWrite(eve.ToSmallString()); //TODO add processing (common) } } } \ No newline at end of file diff --git a/Galactic Colors Control GUI/Game1.cs b/Galactic Colors Control GUI/Game1.cs index 9b900a4..57e86c2 100644 --- a/Galactic Colors Control GUI/Game1.cs +++ b/Galactic Colors Control GUI/Game1.cs @@ -1,4 +1,5 @@ -using Galactic_Colors_Control; +//TODO comment and update for new clientcore +using Galactic_Colors_Control; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; @@ -211,7 +212,8 @@ namespace Galactic_Colors_Control_GUI case GameStatus.Game: if (showOutput) - if (client.Output.Count > 0) + //TODO + /*if (client.Output.Count > 0) { string text = client.Output[0]; switch (text) @@ -225,7 +227,7 @@ namespace Galactic_Colors_Control_GUI break; } client.Output.Remove(text); - } + }*/ if (!client.isRunning) { gameStatus = GameStatus.Kick; } break; } @@ -327,7 +329,7 @@ namespace Galactic_Colors_Control_GUI } if (GUI.Button(new Rectangle(ScreenWidth / 2 + 5, ScreenHeight / 4 + 100, 135, 40), buttonsSprites[0], "No", basicFont)) { - client.Output.Clear(); + //TODO client.Output.Clear(); client.ResetHost(); GUI.ResetFocus(); showYNMessage = false; @@ -406,7 +408,7 @@ namespace Galactic_Colors_Control_GUI if (showChat) { GUI.Box(new Rectangle(0, 30, 310, 310), buttonsSprites[0]); - if (GUI.TextField(new Rectangle(5, 35, 305, 20), ref chatInput, basicFont, null, Manager.textAlign.centerLeft, "Enter message")) { if (chatInput != null) { ChatAdd(chatInput); client.SendRequest(chatInput); chatInput = null; } } + //TODO if (GUI.TextField(new Rectangle(5, 35, 305, 20), ref chatInput, basicFont, null, Manager.textAlign.centerLeft, "Enter message")) { if (chatInput != null) { ChatAdd(chatInput); client.SendRequest(chatInput); chatInput = null; } } GUI.Label(new Rectangle(5, 60, 305, 245), chatText, smallFont, null, Manager.textAlign.topLeft, true); } @@ -446,9 +448,9 @@ namespace Galactic_Colors_Control_GUI { messageTitle = "Error"; messageText = string.Empty; - foreach (string line in client.Output.ToArray()) { messageText += (line + Environment.NewLine); } + //TODO foreach (string line in client.Output.ToArray()) { messageText += (line + Environment.NewLine); } showOKMessage = true; - client.Output.Clear(); + //TODO client.Output.Clear(); client.ResetHost(); ; } else @@ -470,9 +472,9 @@ namespace Galactic_Colors_Control_GUI { messageTitle = "Error"; messageText = string.Empty; - foreach (string line in client.Output.ToArray()) { messageText += (line + Environment.NewLine); } + //TODO foreach (string line in client.Output.ToArray()) { messageText += (line + Environment.NewLine); } showOKMessage = true; - client.Output.Clear(); + //TODO client.Output.Clear(); client.ResetHost(); } showLoading = false; @@ -485,9 +487,9 @@ namespace Galactic_Colors_Control_GUI { if (username.Length > 3) { - client.Output.Clear(); - client.SendRequest("/connect " + username); - int wait = 0; + //TODO client.Output.Clear(); + //TODO client.SendRequest("/connect " + username); + /*int wait = 0; while (wait < 20) { if (client.Output.Count > 0) @@ -523,7 +525,7 @@ namespace Galactic_Colors_Control_GUI showOKMessage = true; showLoading = false; client.Output.Clear(); - } + }*/ } } showLoading = false; @@ -533,6 +535,8 @@ namespace Galactic_Colors_Control_GUI { showLoading = true; GUI.ResetFocus(); + //TODO + /* if (showParty) { client.SendRequest("/party leave"); @@ -584,7 +588,7 @@ namespace Galactic_Colors_Control_GUI showLoading = false; client.Output.Clear(); } - } + }*/ } private void ChatAdd(string text) diff --git a/Galactic Colors Control Server/Logger.cs b/Galactic Colors Control Server/Logger.cs index 3c84d79..176ceee 100644 --- a/Galactic Colors Control Server/Logger.cs +++ b/Galactic Colors Control Server/Logger.cs @@ -1,4 +1,5 @@ -using System; +using Galactic_Colors_Control_Common; +using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; @@ -125,7 +126,7 @@ namespace Galactic_Colors_Control_Server Console.ForegroundColor = Program.config.logForeColor[(int)log.type]; Console.Write("\b"); Console.WriteLine(DateTime.UtcNow.ToString("[yyyy-MM-dd]", CultureInfo.InvariantCulture) + ": " + log.text); - Utilities.ConsoleResetColor(); + Common.ConsoleResetColor(); Console.Write(">"); } } diff --git a/Galactic Colors Control Server/Program.cs b/Galactic Colors Control Server/Program.cs index b8d26dc..729be6b 100644 --- a/Galactic Colors Control Server/Program.cs +++ b/Galactic Colors Control Server/Program.cs @@ -54,7 +54,7 @@ namespace Galactic_Colors_Control_Server break; default: - Utilities.ConsoleWrite("Use --debug or --dev"); + Common.ConsoleWrite("Use --debug or --dev"); break; } } @@ -92,7 +92,7 @@ namespace Galactic_Colors_Control_Server string ConsoleInput = Console.ReadLine(); Console.Write(">"); string[] args = Common.SplitArgs(ConsoleInput); - Utilities.ConsoleWrite(new ResultData(-1, Commands.Manager.Execute(args, null, true)).ToSmallString()); + Common.ConsoleWrite(new ResultData(-1, Commands.Manager.Execute(args, null, true)).ToSmallString()); ConsoleInput = null; } } diff --git a/Galactic Colors Control Server/Utilities.cs b/Galactic Colors Control Server/Utilities.cs index 78d4bae..cfe562c 100644 --- a/Galactic Colors Control Server/Utilities.cs +++ b/Galactic Colors Control Server/Utilities.cs @@ -1,4 +1,5 @@ -using Galactic_Colors_Control_Common.Protocol; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; using System; using System.Net; using System.Net.Sockets; @@ -49,32 +50,6 @@ namespace Galactic_Colors_Control_Server return Program.clients[soc].partyID; } - /// - /// Write line in console with correct colors - /// - /// Text to write - /// Foreground color - /// Background color - public static void ConsoleWrite(string v, ConsoleColor Fore = ConsoleColor.White, ConsoleColor Back = ConsoleColor.Black) - { - Console.Write("\b"); - Console.ForegroundColor = Fore; - Console.BackgroundColor = Back; - Console.WriteLine(v); - ConsoleResetColor(); - Console.Write(">"); - } - - /// - /// Reset Console Colors - /// For non black background console as Ubuntu - /// - public static void ConsoleResetColor() - { - Console.ResetColor(); - Console.BackgroundColor = ConsoleColor.Black; - } - /// /// Send data to specified socket /// @@ -111,7 +86,7 @@ namespace Galactic_Colors_Control_Server { Send(soc, packet); } - ConsoleWrite(packet.ToSmallString()); + Common.ConsoleWrite(packet.ToSmallString()); } /// @@ -132,7 +107,7 @@ namespace Galactic_Colors_Control_Server } if (Program.selectedParty == party) { - ConsoleWrite(data.ToSmallString()); + Common.ConsoleWrite(data.ToSmallString()); } } @@ -147,7 +122,7 @@ namespace Galactic_Colors_Control_Server { if (server) { - ConsoleWrite(data.ToSmallString()); + Common.ConsoleWrite(data.ToSmallString()); } else { diff --git a/Galactic Colors Control/Program.cs b/Galactic Colors Control/Program.cs index 52f66b7..099e81a 100644 --- a/Galactic Colors Control/Program.cs +++ b/Galactic Colors Control/Program.cs @@ -1,4 +1,5 @@ -using Galactic_Colors_Control_Common.Protocol; +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; using System; using System.Collections.Generic; using System.Linq; @@ -9,34 +10,62 @@ using System.Threading; namespace Galactic_Colors_Control { + /// + /// Client CrossPlatform Core + /// public class Client { private Socket ClientSocket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); - public int PORT = 0; - private int _errorCount = 0; - private bool _run = true; - public string IP = null; + public string IP = null; //Server IP + public int PORT = 0; //Server Port + public struct CoreConfig + { + public int resultsBuffer; //Max amount of waiting results + public int timeout; //Request timeout in ms + public int refresh; //Threads sleep in ms + + public CoreConfig(int buffer, int time, int speed) + { + resultsBuffer = buffer; + timeout = time; + refresh = speed; + } + } + + public CoreConfig config = new CoreConfig(20, 2000, 200); //Set default config + + private int _errorCount = 0; //Leave if > 5 + + private bool _run = true; //Thread Stop public bool isRunning { get { return _run; } } - public List Output = new List(); private int RequestId = 0; + private List Results = new List(); + private Thread RecieveThread; //Main Thread + public EventHandler OnEvent; //Execute on EventData reception (must be short or async) - private Thread RecieveThread; - + /// + /// Soft Server Reset + /// public void ResetHost() { IP = null; PORT = 0; } + /// + /// Test and Convert Hostname to Address + /// + /// Hostname + /// Address(IP:PORT) or Error(*'text') public string ValidateHost(string text) { - if (text == null) { text = ""; } - string[] parts = text.Split(new char[] { ':' }, 2, StringSplitOptions.RemoveEmptyEntries); - if (parts.Length == 0) + if (text == null) { text = ""; } //Prevent NullException + string[] parts = text.Split(new char[] { ':' }, 2, StringSplitOptions.RemoveEmptyEntries); //Split IP and Port + if (parts.Length == 0) //Default config (localhost) { parts = new string[] { "" }; PORT = 25001; @@ -45,7 +74,7 @@ namespace Galactic_Colors_Control { if (parts.Length > 1) { - if (!int.TryParse(parts[1], out PORT)) { PORT = 0; } + if (!int.TryParse(parts[1], out PORT)) { PORT = 0; } //Check Port if (PORT < 0 || PORT > 65535) { PORT = 0; } } else @@ -57,29 +86,28 @@ namespace Galactic_Colors_Control { try { - IPHostEntry ipHostEntry = Dns.GetHostEntry(parts[0]); - IPAddress host = ipHostEntry.AddressList.First(a => a.AddressFamily == AddressFamily.InterNetwork); + IPHostEntry ipHostEntry = Dns.GetHostEntry(parts[0]);//Resolve Hostname + IPAddress host = ipHostEntry.AddressList.First(a => a.AddressFamily == AddressFamily.InterNetwork);//Get IPv4 IP = host.ToString(); return IP + ":" + PORT; } catch (Exception e) { PORT = 0; - Output.Add(e.Message); - return null; + return "*" + e.Message; } } else { - Output.Add("Incorrect Port"); - return null; + return "*Port Format"; } } /// - /// Set IP and PORT before + /// Start Server connection /// - /// Connection succes + /// Setup IP and Port before + /// connection success public bool ConnectHost() { int attempts = 0; @@ -89,32 +117,27 @@ namespace Galactic_Colors_Control try { attempts++; - Output.Add("Connection attempt " + attempts); ClientSocket.Connect(IP, PORT); } - catch (SocketException) - { - Output.Clear(); - } + catch (SocketException) { } } - if (attempts < 5) + if (attempts < 5) //Connection success { - Output.Clear(); - Output.Add("Connected to " + IP.ToString()); _run = true; - RecieveThread = new Thread(ReceiveLoop); + RecieveThread = new Thread(ReceiveLoop); //Starting Main Thread RecieveThread.Start(); return true; } else { - Output.Clear(); - Output.Add("Can't connected to " + IP.ToString()); ResetSocket(); return false; } } + /// + /// Hard Reset (unsafe) + /// private void ResetSocket() { ClientSocket.Close(); @@ -128,91 +151,78 @@ namespace Galactic_Colors_Control public void ExitHost() { Send(new RequestData(GetRequestId(), new string[1] { "exit" }));// Tell the server we are exiting - _run = false; + _run = false; //Stopping Thread RecieveThread.Join(2000); ClientSocket.Shutdown(SocketShutdown.Both); ClientSocket.Close(); - Output.Add("Bye"); ResetHost(); } - public void SendRequest(string request) + /// + /// Send RequestData to server + /// + /// Request args + /// ResultData or Timeout + public ResultData Request(string[] args) { - switch (request.ToLower()) + // TODO filter Client Side Requests + RequestData req = new RequestData(GetRequestId(), args); + if (!Send(req)) + return new ResultData(req.id, ResultTypes.Error, Common.Strings("Send Exception")); + + DateTime timeoutDate = DateTime.Now.AddMilliseconds(config.timeout); //Create timeout DataTime + while (timeoutDate > DateTime.Now) { - case "/exit": - ExitHost(); - break; - - case "/ping": - PingHost(); - break; - - case "/clear": - Output.Add("/clear"); - break; - - default: - //TODO add key and send error here - if (request.Length > 0) + foreach (ResultData res in Results.ToArray()) //Check all results + { + if (res.id == req.id) { - if (request[0] == '/') - { - request = request.Substring(1); - string[] array = request.Split(new char[1] { ' ' }, 4, StringSplitOptions.RemoveEmptyEntries); - if (array.Length > 0) - { - Send(new RequestData(GetRequestId(), array)); - } - else - { - Output.Add("Any Command"); - } - } - else - { - Send(new RequestData(GetRequestId(), new string[2] { "say", request })); - } + Results.Remove(res); + return res; } - break; + } + Thread.Sleep(config.refresh); } + return new ResultData(req.id, ResultTypes.Error, Common.Strings("Timeout")); } - private void PingHost() + /// + /// Ping Current Server IP + /// + /// Time in ms or 'Timeout' + private string PingHost() { - Ping p = new Ping(); - PingReply r; + Ping ping = new Ping(); + PingReply reply; - r = p.Send(IP); + reply = ping.Send(IP); + if (reply.Status == IPStatus.Success) + return reply.RoundtripTime.ToString(); - if (r.Status == IPStatus.Success) - { - Output.Add(r.RoundtripTime.ToString() + " ms."); - } - else - { - Output.Add("Time out"); - } + return "Timeout"; } - private void Send(Data packet) + /// + /// Send Data object to server + /// + /// Send success + private bool Send(Data packet) { try { ClientSocket.Send(packet.ToBytes()); + return true; } - catch + catch //Can't contact server { - Output.Add("Can't contact server : " + _errorCount); _errorCount++; } - if (_errorCount >= 5) - { - Output.Add("Kick : too_much_errors"); - _run = false; - } + return false; } + /// + /// Main Thread + /// private void ReceiveLoop() { while (_run) @@ -225,40 +235,40 @@ namespace Galactic_Colors_Control } catch { - Output.Add("Server timeout"); + _errorCount++; + } + if (_errorCount >= 5) + { + _run = false; } if (received == 0) return; _errorCount = 0; var data = new byte[received]; Array.Copy(buffer, data, received); - Data packet = Data.FromBytes(ref data); + Data packet = Data.FromBytes(ref data); //Create Data object from recieve bytes if (packet != null) { switch (packet.GetType().Name) { case "EventData": EventData eve = (EventData)packet; - Output.Add(eve.ToSmallString()); + if (OnEvent != null) + OnEvent.Invoke(this, new EventDataArgs(eve)); break; case "ResultData": ResultData res = (ResultData)packet; - Output.Add(res.ToSmallString()); + ResultAdd(res); break; - default: - Output.Add("Wrong packet"); + default: //Ignore others Packets break; } } - else - { - Output.Add("Wrong packet"); - } - Thread.Sleep(200); + Thread.Sleep(config.refresh); } - Output.Add("/*exit*/"); + //TODOOutput.Add("/*exit*/"); } public int GetRequestId(bool indent = true) @@ -266,5 +276,14 @@ namespace Galactic_Colors_Control if (indent) { RequestId++; } return RequestId; } + + /// + /// Add to Results + /// + public void ResultAdd(ResultData res) + { + while (Results.Count + 1 > config.resultsBuffer) { Results.RemoveAt(0); } //Removes firsts + Results.Add(res); + } } } \ No newline at end of file From 507f9c625f935b368f246b11808b4e599dba44a9 Mon Sep 17 00:00:00 2001 From: sheychen Date: Mon, 14 Nov 2016 15:09:44 +0100 Subject: [PATCH 06/11] Gui Client Start Update --- Galactic Colors Control Console/Program.cs | 5 +- Galactic Colors Control GUI/Background.cs | 74 +++ .../Galactic Colors Control GUI.csproj | 14 +- Galactic Colors Control GUI/Game.cs | 214 ++++++ Galactic Colors Control GUI/Game1.cs | 614 ------------------ Galactic Colors Control GUI/Program.cs | 3 +- .../States/ConnectState.cs | 150 +++++ .../States/GameState.cs | 169 +++++ .../States/IndentificationState.cs | 101 +++ .../States/MainMenuState.cs | 61 ++ .../States/OptionsState.cs | 17 + Galactic Colors Control GUI/States/State.cs | 20 + .../States/TitleState.cs | 41 ++ Galactic Colors Control GUI/Utilities.cs | 21 + Galactic Colors Control.sln | 3 +- Galactic Colors Control/Program.cs | 8 +- 16 files changed, 891 insertions(+), 624 deletions(-) create mode 100644 Galactic Colors Control GUI/Background.cs create mode 100644 Galactic Colors Control GUI/Game.cs delete mode 100644 Galactic Colors Control GUI/Game1.cs create mode 100644 Galactic Colors Control GUI/States/ConnectState.cs create mode 100644 Galactic Colors Control GUI/States/GameState.cs create mode 100644 Galactic Colors Control GUI/States/IndentificationState.cs create mode 100644 Galactic Colors Control GUI/States/MainMenuState.cs create mode 100644 Galactic Colors Control GUI/States/OptionsState.cs create mode 100644 Galactic Colors Control GUI/States/State.cs create mode 100644 Galactic Colors Control GUI/States/TitleState.cs diff --git a/Galactic Colors Control Console/Program.cs b/Galactic Colors Control Console/Program.cs index 9b1a550..dbc657a 100644 --- a/Galactic Colors Control Console/Program.cs +++ b/Galactic Colors Control Console/Program.cs @@ -3,7 +3,6 @@ using Galactic_Colors_Control_Common; using Galactic_Colors_Control_Common.Protocol; using System; using System.Reflection; -using System.Threading; namespace Galactic_Colors_Control_Console { @@ -23,7 +22,7 @@ namespace Galactic_Colors_Control_Console Console.Title = "Galactic Colors Control Client"; //Start display Console.Write(">"); Common.ConsoleWrite("Galactic Colors Control Client", ConsoleColor.Red); - Common.ConsoleWrite("Console " + Assembly.GetEntryAssembly().GetName().Version.ToString(), ConsoleColor.DarkYellow); + Common.ConsoleWrite("Console " + Assembly.GetEntryAssembly().GetName().Version.ToString(), ConsoleColor.Yellow); bool hostSet = false; while (!hostSet) //Request hostname { @@ -79,7 +78,7 @@ namespace Galactic_Colors_Control_Console return; string[] req; - if(input[0] == commandChar) + if (input[0] == commandChar) { input = input.Substring(1); req = Common.SplitArgs(input); diff --git a/Galactic Colors Control GUI/Background.cs b/Galactic Colors Control GUI/Background.cs new file mode 100644 index 0000000..b04284c --- /dev/null +++ b/Galactic Colors Control GUI/Background.cs @@ -0,0 +1,74 @@ +using System; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; + +namespace Galactic_Colors_Control_GUI +{ + /// + /// Multilayer Background + /// + public class Background + { + private double[] backgroundX; + private double[] backgroundY; + private Texture2D[] backSprites; + private double[] ratio; + + public double speedX = 0; + public double speedY = 0; + + internal void Draw(object spriteBatch) + { + throw new NotImplementedException(); + } + + /// + /// Background.lenght == Ratio.Lenght + /// + public Background(Texture2D[] BackSprites, double[] Ratio) + { + backSprites = BackSprites; + ratio = Ratio; + backgroundX = new double[backSprites.Length]; + backgroundY = new double[backSprites.Length]; + } + + /// + /// Manual Move + /// + public void Move(double x, double y) + { + for (int index = 0; index < backSprites.Length; index++) + { + backgroundX[index] += (x * ratio[index]); + backgroundY[index] += (y * ratio[index]); + if (backgroundX[index] > backSprites[index].Width) { backgroundX[index] = 0; } + if (backgroundY[index] > backSprites[index].Height) { backgroundY[index] = 0; } + if (backgroundX[index] < 0) { backgroundX[index] = backSprites[index].Width; } + if (backgroundY[index] < 0) { backgroundY[index] = backSprites[index].Height; } + } + } + + /// + /// AutoMove for speedX and speedY + /// + public void Update() + { + Move(speedX, speedY); + } + + public void Draw(SpriteBatch spriteBatch) + { + for (int index = 0; index < backSprites.Length; index++) + { + for (int X = -1; X < Game.singleton.ScreenWidth / backSprites[index].Width + 1; X++) + { + for (int Y = -1; Y < Game.singleton.ScreenHeight / backSprites[index].Height + 1; Y++) + { + spriteBatch.Draw(backSprites[index], new Rectangle(X * backSprites[index].Width + (int)backgroundX[index], Y * backSprites[index].Height + (int)backgroundY[index], backSprites[index].Width, backSprites[index].Height), Color.White); + } + } + } + } + } +} diff --git a/Galactic Colors Control GUI/Galactic Colors Control GUI.csproj b/Galactic Colors Control GUI/Galactic Colors Control GUI.csproj index fb69eef..eb60deb 100644 --- a/Galactic Colors Control GUI/Galactic Colors Control GUI.csproj +++ b/Galactic Colors Control GUI/Galactic Colors Control GUI.csproj @@ -44,9 +44,17 @@ Properties\AssemblyInfoCommon.cs - + + + + + + + + + @@ -114,6 +122,10 @@ + + {022a69ce-22b5-4934-be9f-a9c6df9557ed} + Galactic Colors Control Common + {93582ce8-c8c8-4e19-908b-d671ecbade25} Galactic Colors Control diff --git a/Galactic Colors Control GUI/Game.cs b/Galactic Colors Control GUI/Game.cs new file mode 100644 index 0000000..788f013 --- /dev/null +++ b/Galactic Colors Control GUI/Game.cs @@ -0,0 +1,214 @@ +using Galactic_Colors_Control; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Audio; +using Microsoft.Xna.Framework.Content; +using Microsoft.Xna.Framework.Graphics; +using Microsoft.Xna.Framework.Input; +using MyMonoGame.GUI; +using System; +using System.IO; +using System.Reflection; +using System.Threading; + +namespace Galactic_Colors_Control_GUI +{ + /// + /// This is the main type for your game. + /// + public class Game : Microsoft.Xna.Framework.Game + { + public static Game singleton; + + private GraphicsDeviceManager graphics; + private SpriteBatch spriteBatch; + private ContentManager content; + + private SoundEffect[] effects = new SoundEffect[4]; //click, hover, explosion,... + + public Fonts fonts; + + internal static Texture2D nullSprite; + + private Texture2D[] pointerSprites = new Texture2D[1]; + public boxSprites[] buttonsSprites = new boxSprites[1]; + public Background background; + + public Client client; //Client Core + public Manager GUI = new Manager(); //MyMonogameGUI + + private string skinName; + private bool isFullScreen = false; + + public States.State gameState = new States.TitleState(new States.MainMenuState(), new TimeSpan(0,0,5)); + + private int _ScreenWidth = 1280; + private int _ScreenHeight = 720; + + public int ScreenWidth { get { return _ScreenWidth; } private set { _ScreenWidth = value; } } + public int ScreenHeight { get { return _ScreenHeight; } private set { _ScreenHeight = value; } } + + public Game() + { + singleton = this; + if (isFullScreen) //Fullscreen resolution + { + ScreenWidth = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width; + ScreenHeight = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height; + } + graphics = new GraphicsDeviceManager(this); + graphics.PreferredBackBufferWidth = ScreenWidth; + graphics.PreferredBackBufferHeight = ScreenHeight; + graphics.IsFullScreen = isFullScreen; + graphics.ApplyChanges(); + Content.RootDirectory = "Content"; + content = Content; + } + + /// + /// Allows the game to perform any initialization it needs to before starting to run. + /// This is where it can query for any required services and load any non-graphic + /// related content. Calling base.Initialize will enumerate through any components + /// and initialize them as well. + /// + protected override void Initialize() + { + nullSprite = new Texture2D(GraphicsDevice, 1, 1); + nullSprite.SetData(new Color[1 * 1] { Color.White }); + + GUI.Initialise(); + base.Initialize(); + } + + /// + /// LoadContent will be called once per game and is the place to load + /// all of your content. + /// + protected override void LoadContent() + { + // Create a new SpriteBatch, which can be used to draw textures. + spriteBatch = new SpriteBatch(GraphicsDevice); + + //Need OpenAL Update for Windows 10 at least + effects[0] = content.Load("Sounds/alert"); + effects[1] = content.Load("Sounds/bip"); + effects[2] = content.Load("Sounds/change"); + effects[3] = content.Load("Sounds/valid"); + + fonts.small = content.Load("Fonts/small"); + fonts.basic = content.Load("Fonts/basic"); + fonts.title = content.Load("Fonts/title"); + + for (int i = 0; i < pointerSprites.Length; i++) + { + pointerSprites[i] = content.Load("Textures/Hub/pointer" + i); + } + + Texture2D[] backSprites = new Texture2D[2]; + backSprites[0] = content.Load("Textures/background0"); + backSprites[1] = content.Load("Textures/background1"); + + States.MainMenuState.logoSprite = content.Load("Textures/LogoSmall"); + + for (int i = 0; i < buttonsSprites.Length; i++) + { + buttonsSprites[i].topLeft = content.Load("Textures/Hub/Buttons/" + i + "/topLeft"); + buttonsSprites[i].topCenter = content.Load("Textures/Hub/Buttons/" + i + "/topCenter"); + buttonsSprites[i].topRight = content.Load("Textures/Hub/Buttons/" + i + "/topRight"); + buttonsSprites[i].centerLeft = content.Load("Textures/Hub/Buttons/" + i + "/centerLeft"); + buttonsSprites[i].centerCenter = content.Load("Textures/Hub/Buttons/" + i + "/centerCenter"); + buttonsSprites[i].centerRight = content.Load("Textures/Hub/Buttons/" + i + "/centerRight"); + buttonsSprites[i].bottomLeft = content.Load("Textures/Hub/Buttons/" + i + "/bottomLeft"); + buttonsSprites[i].bottomCenter = content.Load("Textures/Hub/Buttons/" + i + "/bottomCenter"); + buttonsSprites[i].bottomRight = content.Load("Textures/Hub/Buttons/" + i + "/bottomRight"); + } + + //Load from files + if (Directory.Exists("Skin/" + skinName)) + { + if (Directory.Exists("Skin/" + skinName + "/Sounds")) + { + Utilities.SoundFromMp3("Skin/" + skinName + "/Sounds/alert.mp3", ref effects[0]); + Utilities.SoundFromMp3("Skin/" + skinName + "/Sounds/bip.mp3", ref effects[1]); + Utilities.SoundFromMp3("Skin/" + skinName + "/Sounds/change.mp3", ref effects[2]); + Utilities.SoundFromMp3("Skin/" + skinName + "/Sounds/valid.mp3", ref effects[3]); + } + + if (Directory.Exists("Skin/" + skinName + "/Textures")) + { + Utilities.SpriteFromPng("Skin/" + skinName + "Textures/background0.png", ref backSprites[0], GraphicsDevice); + Utilities.SpriteFromPng("Skin/" + skinName + "Textures/background1.png", ref backSprites[1], GraphicsDevice); + if (Directory.Exists("Skin/" + skinName + "/Textures/Hub/")) + { + if (Directory.Exists("Skin/" + skinName + "/Textures/Hub/Buttons")) + { + for (int i = 0; i < buttonsSprites.Length; i++) + { + Utilities.SpriteFromPng("Skin/" + skinName + "Textures/Hub/Buttons/" + i + "/topLeft.png", ref buttonsSprites[i].topLeft, GraphicsDevice); + Utilities.SpriteFromPng("Skin/" + skinName + "Textures/Hub/Buttons/" + i + "/topCenter.png", ref buttonsSprites[i].topCenter, GraphicsDevice); + Utilities.SpriteFromPng("Skin/" + skinName + "Textures/Hub/Buttons/" + i + "/topRight.png", ref buttonsSprites[i].topRight, GraphicsDevice); + Utilities.SpriteFromPng("Skin/" + skinName + "Textures/Hub/Buttons/" + i + "/centerLeft.png", ref buttonsSprites[i].centerLeft, GraphicsDevice); + Utilities.SpriteFromPng("Skin/" + skinName + "Textures/Hub/Buttons/" + i + "/centerCenter.png", ref buttonsSprites[i].centerCenter, GraphicsDevice); + Utilities.SpriteFromPng("Skin/" + skinName + "Textures/Hub/Buttons/" + i + "/centerRight.png", ref buttonsSprites[i].centerRight, GraphicsDevice); + Utilities.SpriteFromPng("Skin/" + skinName + "Textures/Hub/Buttons/" + i + "/bottomLeft.png", ref buttonsSprites[i].bottomLeft, GraphicsDevice); + Utilities.SpriteFromPng("Skin/" + skinName + "Textures/Hub/Buttons/" + i + "/bottomCenter.png", ref buttonsSprites[i].bottomCenter, GraphicsDevice); + Utilities.SpriteFromPng("Skin/" + skinName + "Textures/Hub/Buttons/" + i + "/bottomRight.png", ref buttonsSprites[i].bottomRight, GraphicsDevice); + } + } + + for (int i = 0; i < pointerSprites.Length; i++) + { + Utilities.SpriteFromPng("Skin/" + skinName + "/Textures/Hub/pointer" + i + ".png", ref pointerSprites[i], GraphicsDevice); + } + } + } + } + + background = new Background(backSprites, new double[2] { 1, 2 }); //Background initialisation + background.speedX = 1; + } + + /// + /// UnloadContent will be called once per game and is the place to unload + /// game-specific content. + /// + protected override void UnloadContent() + { + // Unload any non ContentManager content here + } + + /// + /// Allows the game to run logic such as updating the world, + /// checking for collisions, gathering input, and playing audio. + /// + /// Provides a snapshot of timing values. + protected override void Update(GameTime gameTime) + { + gameState.Update(); + GUI.Update(); + + base.Update(gameTime); + } + + /// + /// This is called when the game should draw itself. + /// + /// Provides a snapshot of timing values. + protected override void Draw(GameTime gameTime) + { + GraphicsDevice.Clear(Color.DarkGray); + + spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied); + + GUI.Draw(spriteBatch); + gameState.Draw(spriteBatch); + + Color ActiveColor = IsActive ? Color.Green : Color.Red; + GUI.Label(new MyMonoGame.Vector(10, ScreenHeight - 20), (1 / (float)gameTime.ElapsedGameTime.TotalSeconds).ToString(), fonts.small, new MyMonoGame.Colors(ActiveColor)); + spriteBatch.Draw(pointerSprites[0], new Rectangle(Mouse.GetState().X - 10, Mouse.GetState().Y - 10, 20, 20), Color.Red); + + spriteBatch.End(); + + base.Draw(gameTime); + } + } +} \ No newline at end of file diff --git a/Galactic Colors Control GUI/Game1.cs b/Galactic Colors Control GUI/Game1.cs deleted file mode 100644 index 57e86c2..0000000 --- a/Galactic Colors Control GUI/Game1.cs +++ /dev/null @@ -1,614 +0,0 @@ -//TODO comment and update for new clientcore -using Galactic_Colors_Control; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Audio; -using Microsoft.Xna.Framework.Content; -using Microsoft.Xna.Framework.Graphics; -using Microsoft.Xna.Framework.Input; -using MyMonoGame.GUI; -using System; -using System.IO; -using System.Reflection; -using System.Threading; - -namespace Galactic_Colors_Control_GUI -{ - /// - /// This is the main type for your game. - /// - public class Game1 : Game - { - private GraphicsDeviceManager graphics; - private SpriteBatch spriteBatch; - private ContentManager content; - - private SoundEffect[] effects = new SoundEffect[4]; - - private SpriteFont smallFont; - private SpriteFont basicFont; - private SpriteFont titleFont; - - internal static Texture2D nullSprite; - private Texture2D logoSprite; - private Texture2D[] backSprites = new Texture2D[2]; - private double[] backgroundX = new double[2]; - private double[] backgroundY = new double[2]; - private double acceleratorX = 1; - - private Texture2D[] pointerSprites = new Texture2D[1]; - private boxSprites[] buttonsSprites = new boxSprites[1]; - - private Client client; - private Manager GUI = new Manager(); - - private string skinName; - private bool isFullScren = false; - - private enum GameStatus - { - Home, Connect, Options, Game, Pause, End, Thanks, - Title, - Indentification, - Kick - } - - private GameStatus gameStatus = GameStatus.Home; - - private int ScreenWidth = 1280; - private int ScreenHeight = 720; - - private string username = null; - - private bool showOKMessage = false; - private string messageTitle; - private string messageText = string.Empty; - private bool showYNMessage = false; - private bool showLoading = false; - private bool showChat = false; - private string chatText = string.Empty; - private string chatInput = string.Empty; - private bool showParty = false; - private bool showOutput = true; - - public Game1() - { - if (isFullScren) - { - ScreenWidth = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width; - ScreenHeight = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height; - } - graphics = new GraphicsDeviceManager(this); - graphics.PreferredBackBufferWidth = ScreenWidth; - graphics.PreferredBackBufferHeight = ScreenHeight; - graphics.IsFullScreen = isFullScren; - graphics.ApplyChanges(); - Content.RootDirectory = "Content"; - content = Content; - } - - /// - /// Allows the game to perform any initialization it needs to before starting to run. - /// This is where it can query for any required services and load any non-graphic - /// related content. Calling base.Initialize will enumerate through any components - /// and initialize them as well. - /// - protected override void Initialize() - { - nullSprite = new Texture2D(GraphicsDevice, 1, 1); - nullSprite.SetData(new Color[1 * 1] { Color.White }); - - GUI.Initialise(); - base.Initialize(); - } - - /// - /// LoadContent will be called once per game and is the place to load - /// all of your content. - /// - protected override void LoadContent() - { - // Create a new SpriteBatch, which can be used to draw textures. - spriteBatch = new SpriteBatch(GraphicsDevice); - - //Need OpenAL Update for Windows 10 at least - effects[0] = content.Load("Sounds/alert"); - effects[1] = content.Load("Sounds/bip"); - effects[2] = content.Load("Sounds/change"); - effects[3] = content.Load("Sounds/valid"); - - smallFont = content.Load("Fonts/small"); - basicFont = content.Load("Fonts/basic"); - titleFont = content.Load("Fonts/title"); - - for (int i = 0; i < pointerSprites.Length; i++) - { - pointerSprites[i] = content.Load("Textures/Hub/pointer" + i); - } - - backSprites[0] = content.Load("Textures/background0"); - backSprites[1] = content.Load("Textures/background1"); - - logoSprite = content.Load("Textures/LogoSmall"); - - for (int i = 0; i < buttonsSprites.Length; i++) - { - buttonsSprites[i].topLeft = content.Load("Textures/Hub/Buttons/" + i + "/topLeft"); - buttonsSprites[i].topCenter = content.Load("Textures/Hub/Buttons/" + i + "/topCenter"); - buttonsSprites[i].topRight = content.Load("Textures/Hub/Buttons/" + i + "/topRight"); - buttonsSprites[i].centerLeft = content.Load("Textures/Hub/Buttons/" + i + "/centerLeft"); - buttonsSprites[i].centerCenter = content.Load("Textures/Hub/Buttons/" + i + "/centerCenter"); - buttonsSprites[i].centerRight = content.Load("Textures/Hub/Buttons/" + i + "/centerRight"); - buttonsSprites[i].bottomLeft = content.Load("Textures/Hub/Buttons/" + i + "/bottomLeft"); - buttonsSprites[i].bottomCenter = content.Load("Textures/Hub/Buttons/" + i + "/bottomCenter"); - buttonsSprites[i].bottomRight = content.Load("Textures/Hub/Buttons/" + i + "/bottomRight"); - } - - if (Directory.Exists("Skin/" + skinName)) - { - if (Directory.Exists("Skin/" + skinName + "/Sounds")) - { - Utilities.SoundFromMp3("Skin/" + skinName + "/Sounds/alert.mp3", ref effects[0]); - Utilities.SoundFromMp3("Skin/" + skinName + "/Sounds/bip.mp3", ref effects[1]); - Utilities.SoundFromMp3("Skin/" + skinName + "/Sounds/change.mp3", ref effects[2]); - Utilities.SoundFromMp3("Skin/" + skinName + "/Sounds/valid.mp3", ref effects[3]); - } - - if (Directory.Exists("Skin/" + skinName + "/Textures")) - { - Utilities.SpriteFromPng("Skin/" + skinName + "Textures/background0.png", ref backSprites[0], GraphicsDevice); - Utilities.SpriteFromPng("Skin/" + skinName + "Textures/background1.png", ref backSprites[1], GraphicsDevice); - if (Directory.Exists("Skin/" + skinName + "/Textures/Hub/")) - { - if (Directory.Exists("Skin/" + skinName + "/Textures/Hub/Buttons")) - { - for (int i = 0; i < buttonsSprites.Length; i++) - { - Utilities.SpriteFromPng("Skin/" + skinName + "Textures/Hub/Buttons/" + i + "/topLeft.png", ref buttonsSprites[i].topLeft, GraphicsDevice); - Utilities.SpriteFromPng("Skin/" + skinName + "Textures/Hub/Buttons/" + i + "/topCenter.png", ref buttonsSprites[i].topCenter, GraphicsDevice); - Utilities.SpriteFromPng("Skin/" + skinName + "Textures/Hub/Buttons/" + i + "/topRight.png", ref buttonsSprites[i].topRight, GraphicsDevice); - Utilities.SpriteFromPng("Skin/" + skinName + "Textures/Hub/Buttons/" + i + "/centerLeft.png", ref buttonsSprites[i].centerLeft, GraphicsDevice); - Utilities.SpriteFromPng("Skin/" + skinName + "Textures/Hub/Buttons/" + i + "/centerCenter.png", ref buttonsSprites[i].centerCenter, GraphicsDevice); - Utilities.SpriteFromPng("Skin/" + skinName + "Textures/Hub/Buttons/" + i + "/centerRight.png", ref buttonsSprites[i].centerRight, GraphicsDevice); - Utilities.SpriteFromPng("Skin/" + skinName + "Textures/Hub/Buttons/" + i + "/bottomLeft.png", ref buttonsSprites[i].bottomLeft, GraphicsDevice); - Utilities.SpriteFromPng("Skin/" + skinName + "Textures/Hub/Buttons/" + i + "/bottomCenter.png", ref buttonsSprites[i].bottomCenter, GraphicsDevice); - Utilities.SpriteFromPng("Skin/" + skinName + "Textures/Hub/Buttons/" + i + "/bottomRight.png", ref buttonsSprites[i].bottomRight, GraphicsDevice); - } - } - - for (int i = 0; i < pointerSprites.Length; i++) - { - Utilities.SpriteFromPng("Skin/" + skinName + "/Textures/Hub/pointer" + i + ".png", ref pointerSprites[i], GraphicsDevice); - } - } - } - } - } - - /// - /// UnloadContent will be called once per game and is the place to unload - /// game-specific content. - /// - protected override void UnloadContent() - { - // Unload any non ContentManager content here - } - - /// - /// Allows the game to run logic such as updating the world, - /// checking for collisions, gathering input, and playing audio. - /// - /// Provides a snapshot of timing values. - protected override void Update(GameTime gameTime) - { - switch (gameStatus) - { - case GameStatus.Home: - case GameStatus.Title: - case GameStatus.Connect: - case GameStatus.Indentification: - backgroundX[0] -= 1 * acceleratorX; - backgroundX[1] -= 2 * acceleratorX; - break; - - case GameStatus.Game: - if (showOutput) - //TODO - /*if (client.Output.Count > 0) - { - string text = client.Output[0]; - switch (text) - { - case "/clear": - chatText = string.Empty; - break; - - default: - ChatAdd(text); - break; - } - client.Output.Remove(text); - }*/ - if (!client.isRunning) { gameStatus = GameStatus.Kick; } - break; - } - - GUI.Update(); - - base.Update(gameTime); - } - - /// - /// This is called when the game should draw itself. - /// - /// Provides a snapshot of timing values. - protected override void Draw(GameTime gameTime) - { - GraphicsDevice.Clear(Color.DarkGray); - - spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied); - - GUI.Draw(spriteBatch); - - switch (gameStatus) - { - case GameStatus.Title: - DrawBackground(0); - DrawBackground(1); - GUI.Label(new MyMonoGame.Vector(ScreenWidth / 2, ScreenHeight / 2), "Galactic Colors Control", titleFont, new MyMonoGame.Colors(Color.White), Manager.textAlign.centerCenter); - break; - - case GameStatus.Home: - DrawBackground(0); - DrawBackground(1); - GUI.Label(new MyMonoGame.Vector(ScreenWidth / 2, ScreenHeight / 4), "Galactic Colors Control", titleFont, new MyMonoGame.Colors(Color.White), Manager.textAlign.centerCenter); - GUI.Label(new MyMonoGame.Vector(ScreenWidth / 2, ScreenHeight / 4 + 40), "GUI " + Assembly.GetEntryAssembly().GetName().Version.ToString(), basicFont, new MyMonoGame.Colors(Color.White), Manager.textAlign.centerCenter); - if (GUI.Button(new Rectangle(ScreenWidth - 64, ScreenHeight - 74, 64, 64), logoSprite)) { System.Diagnostics.Process.Start("https://sheychen.shost.ca/"); } - if (GUI.Button(new Rectangle(ScreenWidth / 2 - 75, ScreenHeight / 2 - 30, 150, 40), buttonsSprites[0], "Play", basicFont, new MyMonoGame.Colors(Color.White, Color.Green))) - { - GUI.ResetFocus(); - client = new Client(); - new Thread(() => - { - while (acceleratorX < 5) - { - Thread.Sleep(20); - acceleratorX += 0.1d; - } - gameStatus = GameStatus.Connect; - }).Start(); - } - //if (GUI.Button(new Rectangle(ScreenWidth / 2 - 75, ScreenHeight / 2 + 20, 150, 40), buttonsSprites[0], "Options", basicFont, new MyMonoGame.Colors(Color.White, Color.Blue))) { - // GUI.ResetFocus(); - // gameStatus = GameStatus.Options; - //} - if (GUI.Button(new Rectangle(ScreenWidth / 2 - 75, ScreenHeight / 2 + 70, 150, 40), buttonsSprites[0], "Exit", basicFont, new MyMonoGame.Colors(Color.White, Color.Red))) - { - GUI.ResetFocus(); - gameStatus = GameStatus.Title; - new Thread(() => - { - while (acceleratorX > 0) - { - Thread.Sleep(10); - acceleratorX -= 0.01d; - } - Exit(); - }).Start(); - } - break; - - case GameStatus.Connect: - DrawBackground(0); - DrawBackground(1); - GUI.Label(new MyMonoGame.Vector(ScreenWidth / 2, ScreenHeight / 4), "Galactic Colors Control", titleFont, new MyMonoGame.Colors(Color.White), Manager.textAlign.centerCenter); - if (showLoading) - { - GUI.Box(new Rectangle(ScreenWidth / 2 - 150, ScreenHeight / 4 + 50, 300, 50), buttonsSprites[0]); - GUI.Label(new Rectangle(ScreenWidth / 2 - 150, ScreenHeight / 4 + 50, 300, 50), "Loading", basicFont); - } - else - { - if (showOKMessage) - { - GUI.Box(new Rectangle(ScreenWidth / 2 - 150, ScreenHeight / 4 + 50, 300, 150), buttonsSprites[0]); - GUI.Label(new MyMonoGame.Vector(ScreenWidth / 2, ScreenHeight / 4 + 60), messageTitle, basicFont, null, Manager.textAlign.bottomCenter); - GUI.Label(new MyMonoGame.Vector(ScreenWidth / 2, ScreenHeight / 4 + 100), messageText, smallFont, null, Manager.textAlign.bottomCenter); - if (GUI.Button(new Rectangle(ScreenWidth / 2 - 140, ScreenHeight / 4 + 150, 280, 40), buttonsSprites[0], "Ok", basicFont)) { GUI.ResetFocus(); showOKMessage = false; } - } - else - { - if (showYNMessage) - { - GUI.Box(new Rectangle(ScreenWidth / 2 - 150, ScreenHeight / 4 + 50, 300, 100), buttonsSprites[0]); - GUI.Label(new MyMonoGame.Vector(ScreenWidth / 2, ScreenHeight / 4 + 60), messageTitle, basicFont, null, Manager.textAlign.bottomCenter); - if (GUI.Button(new Rectangle(ScreenWidth / 2 - 140, ScreenHeight / 4 + 100, 135, 40), buttonsSprites[0], "Yes", basicFont)) - { - GUI.ResetFocus(); - new Thread(ConnectHost).Start(); - showYNMessage = false; - } - if (GUI.Button(new Rectangle(ScreenWidth / 2 + 5, ScreenHeight / 4 + 100, 135, 40), buttonsSprites[0], "No", basicFont)) - { - //TODO client.Output.Clear(); - client.ResetHost(); - GUI.ResetFocus(); - showYNMessage = false; - } - } - else - { - if (GUI.TextField(new Rectangle(ScreenWidth / 2 - 75, ScreenHeight / 2 - 30, 150, 40), ref username, basicFont, new MyMonoGame.Colors(Color.LightGray, Color.White), Manager.textAlign.centerCenter, "Server address")) { new Thread(ValidateHost).Start(); } - if (GUI.Button(new Rectangle(ScreenWidth / 2 - 75, ScreenHeight / 2 + 20, 150, 40), buttonsSprites[0], "Connect", basicFont, new MyMonoGame.Colors(Color.LightGray, Color.White))) { new Thread(ValidateHost).Start(); } - if (GUI.Button(new Rectangle(ScreenWidth / 2 - 75, ScreenHeight / 2 + 70, 150, 40), buttonsSprites[0], "Back", basicFont, new MyMonoGame.Colors(Color.LightGray, Color.White))) - { - GUI.ResetFocus(); - new Thread(() => - { - while (acceleratorX > 1) - { - Thread.Sleep(20); - acceleratorX -= 0.1d; - } - gameStatus = GameStatus.Home; - username = null; - }).Start(); - } - } - } - } - break; - - case GameStatus.Indentification: - DrawBackground(0); - DrawBackground(1); - GUI.Label(new MyMonoGame.Vector(ScreenWidth / 2, ScreenHeight / 4), "Galactic Colors Control", titleFont, new MyMonoGame.Colors(Color.White), Manager.textAlign.centerCenter); - if (showLoading) - { - GUI.Box(new Rectangle(ScreenWidth / 2 - 150, ScreenHeight / 4 + 50, 300, 50), buttonsSprites[0]); - GUI.Label(new Rectangle(ScreenWidth / 2 - 150, ScreenHeight / 4 + 50, 300, 50), "Loading", basicFont); - } - else - { - if (showOKMessage) - { - GUI.Box(new Rectangle(ScreenWidth / 2 - 150, ScreenHeight / 4 + 50, 300, 150), buttonsSprites[0]); - GUI.Label(new MyMonoGame.Vector(ScreenWidth / 2, ScreenHeight / 4 + 60), messageTitle, basicFont, null, Manager.textAlign.bottomCenter); - GUI.Label(new MyMonoGame.Vector(ScreenWidth / 2, ScreenHeight / 4 + 100), messageText, smallFont, null, Manager.textAlign.bottomCenter); - if (GUI.Button(new Rectangle(ScreenWidth / 2 - 140, ScreenHeight / 4 + 150, 280, 40), buttonsSprites[0], "Ok", basicFont)) { GUI.ResetFocus(); showOKMessage = false; } - } - else - { - if (GUI.TextField(new Rectangle(ScreenWidth / 2 - 75, ScreenHeight / 2 - 30, 150, 40), ref username, basicFont, new MyMonoGame.Colors(Color.LightGray, Color.White), Manager.textAlign.centerCenter, "Username")) { new Thread(IdentifiacateHost).Start(); } - if (GUI.Button(new Rectangle(ScreenWidth / 2 - 75, ScreenHeight / 2 + 20, 150, 40), buttonsSprites[0], "Validate", basicFont, new MyMonoGame.Colors(Color.LightGray, Color.White))) { new Thread(IdentifiacateHost).Start(); } - if (GUI.Button(new Rectangle(ScreenWidth / 2 - 75, ScreenHeight / 2 + 70, 150, 40), buttonsSprites[0], "Back", basicFont, new MyMonoGame.Colors(Color.LightGray, Color.White))) - { - GUI.ResetFocus(); - new Thread(() => - { - while (acceleratorX > 1) - { - Thread.Sleep(20); - acceleratorX -= 0.1d; - } - gameStatus = GameStatus.Home; - username = null; - }).Start(); - } - } - } - break; - - case GameStatus.Game: - DrawBackground(0); - DrawBackground(1); - GUI.Texture(new Rectangle(0, 0, ScreenWidth, 30), nullSprite, new MyMonoGame.Colors(new Color(0.1f, 0.1f, 0.1f))); - if (GUI.Button(new Rectangle(5, 5, 50, 20), (showChat ? "Hide" : "Show") + " chat", smallFont, new MyMonoGame.Colors(Color.White, Color.LightGray, Color.Gray))) { GUI.ResetFocus(); showChat = !showChat; } - if (GUI.Button(new Rectangle(65, 5, 50, 20), (showParty ? "Leave" : "Join") + " party", smallFont, new MyMonoGame.Colors(Color.White, Color.LightGray, Color.Gray))) { new Thread(PartyClick).Start(); } - - if (showChat) - { - GUI.Box(new Rectangle(0, 30, 310, 310), buttonsSprites[0]); - //TODO if (GUI.TextField(new Rectangle(5, 35, 305, 20), ref chatInput, basicFont, null, Manager.textAlign.centerLeft, "Enter message")) { if (chatInput != null) { ChatAdd(chatInput); client.SendRequest(chatInput); chatInput = null; } } - GUI.Label(new Rectangle(5, 60, 305, 245), chatText, smallFont, null, Manager.textAlign.topLeft, true); - } - - if (showLoading) - { - GUI.Box(new Rectangle(ScreenWidth / 2 - 150, ScreenHeight / 4 + 50, 300, 50), buttonsSprites[0]); - GUI.Label(new Rectangle(ScreenWidth / 2 - 150, ScreenHeight / 4 + 50, 300, 50), "Loading", basicFont); - } - else - { - if (showOKMessage) - { - GUI.Box(new Rectangle(ScreenWidth / 2 - 150, ScreenHeight / 4 + 50, 300, 150), buttonsSprites[0]); - GUI.Label(new MyMonoGame.Vector(ScreenWidth / 2, ScreenHeight / 4 + 60), messageTitle, basicFont, null, Manager.textAlign.bottomCenter); - GUI.Label(new MyMonoGame.Vector(ScreenWidth / 2, ScreenHeight / 4 + 100), messageText, smallFont, null, Manager.textAlign.bottomCenter); - if (GUI.Button(new Rectangle(ScreenWidth / 2 - 140, ScreenHeight / 4 + 150, 280, 40), buttonsSprites[0], "Ok", basicFont)) { GUI.ResetFocus(); showOKMessage = false; } - } - } - break; - } - - Color ActiveColor = IsActive ? Color.Green : Color.Red; - GUI.Label(new MyMonoGame.Vector(10, ScreenHeight - 20), (1 / (float)gameTime.ElapsedGameTime.TotalSeconds).ToString(), smallFont, new MyMonoGame.Colors(ActiveColor)); - spriteBatch.Draw(pointerSprites[0], new Rectangle(Mouse.GetState().X - 10, Mouse.GetState().Y - 10, 20, 20), Color.Red); - - spriteBatch.End(); - - base.Draw(gameTime); - } - - private void ValidateHost() - { - showLoading = true; - if (username == null) { username = ""; } - string Host = client.ValidateHost(username); - if (Host == null) - { - messageTitle = "Error"; - messageText = string.Empty; - //TODO foreach (string line in client.Output.ToArray()) { messageText += (line + Environment.NewLine); } - showOKMessage = true; - //TODO client.Output.Clear(); - client.ResetHost(); ; - } - else - { - messageTitle = "Use " + Host + "?"; - showYNMessage = true; - } - showLoading = false; - } - - private void ConnectHost() - { - showLoading = true; - if (client.ConnectHost()) - { - gameStatus = GameStatus.Indentification; - } - else - { - messageTitle = "Error"; - messageText = string.Empty; - //TODO foreach (string line in client.Output.ToArray()) { messageText += (line + Environment.NewLine); } - showOKMessage = true; - //TODO client.Output.Clear(); - client.ResetHost(); - } - showLoading = false; - } - - private void IdentifiacateHost() - { - showLoading = true; - if (username != null) - { - if (username.Length > 3) - { - //TODO client.Output.Clear(); - //TODO client.SendRequest("/connect " + username); - /*int wait = 0; - while (wait < 20) - { - if (client.Output.Count > 0) - { - wait = 20; - } - else - { - wait++; - Thread.Sleep(200); - } - } - if (client.Output.Count > 0) - { - if (client.Output.Contains("Identifiaction succes")) - { - gameStatus = GameStatus.Game; - } - else - { - messageTitle = "Error"; - messageText = string.Empty; - foreach (string line in client.Output.ToArray()) { messageText += (line + Environment.NewLine); } - showOKMessage = true; - showLoading = false; - client.Output.Clear(); - } - } - else - { - messageTitle = "Timeout"; - messageText = ""; - showOKMessage = true; - showLoading = false; - client.Output.Clear(); - }*/ - } - } - showLoading = false; - } - - private void PartyClick() - { - showLoading = true; - GUI.ResetFocus(); - //TODO - /* - if (showParty) - { - client.SendRequest("/party leave"); - showParty = false; - showLoading = false; - } - else - { - client.Output.Clear(); - client.SendRequest("/party list"); - int wait = 0; - while (wait < 20) - { - if (client.Output.Count > 0) - { - wait = 20; - } - else - { - wait++; - Thread.Sleep(200); - } - } - if (client.Output.Count > 0) - { - Thread.Sleep(500); - if (client.Output.Count > 1) - { - messageTitle = "Party"; - messageText = string.Empty; - foreach (string line in client.Output.ToArray()) { messageText += (line + Environment.NewLine); } - showOKMessage = true; - client.Output.Clear(); - } - else - { - messageTitle = "Any party"; - messageText = string.Empty; - foreach (string line in client.Output.ToArray()) { messageText += (line + Environment.NewLine); } - showOKMessage = true; - client.Output.Clear(); - } - } - else - { - messageTitle = "Timeout"; - messageText = ""; - showOKMessage = true; - showLoading = false; - client.Output.Clear(); - } - }*/ - } - - private void ChatAdd(string text) - { - chatText += ((chatText != string.Empty ? Environment.NewLine : "") + text); - } - - private void DrawBackground(int index) - { - if (backgroundX[index] > backSprites[index].Width) { backgroundX[index] = 0; } - if (backgroundY[index] > backSprites[index].Height) { backgroundY[index] = 0; } - if (backgroundX[index] < 0) { backgroundX[index] = backSprites[index].Width; } - if (backgroundY[index] < 0) { backgroundY[index] = backSprites[index].Height; } - for (int X = -1; X < ScreenWidth / backSprites[index].Width + 1; X++) - { - for (int Y = -1; Y < ScreenHeight / backSprites[index].Height + 1; Y++) - { - GUI.Texture(new Rectangle(X * backSprites[index].Width + (int)backgroundX[index], Y * backSprites[index].Height + (int)backgroundY[index], backSprites[index].Width, backSprites[index].Height), backSprites[index], new MyMonoGame.Colors(Color.White)); - } - } - } - } -} \ No newline at end of file diff --git a/Galactic Colors Control GUI/Program.cs b/Galactic Colors Control GUI/Program.cs index 2a68843..6078cfc 100644 --- a/Galactic Colors Control GUI/Program.cs +++ b/Galactic Colors Control GUI/Program.cs @@ -13,7 +13,8 @@ namespace Galactic_Colors_Control_GUI [STAThread] private static void Main() { - using (var game = new Game1()) + //TODO add debug and more + using (var game = new Game()) game.Run(); } } diff --git a/Galactic Colors Control GUI/States/ConnectState.cs b/Galactic Colors Control GUI/States/ConnectState.cs new file mode 100644 index 0000000..06f5478 --- /dev/null +++ b/Galactic Colors Control GUI/States/ConnectState.cs @@ -0,0 +1,150 @@ +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using MyMonoGame.GUI; +using System.Threading; +using System; + +namespace Galactic_Colors_Control_GUI.States +{ + public struct Message + { + public string title; + public string text; + public Message(string Title, string Text = "") + { + title = Title; + text = Text; + } + } + + public class ConnectState : State + { + private bool locked = false; + private bool showLoading = false; + private bool showOKMessage = false; + private bool showYNMessage = false; + + private Message message; + private string adress; + + public override void Draw(SpriteBatch spritebatch) + { + Game.singleton.background.Draw(spritebatch); + Game.singleton.GUI.Label(new MyMonoGame.Vector(Game.singleton.ScreenWidth / 2, Game.singleton.ScreenHeight / 4), "Galactic Colors Control", Game.singleton.fonts.title, new MyMonoGame.Colors(Color.White), Manager.textAlign.centerCenter); + if (showLoading) + { + Game.singleton.GUI.Box(new Rectangle(Game.singleton.ScreenWidth / 2 - 150, Game.singleton.ScreenHeight / 4 + 50, 300, 50), Game.singleton.buttonsSprites[0]); + Game.singleton.GUI.Label(new Rectangle(Game.singleton.ScreenWidth / 2 - 150, Game.singleton.ScreenHeight / 4 + 50, 300, 50), "Loading", Game.singleton.fonts.basic); + } + else + { + if (showOKMessage) + { + Game.singleton.GUI.Box(new Rectangle(Game.singleton.ScreenWidth / 2 - 150, Game.singleton.ScreenHeight / 4 + 50, 300, 150), Game.singleton.buttonsSprites[0]); + Game.singleton.GUI.Label(new MyMonoGame.Vector(Game.singleton.ScreenWidth / 2, Game.singleton.ScreenHeight / 4 + 60), message.title, Game.singleton.fonts.basic , null, Manager.textAlign.bottomCenter); + Game.singleton.GUI.Label(new MyMonoGame.Vector(Game.singleton.ScreenWidth / 2, Game.singleton.ScreenHeight / 4 + 100), message.text, Game.singleton.fonts.small, null, Manager.textAlign.bottomCenter); + if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 - 140, Game.singleton.ScreenHeight / 4 + 150, 280, 40), Game.singleton.buttonsSprites[0], "Ok", Game.singleton.fonts.basic)) { locked = false; Game.singleton.GUI.ResetFocus(); showOKMessage = false; } + } + else + { + if (showYNMessage) + { + Game.singleton.GUI.Box(new Rectangle(Game.singleton.ScreenWidth / 2 - 150, Game.singleton.ScreenHeight / 4 + 50, 300, 100), Game.singleton.buttonsSprites[0]); + Game.singleton.GUI.Label(new MyMonoGame.Vector(Game.singleton.ScreenWidth / 2, Game.singleton.ScreenHeight / 4 + 60), message.title, Game.singleton.fonts.basic, null, Manager.textAlign.bottomCenter); + if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 - 140, Game.singleton.ScreenHeight / 4 + 100, 135, 40), Game.singleton.buttonsSprites[0], "Yes", Game.singleton.fonts.basic)) + { + if (!locked) + { + locked = true; + showYNMessage = false; + Game.singleton.GUI.ResetFocus(); + new Thread(ConnectHost).Start(); + } + } + if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 + 5, Game.singleton.ScreenHeight / 4 + 100, 135, 40), Game.singleton.buttonsSprites[0], "No", Game.singleton.fonts.basic)) + { + showYNMessage = false; + Game.singleton.client.ResetHost(); + Game.singleton.GUI.ResetFocus(); + } + } + else + { + if (Game.singleton.GUI.TextField(new Rectangle(Game.singleton.ScreenWidth / 2 - 75, Game.singleton.ScreenHeight / 2 - 30, 150, 40), ref adress, Game.singleton.fonts.basic, new MyMonoGame.Colors(Color.LightGray, Color.White), Manager.textAlign.centerCenter, "Server address")) { + if (!locked) + { + locked = true; + new Thread(ValidateHost).Start(); + } + } + if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 - 75, Game.singleton.ScreenHeight / 2 + 20, 150, 40), Game.singleton.buttonsSprites[0], "Connect", Game.singleton.fonts.basic, new MyMonoGame.Colors(Color.LightGray, Color.White))) + { + if (!locked) + { + locked = true; + new Thread(ValidateHost).Start(); + } + } + if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 - 75, Game.singleton.ScreenHeight / 2 + 70, 150, 40), Game.singleton.buttonsSprites[0], "Back", Game.singleton.fonts.basic, new MyMonoGame.Colors(Color.LightGray, Color.White))) + { + if (!locked) + { + locked = true; + Game.singleton.GUI.ResetFocus(); + new Thread(() => + { + while (!Utilities.DoubleTo(ref Game.singleton.background.speedX, 1, 0.1)) { Thread.Sleep(20); } + Game.singleton.gameState = new MainMenuState(); + }).Start(); + } + } + } + } + } + } + + public override void Update() + { + Game.singleton.background.Update(); + } + + private void ValidateHost() + { + showLoading = true; + if (adress == null) { adress = ""; } + string Host = Game.singleton.client.ValidateHost(adress); + if (Host[0] == '*') + { + Host = Host.Substring(1); + message.title = "Error"; + message.text = Host; + showOKMessage = true; + Game.singleton.client.ResetHost(); ; + } + else + { + message.title = "Use " + Host + "?"; + showYNMessage = true; + } + showLoading = false; + locked = false; + } + + private void ConnectHost() + { + showLoading = true; + if (Game.singleton.client.ConnectHost()) + { + Game.singleton.gameState = new IndentificationState(); + } + else + { + message.title = "Error"; + message.text = string.Empty; + showOKMessage = true; + Game.singleton.client.ResetHost(); + } + showLoading = false; + } + } +} \ No newline at end of file diff --git a/Galactic Colors Control GUI/States/GameState.cs b/Galactic Colors Control GUI/States/GameState.cs new file mode 100644 index 0000000..e0aab0c --- /dev/null +++ b/Galactic Colors Control GUI/States/GameState.cs @@ -0,0 +1,169 @@ +//TODO add party support +using Galactic_Colors_Control_Common; +using Galactic_Colors_Control_Common.Protocol; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using MyMonoGame.GUI; +using System.Threading; +using System; +using Microsoft.Xna.Framework.Input; + +namespace Galactic_Colors_Control_GUI.States +{ + public class GameState : State + { + private string username; + private bool showChat = false; + private string chatText; + private string chatInput; + + private bool showLoading = false; + private bool showOKMessage = false; + private Message message; + + public GameState(string Username) + { + Game.singleton.client.OnEvent += new EventHandler(OnEvent); //Set OnEvent function + username = Username; + } + + public override void Draw(SpriteBatch spritebatch) + { + Game.singleton.background.Draw(spritebatch); + Game.singleton.GUI.Texture(new Rectangle(0, 0, Game.singleton.ScreenWidth, 30), Game.nullSprite, new MyMonoGame.Colors(new Color(0.1f, 0.1f, 0.1f))); + if (Game.singleton.GUI.Button(new Rectangle(5, 5, 50, 20), (showChat ? "Hide" : "Show") + " chat", Game.singleton.fonts.small, new MyMonoGame.Colors(Color.White, Color.LightGray, Color.Gray))) { Game.singleton.GUI.ResetFocus(); showChat = !showChat; } + //if (Game.singleton.GUI.Button(new Rectangle(65, 5, 50, 20), (showParty ? "Leave" : "Join") + " party", smallFont, new MyMonoGame.Colors(Color.White, Color.LightGray, Color.Gray))) { new Thread(PartyClick).Start(); } + + if (showChat) + { + Game.singleton.GUI.Box(new Rectangle(0, 30, 310, 310), Game.singleton.buttonsSprites[0]); + if (Game.singleton.GUI.TextField(new Rectangle(5, 35, 305, 20), ref chatInput, Game.singleton.fonts.basic, null, Manager.textAlign.centerLeft, "Enter message")) { if (chatInput != null) { new Thread(ChatEnter).Start(); } } + Game.singleton.GUI.Label(new Rectangle(5, 60, 305, 245), chatText, Game.singleton.fonts.small, null, Manager.textAlign.topLeft, true); + } + + if (showLoading) + { + Game.singleton.GUI.Box(new Rectangle(Game.singleton.ScreenWidth / 2 - 150, Game.singleton.ScreenHeight / 4 + 50, 300, 50), Game.singleton.buttonsSprites[0]); + Game.singleton.GUI.Label(new Rectangle(Game.singleton.ScreenWidth / 2 - 150, Game.singleton.ScreenHeight / 4 + 50, 300, 50), "Loading", Game.singleton.fonts.basic); + } + else + { + if (showOKMessage) + { + Game.singleton.GUI.Box(new Rectangle(Game.singleton.ScreenWidth / 2 - 150, Game.singleton.ScreenHeight / 4 + 50, 300, 150), Game.singleton.buttonsSprites[0]); + Game.singleton.GUI.Label(new MyMonoGame.Vector(Game.singleton.ScreenWidth / 2, Game.singleton.ScreenHeight / 4 + 60), message.title, Game.singleton.fonts.basic, null, Manager.textAlign.bottomCenter); + Game.singleton.GUI.Label(new MyMonoGame.Vector(Game.singleton.ScreenWidth / 2, Game.singleton.ScreenHeight / 4 + 100), message.text, Game.singleton.fonts.small, null, Manager.textAlign.bottomCenter); + if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 - 140, Game.singleton.ScreenHeight / 4 + 150, 280, 40), Game.singleton.buttonsSprites[0], "Ok", Game.singleton.fonts.basic)) { Game.singleton.GUI.ResetFocus(); showOKMessage = false; Game.singleton.client.ExitHost(); Game.singleton.gameState = new MainMenuState(); } + } + } + } + + public override void Update() + { + if (Keyboard.GetState().IsKeyDown(Keys.Escape)) { Game.singleton.GUI.ResetFocus(); Game.singleton.client.ExitHost(); Game.singleton.gameState = new MainMenuState(); } + } + + private void ChatEnter() + { + string request = chatInput; + chatInput = null; + ResultData res = Game.singleton.client.Request(new string[2] { "say", request }); + if(res.type != ResultTypes.OK) + { + //TODO Mutlilang + ChatText("Error :" + Common.ArrayToString(res.result)); + } + } + + private void OnEvent(object sender, EventArgs e) + { + EventData eve = ((EventDataArgs)e).Data; + switch (eve.type) + { + case EventTypes.ChatMessage: + ChatText(Common.ArrayToString(eve.data)); + break; + + case EventTypes.ServerJoin: + ChatText(Common.ArrayToString(eve.data) + "join the server"); + break; + + case EventTypes.ServerLeave: + ChatText(Common.ArrayToString(eve.data) + "leave the server"); + break; + + case EventTypes.ServerKick: + message.title = "Kick from server"; + message.text = Common.ArrayToString(eve.data); + showOKMessage = true; + break; + } + } + + public void ChatText(string text) + { + chatText += (text + Environment.NewLine); + } + + /* + private void PartyClick() + { + showLoading = true; + GUI.ResetFocus(); + //TODO + /* + if (showParty) + { + client.SendRequest("/party leave"); + showParty = false; + showLoading = false; + } + else + { + client.Output.Clear(); + client.SendRequest("/party list"); + int wait = 0; + while (wait < 20) + { + if (client.Output.Count > 0) + { + wait = 20; + } + else + { + wait++; + Thread.Sleep(200); + } + } + if (client.Output.Count > 0) + { + Thread.Sleep(500); + if (client.Output.Count > 1) + { + messageTitle = "Party"; + messageText = string.Empty; + foreach (string line in client.Output.ToArray()) { messageText += (line + Environment.NewLine); } + showOKMessage = true; + client.Output.Clear(); + } + else + { + messageTitle = "Any party"; + messageText = string.Empty; + foreach (string line in client.Output.ToArray()) { messageText += (line + Environment.NewLine); } + showOKMessage = true; + client.Output.Clear(); + } + } + else + { + messageTitle = "Timeout"; + messageText = ""; + showOKMessage = true; + showLoading = false; + client.Output.Clear(); + } + } + }*/ + } +} \ No newline at end of file diff --git a/Galactic Colors Control GUI/States/IndentificationState.cs b/Galactic Colors Control GUI/States/IndentificationState.cs new file mode 100644 index 0000000..324b80c --- /dev/null +++ b/Galactic Colors Control GUI/States/IndentificationState.cs @@ -0,0 +1,101 @@ +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using MyMonoGame.GUI; +using System.Threading; +using System; +using Galactic_Colors_Control_Common.Protocol; +using Galactic_Colors_Control_Common; + +namespace Galactic_Colors_Control_GUI.States +{ + public class IndentificationState : State + { + private string username; + private Message message; + + private bool locked = false; + private bool showLoading = false; + private bool showOKMessage = false; + + public override void Draw(SpriteBatch spritebatch) + { + Game.singleton.background.Draw(spritebatch); + Game.singleton.GUI.Label(new MyMonoGame.Vector(Game.singleton.ScreenWidth / 2, Game.singleton.ScreenHeight / 4), "Galactic Colors Control", Game.singleton.fonts.title , new MyMonoGame.Colors(Color.White), Manager.textAlign.centerCenter); + if (showLoading) + { + Game.singleton.GUI.Box(new Rectangle(Game.singleton.ScreenWidth / 2 - 150, Game.singleton.ScreenHeight / 4 + 50, 300, 50), Game.singleton.buttonsSprites[0]); + Game.singleton.GUI.Label(new Rectangle(Game.singleton.ScreenWidth / 2 - 150, Game.singleton.ScreenHeight / 4 + 50, 300, 50), "Loading", Game.singleton.fonts.basic); + } + else + { + if (showOKMessage) + { + Game.singleton.GUI.Box(new Rectangle(Game.singleton.ScreenWidth / 2 - 150, Game.singleton.ScreenHeight / 4 + 50, 300, 150), Game.singleton.buttonsSprites[0]); + Game.singleton.GUI.Label(new MyMonoGame.Vector(Game.singleton.ScreenWidth / 2, Game.singleton.ScreenHeight / 4 + 60), message.title, Game.singleton.fonts.basic, null, Manager.textAlign.bottomCenter); + Game.singleton.GUI.Label(new MyMonoGame.Vector(Game.singleton.ScreenWidth / 2, Game.singleton.ScreenHeight / 4 + 100), message.text, Game.singleton.fonts.small, null, Manager.textAlign.bottomCenter); + if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 - 140, Game.singleton.ScreenHeight / 4 + 150, 280, 40), Game.singleton.buttonsSprites[0], "Ok", Game.singleton.fonts.basic)){ Game.singleton.GUI.ResetFocus(); showOKMessage = false; } + } + else + { + if (Game.singleton.GUI.TextField(new Rectangle(Game.singleton.ScreenWidth / 2 - 75, Game.singleton.ScreenHeight / 2 - 30, 150, 40), ref username, Game.singleton.fonts.basic, new MyMonoGame.Colors(Color.LightGray, Color.White), Manager.textAlign.centerCenter, "Username")) { + if (!locked) + { + locked = true; + new Thread(IdentifiacateHost).Start(); + } + } + if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 - 75, Game.singleton.ScreenHeight / 2 + 20, 150, 40), Game.singleton.buttonsSprites[0], "Validate", Game.singleton.fonts.basic, new MyMonoGame.Colors(Color.LightGray, Color.White))) { + if (!locked) + { + locked = true; + new Thread(IdentifiacateHost).Start(); + } + } + if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 - 75, Game.singleton.ScreenHeight / 2 + 70, 150, 40), Game.singleton.buttonsSprites[0], "Back", Game.singleton.fonts.basic, new MyMonoGame.Colors(Color.LightGray, Color.White))) + { + if (!locked) + { + locked = true; + Game.singleton.GUI.ResetFocus(); + new Thread(() => + { + while (!Utilities.DoubleTo(ref Game.singleton.background.speedX, 1, 0.1)) { Thread.Sleep(20); } + Game.singleton.gameState = new MainMenuState(); + }).Start(); + } + } + } + } + } + + private void IdentifiacateHost() + { + showLoading = true; + if (username != null) + { + if (username.Length > 3) + { + ResultData res = Game.singleton.client.Request(new string[2] { "connect", username }); + if (res.type == ResultTypes.OK) + { + Game.singleton.gameState = new GameState(username); + } + else + { + message.title = "Error"; + message.text = Common.ArrayToString(res.result); + showOKMessage = true; + } + } + } + showLoading = false; + locked = false; + } + + + public override void Update() + { + Game.singleton.background.Update(); + } + } +} \ No newline at end of file diff --git a/Galactic Colors Control GUI/States/MainMenuState.cs b/Galactic Colors Control GUI/States/MainMenuState.cs new file mode 100644 index 0000000..4c190fc --- /dev/null +++ b/Galactic Colors Control GUI/States/MainMenuState.cs @@ -0,0 +1,61 @@ +using System; +using Microsoft.Xna.Framework.Graphics; +using Microsoft.Xna.Framework; +using MyMonoGame.GUI; +using System.Reflection; +using Galactic_Colors_Control; +using System.Threading; + +namespace Galactic_Colors_Control_GUI.States +{ + public class MainMenuState : State + { + public static Texture2D logoSprite; + private bool locked = false; + + public override void Draw(SpriteBatch spritebatch) + { + Game.singleton.background.Draw(spritebatch); + Game.singleton.GUI.Label(new MyMonoGame.Vector(Game.singleton.ScreenWidth / 2, Game.singleton.ScreenHeight / 4), "Galactic Colors Control", Game.singleton.fonts.title, new MyMonoGame.Colors(Color.White), Manager.textAlign.centerCenter); + Game.singleton.GUI.Label(new MyMonoGame.Vector(Game.singleton.ScreenWidth / 2, Game.singleton.ScreenHeight / 4 + 40), "GUI " + Assembly.GetEntryAssembly().GetName().Version.ToString(), Game.singleton.fonts.basic, new MyMonoGame.Colors(Color.White), Manager.textAlign.centerCenter); + if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth - 64, Game.singleton.ScreenHeight - 74, 64, 64), logoSprite)) { System.Diagnostics.Process.Start("https://sheychen.shost.ca/"); } + if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 - 75, Game.singleton.ScreenHeight / 2 - 30, 150, 40), Game.singleton.buttonsSprites[0], "Play", Game.singleton.fonts.basic, new MyMonoGame.Colors(Color.White, Color.Green))) + { + if (!locked) + { + locked = true; + Game.singleton.GUI.ResetFocus(); + Game.singleton.client = new Client(); + new Thread(() => + { + while (!Utilities.DoubleTo(ref Game.singleton.background.speedX, 5, 0.1)) { Thread.Sleep(20); } + Game.singleton.gameState = new ConnectState(); + }).Start(); + } + } + if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 - 75, Game.singleton.ScreenHeight / 2 + 20, 150, 40), Game.singleton.buttonsSprites[0], "Options", Game.singleton.fonts.basic, new MyMonoGame.Colors(Color.White, Color.Blue))) { + Game.singleton.GUI.ResetFocus(); + Game.singleton.gameState = new OptionsState(); + } + if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 - 75, Game.singleton.ScreenHeight / 2 + 70, 150, 40), Game.singleton.buttonsSprites[0], "Exit", Game.singleton.fonts.basic, new MyMonoGame.Colors(Color.White, Color.Red))) + { + if (!locked) + { + locked = true; + Game.singleton.GUI.ResetFocus(); + Game.singleton.gameState = new TitleState(); + new Thread(() => + { + while (!Utilities.DoubleTo(ref Game.singleton.background.speedX, 0, 0.1)) { Thread.Sleep(50); } + Game.singleton.Exit(); + }).Start(); + } + } + } + + public override void Update() + { + Game.singleton.background.Update(); + } + } +} diff --git a/Galactic Colors Control GUI/States/OptionsState.cs b/Galactic Colors Control GUI/States/OptionsState.cs new file mode 100644 index 0000000..e0b90b5 --- /dev/null +++ b/Galactic Colors Control GUI/States/OptionsState.cs @@ -0,0 +1,17 @@ +using Microsoft.Xna.Framework.Graphics; + +namespace Galactic_Colors_Control_GUI.States +{ + public class OptionsState : State + { + public override void Draw(SpriteBatch spritebatch) + { + Game.singleton.background.Draw(spritebatch); + } + + public override void Update() + { + Game.singleton.background.Update(); + } + } +} \ No newline at end of file diff --git a/Galactic Colors Control GUI/States/State.cs b/Galactic Colors Control GUI/States/State.cs new file mode 100644 index 0000000..294cd2f --- /dev/null +++ b/Galactic Colors Control GUI/States/State.cs @@ -0,0 +1,20 @@ +using Microsoft.Xna.Framework.Graphics; + +namespace Galactic_Colors_Control_GUI.States +{ + /// + /// Game Menu Main Class + /// + public class State + { + public virtual void Draw(SpriteBatch spritebatch) + { + + } + + public virtual void Update() + { + + } + } +} diff --git a/Galactic Colors Control GUI/States/TitleState.cs b/Galactic Colors Control GUI/States/TitleState.cs new file mode 100644 index 0000000..67b8e40 --- /dev/null +++ b/Galactic Colors Control GUI/States/TitleState.cs @@ -0,0 +1,41 @@ +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using MyMonoGame.GUI; +using System; + +namespace Galactic_Colors_Control_GUI.States +{ + /// + /// Only title in screen (and state change) + /// + public class TitleState : State + { + private DateTime _changeDate; + private State _target; + + public TitleState() + { + _target = null; + } + + public TitleState(State target, TimeSpan time) + { + _target = target; + _changeDate = DateTime.Now.Add(time); + } + + public override void Draw(SpriteBatch spritebatch) + { + Game.singleton.background.Draw(spritebatch); + Game.singleton.GUI.Label(new MyMonoGame.Vector(Game.singleton.ScreenWidth / 2, Game.singleton.ScreenHeight / 2), "Galactic Colors Control", Game.singleton.fonts.title, new MyMonoGame.Colors(Color.White), Manager.textAlign.centerCenter); + } + + public override void Update() + { + if (_target != null) + { + if (DateTime.Now > _changeDate) { Game.singleton.gameState = _target; } + } + } + } +} diff --git a/Galactic Colors Control GUI/Utilities.cs b/Galactic Colors Control GUI/Utilities.cs index 40ae3b0..9dca3de 100644 --- a/Galactic Colors Control GUI/Utilities.cs +++ b/Galactic Colors Control GUI/Utilities.cs @@ -1,9 +1,17 @@ using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Graphics; +using System; using System.IO; namespace Galactic_Colors_Control_GUI { + public struct Fonts + { + public SpriteFont small; //Text fonts + public SpriteFont basic; + public SpriteFont title; + } + internal static class Utilities { /// @@ -37,5 +45,18 @@ namespace Galactic_Colors_Control_GUI } } } + + public static bool DoubleTo(ref double value, double target, double speed) + { + speed = Math.Abs(speed); + bool up = value < target; + value += (up ? 1 : -1) * speed; + if ((up && value >= target) || (!up && value <= target)) + { + value = target; + return true; + } + return false; + } } } \ No newline at end of file diff --git a/Galactic Colors Control.sln b/Galactic Colors Control.sln index 89b466b..65d7181 100644 --- a/Galactic Colors Control.sln +++ b/Galactic Colors Control.sln @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 14 -VisualStudioVersion = 14.0.24720.0 +VisualStudioVersion = 14.0.25420.1 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Galactic Colors Control Server", "Galactic Colors Control Server\Galactic Colors Control Server.csproj", "{9E3AF4E1-88C6-4139-A15C-B4F633E80612}" ProjectSection(ProjectDependencies) = postProject @@ -15,6 +15,7 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Galactic Colors Control", " EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Galactic Colors Control GUI", "Galactic Colors Control GUI\Galactic Colors Control GUI.csproj", "{F6CDDF1B-5A57-4A84-B57C-749FFF9AE031}" ProjectSection(ProjectDependencies) = postProject + {022A69CE-22B5-4934-BE9F-A9C6DF9557ED} = {022A69CE-22B5-4934-BE9F-A9C6DF9557ED} {93582CE8-C8C8-4E19-908B-D671ECBADE25} = {93582CE8-C8C8-4E19-908B-D671ECBADE25} EndProjectSection EndProject diff --git a/Galactic Colors Control/Program.cs b/Galactic Colors Control/Program.cs index 099e81a..5d0aed5 100644 --- a/Galactic Colors Control/Program.cs +++ b/Galactic Colors Control/Program.cs @@ -208,16 +208,16 @@ namespace Galactic_Colors_Control /// Send success private bool Send(Data packet) { - try - { + //try + //{ ClientSocket.Send(packet.ToBytes()); return true; - } + /*} catch //Can't contact server { _errorCount++; } - return false; + return false;*/ } /// From ed1f647fa2ca9336baa594e65611beb39fb74be4 Mon Sep 17 00:00:00 2001 From: sheychen Date: Tue, 15 Nov 2016 12:11:42 +0100 Subject: [PATCH 07/11] Changer version format to : 'major.realese.fix.build' --- AssemblyInfoCommon.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/AssemblyInfoCommon.cs b/AssemblyInfoCommon.cs index dc9abee..f1919a8 100644 --- a/AssemblyInfoCommon.cs +++ b/AssemblyInfoCommon.cs @@ -17,5 +17,5 @@ using System.Reflection; // Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de build et de révision par défaut // en utilisant '*', comme indiqué ci-dessous : // [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.1.1")] -[assembly: AssemblyFileVersion("1.0.1.1")] \ No newline at end of file +[assembly: AssemblyVersion("1.1.0.1")] +[assembly: AssemblyFileVersion("1.1.0.1")] \ No newline at end of file From 5add5b8f282394f1a49f09adda5e1d566a990776 Mon Sep 17 00:00:00 2001 From: sheychen Date: Tue, 15 Nov 2016 18:54:13 +0100 Subject: [PATCH 08/11] Common Logger, MultiLang(not used), Config --- .../Galactic Colors Control Common.csproj | 16 +++ .../Logger.cs | 99 ++++++++------ Galactic Colors Control Common/MultiLang.cs | 74 +++++++++++ .../Properties/Resources.Designer.cs | 87 ++++++++++++ .../Properties/Resources.resx | 124 ++++++++++++++++++ .../Resources/Lang.csv | 5 + Galactic Colors Control Console/Config.cs | 117 +++++++++++++++++ .../Galactic Colors Control Console.csproj | 1 + Galactic Colors Control Console/Program.cs | 40 +++++- Galactic Colors Control GUI/Config.cs | 117 +++++++++++++++++ .../Galactic Colors Control GUI.csproj | 1 + Galactic Colors Control GUI/Game.cs | 11 +- Galactic Colors Control GUI/Program.cs | 25 +++- .../States/GameState.cs | 55 ++++---- .../Commands/Client/KickCommand.cs | 4 +- .../Commands/ConnectCommand.cs | 4 +- .../Commands/ExitCommand.cs | 4 +- .../Commands/LogLevelCommand.cs | 1 + .../Commands/Manager.cs | 4 +- .../Commands/Party/PartyCreateCommand.cs | 2 +- .../Commands/Party/PartyStopCommand.cs | 2 +- .../Commands/Server/ServerCloseCommand.cs | 2 +- .../Commands/Server/ServerOpenCommand.cs | 2 +- Galactic Colors Control Server/Config.cs | 16 ++- .../Galactic Colors Control Server.csproj | 1 - Galactic Colors Control Server/Program.cs | 49 +++---- Galactic Colors Control Server/Utilities.cs | 6 +- Galactic Colors Control/Program.cs | 27 +++- 28 files changed, 769 insertions(+), 127 deletions(-) rename {Galactic Colors Control Server => Galactic Colors Control Common}/Logger.cs (59%) create mode 100644 Galactic Colors Control Common/MultiLang.cs create mode 100644 Galactic Colors Control Common/Properties/Resources.Designer.cs create mode 100644 Galactic Colors Control Common/Properties/Resources.resx create mode 100644 Galactic Colors Control Common/Resources/Lang.csv create mode 100644 Galactic Colors Control Console/Config.cs create mode 100644 Galactic Colors Control GUI/Config.cs diff --git a/Galactic Colors Control Common/Galactic Colors Control Common.csproj b/Galactic Colors Control Common/Galactic Colors Control Common.csproj index 293857c..10505e4 100644 --- a/Galactic Colors Control Common/Galactic Colors Control Common.csproj +++ b/Galactic Colors Control Common/Galactic Colors Control Common.csproj @@ -49,7 +49,14 @@ + + + + True + True + Resources.resx + @@ -57,6 +64,15 @@ + + + ResXFileCodeGenerator + Resources.Designer.cs + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + + ..\Resources\Lang.csv;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 + + \ No newline at end of file diff --git a/Galactic Colors Control Common/Resources/Lang.csv b/Galactic Colors Control Common/Resources/Lang.csv new file mode 100644 index 0000000..44fada4 --- /dev/null +++ b/Galactic Colors Control Common/Resources/Lang.csv @@ -0,0 +1,5 @@ +Key;Français;English +ServerJoin;rejoint le server;join the server +PartyJoin;rejoint la partie;join the party +ServerLeave;quitte le server;leave the server +PartyLeave;quitte la partie;leave the party \ No newline at end of file diff --git a/Galactic Colors Control Console/Config.cs b/Galactic Colors Control Console/Config.cs new file mode 100644 index 0000000..b621703 --- /dev/null +++ b/Galactic Colors Control Console/Config.cs @@ -0,0 +1,117 @@ +using Galactic_Colors_Control_Common; +using System; +using System.IO; +using System.Xml; +using System.Xml.Serialization; + +namespace Galactic_Colors_Control_Console +{ + [XmlRoot("config")] + public class Config + { + public string logPath = AppDomain.CurrentDomain.BaseDirectory + "Logs"; + public Logger.logType logLevel = Logger.logType.info; + public char commandChar = '/'; + public ConsoleColor[] logForeColor = new ConsoleColor[6] { ConsoleColor.DarkGray, ConsoleColor.Gray, ConsoleColor.White, ConsoleColor.Yellow, ConsoleColor.Red, ConsoleColor.White }; + public ConsoleColor[] logBackColor = new ConsoleColor[6] { ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Red }; + public int lang = 0; + + /// + /// Load config from xml file + /// App.config is too easy + /// + /// Loaded config + public Config Load() + { + Program.logger.Write("Loading config", Logger.logType.info); + Config config = new Config(); + if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + "Config.xml")) + { + if (CorrectConfig()) + { + XmlSerializer xs = new XmlSerializer(typeof(Config)); + using (StreamReader re = new StreamReader(AppDomain.CurrentDomain.BaseDirectory + "Config.xml")) + { + config = xs.Deserialize(re) as Config; + }; + } + else + { + Program.logger.Write("Old config in Config.xml.old", Logger.logType.warm); + File.Delete(AppDomain.CurrentDomain.BaseDirectory + "Config.xml.old"); + File.Move(AppDomain.CurrentDomain.BaseDirectory + "Config.xml", AppDomain.CurrentDomain.BaseDirectory + "Config.xml.old"); + config.Save(); + } + } + else + { + Program.logger.Write("Any config file", Logger.logType.error); + config.Save(); + } + if (Program._debug) { config.logLevel = Logger.logType.debug; } + if (Program._dev) { config.logLevel = Logger.logType.dev; } + return config; + } + + /// + /// Write actual config in xml file + /// + public void Save() + { + XmlSerializer xs = new XmlSerializer(typeof(Config)); + if (Program._debug || Program._dev) { logLevel = Logger.logType.info; } + using (StreamWriter st = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "Config.xml")) + { + xs.Serialize(st, this); + }; + if (Program._debug) { logLevel = Logger.logType.debug; } + if (Program._dev) { logLevel = Logger.logType.dev; } + } + + /// + /// Check config format using Schema + /// + public bool CorrectConfig() + { + bool isCorrect = false; + + using (Stream fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "Config.xml", FileMode.Open)) + { + XmlReader re = new XmlTextReader(fs); + XmlSerializer xs = new XmlSerializer(typeof(Config)); + try + { + isCorrect = xs.CanDeserialize(re); + } + catch (XmlException e) + { + isCorrect = false; + Program.logger.Write("Error: " + e.Message, Logger.logType.error); + } + } + + if (isCorrect) + { + try + { + XmlDocument d = new XmlDocument(); + d.Load(AppDomain.CurrentDomain.BaseDirectory + "Config.xml"); + d.Schemas.Add("", XmlReader.Create("ConfigSchema.xsd")); + + d.Validate((o, e) => + { + Program.logger.Write("Error: " + e.Message, Logger.logType.error); + isCorrect = false; + }); + } + catch (XmlException e) + { + isCorrect = false; + Program.logger.Write("Error: " + e.Message, Logger.logType.error); + } + } + + return isCorrect; + } + } +} \ No newline at end of file diff --git a/Galactic Colors Control Console/Galactic Colors Control Console.csproj b/Galactic Colors Control Console/Galactic Colors Control Console.csproj index 50b8893..f82f6ef 100644 --- a/Galactic Colors Control Console/Galactic Colors Control Console.csproj +++ b/Galactic Colors Control Console/Galactic Colors Control Console.csproj @@ -47,6 +47,7 @@ Properties\AssemblyInfoCommon.cs + diff --git a/Galactic Colors Control Console/Program.cs b/Galactic Colors Control Console/Program.cs index dbc657a..8637b21 100644 --- a/Galactic Colors Control Console/Program.cs +++ b/Galactic Colors Control Console/Program.cs @@ -11,18 +11,44 @@ namespace Galactic_Colors_Control_Console /// internal class Program { - private static Client client; - private static bool run = true; - private static char commandChar = '/'; + public static bool _debug = false; + public static bool _dev = false; - private static void Main() + private static Client client = new Client(); + private static MultiLang multilang = new MultiLang(); //TODO use multilang + public static Config config = new Config(); + public static Logger logger = new Logger(); + private static bool run = true; + + private static void Main(string[] args) { - client = new Client(); + config = config.Load(); + logger.Initialise(config.logPath, config.logBackColor, config.logForeColor, config.logLevel); + multilang.Load(); client.OnEvent += new EventHandler(OnEvent); //Set OnEvent function Console.Title = "Galactic Colors Control Client"; //Start display Console.Write(">"); Common.ConsoleWrite("Galactic Colors Control Client", ConsoleColor.Red); Common.ConsoleWrite("Console " + Assembly.GetEntryAssembly().GetName().Version.ToString(), ConsoleColor.Yellow); + if (args.Length > 0) + { + switch (args[0]) + { + case "--debug": + _debug = true; + logger.Write("CLIENT IS IN DEBUG MODE !", Logger.logType.error, Logger.logConsole.show); + break; + + case "--dev": + _dev = true; + logger.Write("CLIENT IS IN DEV MODE !", Logger.logType.error, Logger.logConsole.show); + break; + + default: + Common.ConsoleWrite("Use --debug or --dev"); + break; + } + } bool hostSet = false; while (!hostSet) //Request hostname { @@ -78,7 +104,7 @@ namespace Galactic_Colors_Control_Console return; string[] req; - if (input[0] == commandChar) + if (input[0] == config.commandChar) { input = input.Substring(1); req = Common.SplitArgs(input); @@ -93,7 +119,7 @@ namespace Galactic_Colors_Control_Console private static void OnEvent(object sender, EventArgs e) { EventData eve = ((EventDataArgs)e).Data; - Common.ConsoleWrite(eve.ToSmallString()); //TODO add processing (common) + Common.ConsoleWrite(multilang.GetEventText(eve, config.lang)); } } } \ No newline at end of file diff --git a/Galactic Colors Control GUI/Config.cs b/Galactic Colors Control GUI/Config.cs new file mode 100644 index 0000000..0632ad9 --- /dev/null +++ b/Galactic Colors Control GUI/Config.cs @@ -0,0 +1,117 @@ +using Galactic_Colors_Control_Common; +using System; +using System.IO; +using System.Xml; +using System.Xml.Serialization; + +namespace Galactic_Colors_Control_GUI +{ + [XmlRoot("config")] + public class Config + { + public string logPath = AppDomain.CurrentDomain.BaseDirectory + "Logs"; + public Logger.logType logLevel = Logger.logType.info; + public char commandChar = '/'; + public ConsoleColor[] logForeColor = new ConsoleColor[6] { ConsoleColor.DarkGray, ConsoleColor.Gray, ConsoleColor.White, ConsoleColor.Yellow, ConsoleColor.Red, ConsoleColor.White }; + public ConsoleColor[] logBackColor = new ConsoleColor[6] { ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Red }; + public int lang = 0; + + /// + /// Load config from xml file + /// App.config is too easy + /// + /// Loaded config + public Config Load() + { + Game.singleton.logger.Write("Loading config", Logger.logType.info); + Config config = new Config(); + if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + "Config.xml")) + { + if (CorrectConfig()) + { + XmlSerializer xs = new XmlSerializer(typeof(Config)); + using (StreamReader re = new StreamReader(AppDomain.CurrentDomain.BaseDirectory + "Config.xml")) + { + config = xs.Deserialize(re) as Config; + }; + } + else + { + Game.singleton.logger.Write("Old config in Config.xml.old", Logger.logType.warm); + File.Delete(AppDomain.CurrentDomain.BaseDirectory + "Config.xml.old"); + File.Move(AppDomain.CurrentDomain.BaseDirectory + "Config.xml", AppDomain.CurrentDomain.BaseDirectory + "Config.xml.old"); + config.Save(); + } + } + else + { + Game.singleton.logger.Write("Any config file", Logger.logType.error); + config.Save(); + } + if (Program._debug) { config.logLevel = Logger.logType.debug; } + if (Program._dev) { config.logLevel = Logger.logType.dev; } + return config; + } + + /// + /// Write actual config in xml file + /// + public void Save() + { + XmlSerializer xs = new XmlSerializer(typeof(Config)); + if (Program._debug || Program._dev) { logLevel = Logger.logType.info; } + using (StreamWriter st = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "Config.xml")) + { + xs.Serialize(st, this); + }; + if (Program._debug) { logLevel = Logger.logType.debug; } + if (Program._dev) { logLevel = Logger.logType.dev; } + } + + /// + /// Check config format using Schema + /// + public bool CorrectConfig() + { + bool isCorrect = false; + + using (Stream fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "Config.xml", FileMode.Open)) + { + XmlReader re = new XmlTextReader(fs); + XmlSerializer xs = new XmlSerializer(typeof(Config)); + try + { + isCorrect = xs.CanDeserialize(re); + } + catch (XmlException e) + { + isCorrect = false; + Game.singleton.logger.Write("Error: " + e.Message, Logger.logType.error); + } + } + + if (isCorrect) + { + try + { + XmlDocument d = new XmlDocument(); + d.Load(AppDomain.CurrentDomain.BaseDirectory + "Config.xml"); + d.Schemas.Add("", XmlReader.Create("ConfigSchema.xsd")); + + d.Validate((o, e) => + { + Game.singleton.logger.Write("Error: " + e.Message, Logger.logType.error); + isCorrect = false; + }); + } + catch (XmlException e) + { + isCorrect = false; + Game.singleton.logger.Write("Error: " + e.Message, Logger.logType.error); + } + } + + return isCorrect; + } + } +} \ No newline at end of file diff --git a/Galactic Colors Control GUI/Galactic Colors Control GUI.csproj b/Galactic Colors Control GUI/Galactic Colors Control GUI.csproj index eb60deb..513ec85 100644 --- a/Galactic Colors Control GUI/Galactic Colors Control GUI.csproj +++ b/Galactic Colors Control GUI/Galactic Colors Control GUI.csproj @@ -45,6 +45,7 @@ Properties\AssemblyInfoCommon.cs + diff --git a/Galactic Colors Control GUI/Game.cs b/Galactic Colors Control GUI/Game.cs index 788f013..f7e68c5 100644 --- a/Galactic Colors Control GUI/Game.cs +++ b/Galactic Colors Control GUI/Game.cs @@ -1,4 +1,5 @@ using Galactic_Colors_Control; +using Galactic_Colors_Control_Common; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; @@ -7,8 +8,6 @@ using Microsoft.Xna.Framework.Input; using MyMonoGame.GUI; using System; using System.IO; -using System.Reflection; -using System.Threading; namespace Galactic_Colors_Control_GUI { @@ -33,6 +32,9 @@ namespace Galactic_Colors_Control_GUI public boxSprites[] buttonsSprites = new boxSprites[1]; public Background background; + public MultiLang multilang = new MultiLang(); + public Config config = new Config(); + public Logger logger = new Logger(); public Client client; //Client Core public Manager GUI = new Manager(); //MyMonogameGUI @@ -72,6 +74,11 @@ namespace Galactic_Colors_Control_GUI /// protected override void Initialize() { + config = config.Load(); + logger.Initialise(config.logPath, config.logBackColor, config.logForeColor, config.logLevel); + multilang.Load(); + if (Program._debug) { logger.Write("CLIENT IS IN DEBUG MODE !", Logger.logType.error, Logger.logConsole.show); } + if (Program._dev) { logger.Write("CLIENT IS IN DEV MODE !", Logger.logType.error, Logger.logConsole.show); } nullSprite = new Texture2D(GraphicsDevice, 1, 1); nullSprite.SetData(new Color[1 * 1] { Color.White }); diff --git a/Galactic Colors Control GUI/Program.cs b/Galactic Colors Control GUI/Program.cs index 6078cfc..18b1aa6 100644 --- a/Galactic Colors Control GUI/Program.cs +++ b/Galactic Colors Control GUI/Program.cs @@ -1,4 +1,5 @@ -using System; +using Galactic_Colors_Control_Common; +using System; namespace Galactic_Colors_Control_GUI { @@ -7,13 +8,31 @@ namespace Galactic_Colors_Control_GUI /// public static class Program { + public static bool _dev = false; + public static bool _debug = false; /// /// The main entry point for the application. /// [STAThread] - private static void Main() + private static void Main(string[] args) { - //TODO add debug and more + if (args.Length > 0) + { + switch (args[0]) + { + case "--debug": + _debug = true; + break; + + case "--dev": + _dev = true; + break; + + default: + Common.ConsoleWrite("Use --debug or --dev"); + break; + } + } using (var game = new Game()) game.Run(); } diff --git a/Galactic Colors Control GUI/States/GameState.cs b/Galactic Colors Control GUI/States/GameState.cs index e0aab0c..e763883 100644 --- a/Galactic Colors Control GUI/States/GameState.cs +++ b/Galactic Colors Control GUI/States/GameState.cs @@ -53,50 +53,57 @@ namespace Galactic_Colors_Control_GUI.States Game.singleton.GUI.Box(new Rectangle(Game.singleton.ScreenWidth / 2 - 150, Game.singleton.ScreenHeight / 4 + 50, 300, 150), Game.singleton.buttonsSprites[0]); Game.singleton.GUI.Label(new MyMonoGame.Vector(Game.singleton.ScreenWidth / 2, Game.singleton.ScreenHeight / 4 + 60), message.title, Game.singleton.fonts.basic, null, Manager.textAlign.bottomCenter); Game.singleton.GUI.Label(new MyMonoGame.Vector(Game.singleton.ScreenWidth / 2, Game.singleton.ScreenHeight / 4 + 100), message.text, Game.singleton.fonts.small, null, Manager.textAlign.bottomCenter); - if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 - 140, Game.singleton.ScreenHeight / 4 + 150, 280, 40), Game.singleton.buttonsSprites[0], "Ok", Game.singleton.fonts.basic)) { Game.singleton.GUI.ResetFocus(); showOKMessage = false; Game.singleton.client.ExitHost(); Game.singleton.gameState = new MainMenuState(); } + if (Game.singleton.GUI.Button(new Rectangle(Game.singleton.ScreenWidth / 2 - 140, Game.singleton.ScreenHeight / 4 + 150, 280, 40), Game.singleton.buttonsSprites[0], "Ok", Game.singleton.fonts.basic)) { Game.singleton.GUI.ResetFocus(); showOKMessage = false; Game.singleton.client.ExitHost(); } } } } public override void Update() { - if (Keyboard.GetState().IsKeyDown(Keys.Escape)) { Game.singleton.GUI.ResetFocus(); Game.singleton.client.ExitHost(); Game.singleton.gameState = new MainMenuState(); } + if (Keyboard.GetState().IsKeyDown(Keys.Escape) || (!Game.singleton.client.isRunning)) { Game.singleton.GUI.ResetFocus(); Game.singleton.client.ExitHost(); } } private void ChatEnter() { string request = chatInput; chatInput = null; - ResultData res = Game.singleton.client.Request(new string[2] { "say", request }); - if(res.type != ResultTypes.OK) + + if (request == null) + return; + + if (request.Length == 0) + return; + + ResultData res; + if (request[0] == Game.singleton.config.commandChar) { - //TODO Mutlilang - ChatText("Error :" + Common.ArrayToString(res.result)); + request = request.Substring(1); + res = Game.singleton.client.Request(Common.SplitArgs(request)); + ChatText(res.ToSmallString()); //TODO multilang + } + else + { + res = Game.singleton.client.Request(Common.Strings("say", request)); + if (res.type != ResultTypes.OK) + { + //TODO Mutlilang + ChatText("Error :" + Common.ArrayToString(res.result)); + } } } private void OnEvent(object sender, EventArgs e) { + //TODO add PartyKick EventData eve = ((EventDataArgs)e).Data; - switch (eve.type) + if (eve.type == EventTypes.ServerKick) { - case EventTypes.ChatMessage: - ChatText(Common.ArrayToString(eve.data)); - break; - - case EventTypes.ServerJoin: - ChatText(Common.ArrayToString(eve.data) + "join the server"); - break; - - case EventTypes.ServerLeave: - ChatText(Common.ArrayToString(eve.data) + "leave the server"); - break; - - case EventTypes.ServerKick: - message.title = "Kick from server"; - message.text = Common.ArrayToString(eve.data); - showOKMessage = true; - break; + message.title = "Kick from server"; + message.text = Common.ArrayToString(eve.data); + showOKMessage = true; + }else + { + ChatText(Game.singleton.multilang.GetEventText(eve, Game.singleton.config.lang)); } } diff --git a/Galactic Colors Control Server/Commands/Client/KickCommand.cs b/Galactic Colors Control Server/Commands/Client/KickCommand.cs index 6b1e0aa..a59f9a4 100644 --- a/Galactic Colors Control Server/Commands/Client/KickCommand.cs +++ b/Galactic Colors Control Server/Commands/Client/KickCommand.cs @@ -27,11 +27,11 @@ namespace Galactic_Colors_Control_Server.Commands if (target == null) return new RequestResult(ResultTypes.Error, Common.Strings("Can't find")); - Logger.Write(args[2] + " was kick by server.", Logger.logType.info, Logger.logConsole.show); + Program.logger.Write(args[2] + " was kick by server.", Logger.logType.info, Logger.logConsole.show); if (args.Length > 2) { Utilities.Send(target, new EventData(EventTypes.ServerKick, Common.Strings(args[3]))); - Logger.Write("because" + args[3], Logger.logType.debug); + Program.logger.Write("because" + args[3], Logger.logType.debug); } else { diff --git a/Galactic Colors Control Server/Commands/ConnectCommand.cs b/Galactic Colors Control Server/Commands/ConnectCommand.cs index 7e2ed4d..0a6728d 100644 --- a/Galactic Colors Control Server/Commands/ConnectCommand.cs +++ b/Galactic Colors Control Server/Commands/ConnectCommand.cs @@ -26,7 +26,7 @@ namespace Galactic_Colors_Control_Server.Commands if (args[1].Length < 3) return new RequestResult(ResultTypes.Error, Common.Strings("Too Short")); - Logger.Write("Identifiaction request from " + Utilities.GetName(soc), Logger.logType.debug); + Program.logger.Write("Identifiaction request from " + Utilities.GetName(soc), Logger.logType.debug); bool allreadyconnected = false; args[1] = args[1][0].ToString().ToUpper()[0] + args[1].Substring(1); foreach (Client client in Program.clients.Values) @@ -39,7 +39,7 @@ namespace Galactic_Colors_Control_Server.Commands Program.clients[soc].status = 0; Program.clients[soc].pseudo = args[1]; Utilities.Broadcast(new EventData(EventTypes.ServerJoin, Common.Strings(args[1]))); - Logger.Write("Identified as " + Utilities.GetName(soc) + " form " + ((IPEndPoint)soc.LocalEndPoint).Address.ToString(), Logger.logType.info); + Program.logger.Write("Identified as " + Utilities.GetName(soc) + " form " + ((IPEndPoint)soc.LocalEndPoint).Address.ToString(), Logger.logType.info); return new RequestResult(ResultTypes.OK, Common.Strings(args[1])); } } diff --git a/Galactic Colors Control Server/Commands/ExitCommand.cs b/Galactic Colors Control Server/Commands/ExitCommand.cs index b473af9..ba5d03e 100644 --- a/Galactic Colors Control Server/Commands/ExitCommand.cs +++ b/Galactic Colors Control Server/Commands/ExitCommand.cs @@ -20,13 +20,13 @@ namespace Galactic_Colors_Control_Server.Commands public RequestResult Execute(string[] args, Socket soc, bool server = false) { soc.Shutdown(SocketShutdown.Both); - Logger.Write("Client disconnected from " + Utilities.GetName(soc), Logger.logType.info); + Program.logger.Write("Client disconnected from " + Utilities.GetName(soc), Logger.logType.info); string username = Utilities.GetName(soc); bool connected = Program.clients[soc].status != -1; soc.Close(); Program.clients.Remove(soc); if (connected) { Utilities.Broadcast(new EventData(EventTypes.ServerLeave, Common.Strings(username))); } - Logger.Write("Size: " + Program.clients.Count + "/" + Program.config.size, Logger.logType.debug); + Program.logger.Write("Size: " + Program.clients.Count + "/" + Program.config.size, Logger.logType.debug); return new RequestResult(ResultTypes.OK); } } diff --git a/Galactic Colors Control Server/Commands/LogLevelCommand.cs b/Galactic Colors Control Server/Commands/LogLevelCommand.cs index f5cb6ed..c461946 100644 --- a/Galactic Colors Control Server/Commands/LogLevelCommand.cs +++ b/Galactic Colors Control Server/Commands/LogLevelCommand.cs @@ -22,6 +22,7 @@ namespace Galactic_Colors_Control_Server.Commands { if (Enum.TryParse(args[1], true, out Program.config.logLevel)) { + Program.logger.ChangeLevel(Program.config.logLevel); return new RequestResult(ResultTypes.OK, Common.Strings(Program.config.logLevel.ToString())); } else diff --git a/Galactic Colors Control Server/Commands/Manager.cs b/Galactic Colors Control Server/Commands/Manager.cs index a0defc2..1375ad3 100644 --- a/Galactic Colors Control Server/Commands/Manager.cs +++ b/Galactic Colors Control Server/Commands/Manager.cs @@ -26,7 +26,7 @@ namespace Galactic_Colors_Control_Server.Commands foreach (ICommand com in coms) { commands.Add(com); - Logger.Write("Added command " + com.Group.ToString() + " " + com.Name, Logger.logType.debug); + Program.logger.Write("Added command " + com.Group.ToString() + " " + com.Name, Logger.logType.debug); } } @@ -60,7 +60,7 @@ namespace Galactic_Colors_Control_Server.Commands } catch (Exception e) { - Logger.Write("Command " + args[0] + " Exception : " + e.Message, Logger.logType.error); + Program.logger.Write("Command " + args[0] + " Exception : " + e.Message, Logger.logType.error); return new RequestResult(ResultTypes.Error, Common.Strings("Execute Exception")); } } diff --git a/Galactic Colors Control Server/Commands/Party/PartyCreateCommand.cs b/Galactic Colors Control Server/Commands/Party/PartyCreateCommand.cs index f37a2f5..326f397 100644 --- a/Galactic Colors Control Server/Commands/Party/PartyCreateCommand.cs +++ b/Galactic Colors Control Server/Commands/Party/PartyCreateCommand.cs @@ -33,7 +33,7 @@ namespace Galactic_Colors_Control_Server.Commands return new RequestResult(ResultTypes.Error, Common.Strings("Too Big")); Program.AddParty(new Party(args[2], size, Utilities.GetName(soc))); - Logger.Write("Party " + args[2] + " create with " + size + " slots as " + Program.GetPartyID(false), Logger.logType.info); + Program.logger.Write("Party " + args[2] + " create with " + size + " slots as " + Program.GetPartyID(false), Logger.logType.info); if (server) { Program.selectedParty = Program.GetPartyID(false); diff --git a/Galactic Colors Control Server/Commands/Party/PartyStopCommand.cs b/Galactic Colors Control Server/Commands/Party/PartyStopCommand.cs index dfd5d52..8fb03e0 100644 --- a/Galactic Colors Control Server/Commands/Party/PartyStopCommand.cs +++ b/Galactic Colors Control Server/Commands/Party/PartyStopCommand.cs @@ -27,7 +27,7 @@ namespace Galactic_Colors_Control_Server.Commands { Manager.Execute(new string[4] { "party", "kick", Utilities.GetName(client), "stop_party" }, soc, server); } - Logger.Write("Party " + Program.parties[partyId].name + " closed", Logger.logType.info, server ? Logger.logConsole.show : Logger.logConsole.normal); + Program.logger.Write("Party " + Program.parties[partyId].name + " closed", Logger.logType.info, server ? Logger.logConsole.show : Logger.logConsole.normal); if (Program.selectedParty == partyId) { Program.selectedParty = -1; } Program.parties.Remove(partyId); return new RequestResult(ResultTypes.OK); diff --git a/Galactic Colors Control Server/Commands/Server/ServerCloseCommand.cs b/Galactic Colors Control Server/Commands/Server/ServerCloseCommand.cs index 9cd624f..a9a44bc 100644 --- a/Galactic Colors Control Server/Commands/Server/ServerCloseCommand.cs +++ b/Galactic Colors Control Server/Commands/Server/ServerCloseCommand.cs @@ -23,7 +23,7 @@ namespace Galactic_Colors_Control_Server.Commands return new RequestResult(ResultTypes.Error, Common.Strings("Allready")); Program._open = false; - Logger.Write("Server closed", Logger.logType.warm, Logger.logConsole.show); + Program.logger.Write("Server closed", Logger.logType.warm, Logger.logConsole.show); return new RequestResult(ResultTypes.OK); } } diff --git a/Galactic Colors Control Server/Commands/Server/ServerOpenCommand.cs b/Galactic Colors Control Server/Commands/Server/ServerOpenCommand.cs index aef73bc..6ea0a12 100644 --- a/Galactic Colors Control Server/Commands/Server/ServerOpenCommand.cs +++ b/Galactic Colors Control Server/Commands/Server/ServerOpenCommand.cs @@ -23,7 +23,7 @@ namespace Galactic_Colors_Control_Server.Commands return new RequestResult(ResultTypes.Error, Common.Strings("Allready")); Program._open = true; - Logger.Write("Server opened", Logger.logType.warm, Logger.logConsole.show); + Program.logger.Write("Server opened", Logger.logType.warm, Logger.logConsole.show); return new RequestResult(ResultTypes.OK); } } diff --git a/Galactic Colors Control Server/Config.cs b/Galactic Colors Control Server/Config.cs index 948647f..66aa5a3 100644 --- a/Galactic Colors Control Server/Config.cs +++ b/Galactic Colors Control Server/Config.cs @@ -1,4 +1,5 @@ -using System; +using Galactic_Colors_Control_Common; +using System; using System.IO; using System.Xml; using System.Xml.Serialization; @@ -14,6 +15,7 @@ namespace Galactic_Colors_Control_Server public int size = 20; public ConsoleColor[] logForeColor = new ConsoleColor[6] { ConsoleColor.DarkGray, ConsoleColor.Gray, ConsoleColor.White, ConsoleColor.Yellow, ConsoleColor.Red, ConsoleColor.White }; public ConsoleColor[] logBackColor = new ConsoleColor[6] { ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Black, ConsoleColor.Red }; + public int lang = 0; /// /// Load config from xml file @@ -22,7 +24,7 @@ namespace Galactic_Colors_Control_Server /// Loaded config public Config Load() { - Logger.Write("Loading config", Logger.logType.info); + Program.logger.Write("Loading config", Logger.logType.info); Config config = new Config(); if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + "Config.xml")) { @@ -36,7 +38,7 @@ namespace Galactic_Colors_Control_Server } else { - Logger.Write("Old config in Config.xml.old", Logger.logType.warm); + Program.logger.Write("Old config in Config.xml.old", Logger.logType.warm); File.Delete(AppDomain.CurrentDomain.BaseDirectory + "Config.xml.old"); File.Move(AppDomain.CurrentDomain.BaseDirectory + "Config.xml", AppDomain.CurrentDomain.BaseDirectory + "Config.xml.old"); config.Save(); @@ -44,7 +46,7 @@ namespace Galactic_Colors_Control_Server } else { - Logger.Write("Any config file", Logger.logType.error); + Program.logger.Write("Any config file", Logger.logType.error); config.Save(); } if (Program._debug) { config.logLevel = Logger.logType.debug; } @@ -85,7 +87,7 @@ namespace Galactic_Colors_Control_Server catch (XmlException e) { isCorrect = false; - Logger.Write("Error: " + e.Message, Logger.logType.error); + Program.logger.Write("Error: " + e.Message, Logger.logType.error); } } @@ -99,14 +101,14 @@ namespace Galactic_Colors_Control_Server d.Validate((o, e) => { - Logger.Write("Error: " + e.Message, Logger.logType.error); + Program.logger.Write("Error: " + e.Message, Logger.logType.error); isCorrect = false; }); } catch (XmlException e) { isCorrect = false; - Logger.Write("Error: " + e.Message, Logger.logType.error); + Program.logger.Write("Error: " + e.Message, Logger.logType.error); } } diff --git a/Galactic Colors Control Server/Galactic Colors Control Server.csproj b/Galactic Colors Control Server/Galactic Colors Control Server.csproj index b89d988..648b04e 100644 --- a/Galactic Colors Control Server/Galactic Colors Control Server.csproj +++ b/Galactic Colors Control Server/Galactic Colors Control Server.csproj @@ -88,7 +88,6 @@ - diff --git a/Galactic Colors Control Server/Program.cs b/Galactic Colors Control Server/Program.cs index 729be6b..4aaa36c 100644 --- a/Galactic Colors Control Server/Program.cs +++ b/Galactic Colors Control Server/Program.cs @@ -29,7 +29,9 @@ namespace Galactic_Colors_Control_Server public static Dictionary parties { get; private set; } = new Dictionary(); public static int selectedParty = -1; + //TODO add multilang public static Config config = new Config(); + public static Logger logger = new Logger(); public static Thread CheckConnected = new Thread(CheckConnectedLoop); /// @@ -38,19 +40,19 @@ namespace Galactic_Colors_Control_Server private static void Main(string[] args) { Console.Title = "Galactic Colors Control Server"; - Logger.Write("Galactic Colors Control Server " + Assembly.GetEntryAssembly().GetName().Version.ToString(), Logger.logType.fatal); + logger.Write("Galactic Colors Control Server " + Assembly.GetEntryAssembly().GetName().Version.ToString(), Logger.logType.fatal); if (args.Length > 0) { switch (args[0]) { case "--debug": _debug = true; - Logger.Write("SERVER IS IN DEBUG MODE !", Logger.logType.error, Logger.logConsole.show); + logger.Write("SERVER IS IN DEBUG MODE !", Logger.logType.error, Logger.logConsole.show); break; case "--dev": _dev = true; - Logger.Write("SERVER IS IN DEV MODE !", Logger.logType.error, Logger.logConsole.show); + logger.Write("SERVER IS IN DEV MODE !", Logger.logType.error, Logger.logConsole.show); break; default: @@ -58,7 +60,7 @@ namespace Galactic_Colors_Control_Server break; } } - if (Type.GetType("Mono.Runtime") != null) { Logger.Write("Using Mono", Logger.logType.warm); } + if (Type.GetType("Mono.Runtime") != null) { logger.Write("Using Mono", Logger.logType.warm, Logger.logConsole.show); } Console.Write(">"); SetupServer(); ConsoleLoop(); @@ -71,15 +73,15 @@ namespace Galactic_Colors_Control_Server private static void SetupServer() { config = config.Load(); - Logger.Initialise(); + logger.Initialise(config.logPath, config.logBackColor, config.logForeColor, config.logLevel); Commands.Manager.Load(); - Logger.Write("Setting up server on *:" + config.port, Logger.logType.warm); - Logger.Write("Size:" + config.size, Logger.logType.debug); + logger.Write("Setting up server on *:" + config.port, Logger.logType.warm); + logger.Write("Size:" + config.size, Logger.logType.debug); serverSocket.Bind(new IPEndPoint(IPAddress.Any, config.port)); serverSocket.Listen(0); serverSocket.BeginAccept(AcceptCallback, null); CheckConnected.Start(); - Logger.Write("Server setup complete", Logger.logType.info); + logger.Write("Server setup complete", Logger.logType.info); } /// @@ -102,19 +104,18 @@ namespace Galactic_Colors_Control_Server /// private static void CloseAllSockets() { - Logger.Write("Stoping server", Logger.logType.warm, Logger.logConsole.show); + logger.Write("Stoping server", Logger.logType.warm, Logger.logConsole.show); Utilities.Broadcast(new EventData(EventTypes.ServerKick, Common.Strings("Close"))); config.Save(); foreach (Socket socket in clients.Keys) { socket.Shutdown(SocketShutdown.Both); - Logger.Write("Shutdown " + Utilities.GetName(socket), Logger.logType.debug); + logger.Write("Shutdown " + Utilities.GetName(socket), Logger.logType.debug); } serverSocket.Close(); CheckConnected.Join(2000); - Logger.Write("Server stoped", Logger.logType.info); - Logger._run = false; - Logger.Updater.Join(); + logger.Write("Server stoped", Logger.logType.info); + logger.Join(); } /// @@ -139,14 +140,14 @@ namespace Galactic_Colors_Control_Server } else { - Logger.Write("Client can't join from " + ((IPEndPoint)socket.LocalEndPoint).Address.ToString() + " no more space", Logger.logType.warm); + logger.Write("Client can't join from " + ((IPEndPoint)socket.LocalEndPoint).Address.ToString() + " no more space", Logger.logType.warm); Utilities.Send(socket, new EventData(EventTypes.ServerKick, Common.Strings("Space"))); socket.Close(); } } else { - Logger.Write("Client can't join from " + ((IPEndPoint)socket.LocalEndPoint).Address.ToString() + " server closed", Logger.logType.info); + logger.Write("Client can't join from " + ((IPEndPoint)socket.LocalEndPoint).Address.ToString() + " server closed", Logger.logType.info); Utilities.Send(socket, new EventData(EventTypes.ServerKick, Common.Strings("Close"))); socket.Close(); } @@ -161,11 +162,11 @@ namespace Galactic_Colors_Control_Server Client client = new Client(); clients.Add(socket, client); socket.BeginReceive(buffer, 0, BUFFER_SIZE, SocketFlags.None, ReceiveCallback, socket); - Logger.Write("Client connection from " + Utilities.GetName(socket), Logger.logType.info); - Logger.Write("Size: " + clients.Count + "/" + config.size, Logger.logType.dev); + logger.Write("Client connection from " + Utilities.GetName(socket), Logger.logType.info); + logger.Write("Size: " + clients.Count + "/" + config.size, Logger.logType.dev); if (clients.Count >= config.size) { - Logger.Write("Server full", Logger.logType.warm, Logger.logConsole.show); + logger.Write("Server full", Logger.logType.warm, Logger.logConsole.show); } } @@ -183,10 +184,10 @@ namespace Galactic_Colors_Control_Server } catch (SocketException) { - Logger.Write("Client forcefully disconnected from " + Utilities.GetName(current) + " : SocketException", Logger.logType.info); + logger.Write("Client forcefully disconnected from " + Utilities.GetName(current) + " : SocketException", Logger.logType.info); string username = Utilities.GetName(current); bool connected = clients[current].status != -1; - Logger.Write("Size: " + clients.Count + "/" + config.size, Logger.logType.debug); + logger.Write("Size: " + clients.Count + "/" + config.size, Logger.logType.debug); current.Close(); // Don't shutdown because the socket may be disposed and its disconnected anyway. clients.Remove(current); if (connected) { Utilities.Broadcast(new EventData(EventTypes.ServerLeave, Common.Strings(username))); } @@ -207,13 +208,13 @@ namespace Galactic_Colors_Control_Server break; default: - Logger.Write("Wrong packet from " + Utilities.GetName(current), Logger.logType.error); + logger.Write("Wrong packet from " + Utilities.GetName(current), Logger.logType.error); break; } } else { - Logger.Write("Wrong packet from " + Utilities.GetName(current), Logger.logType.error); + logger.Write("Wrong packet from " + Utilities.GetName(current), Logger.logType.error); } if (clients.ContainsKey(current)) { current.BeginReceive(buffer, 0, BUFFER_SIZE, SocketFlags.None, ReceiveCallback, current); } @@ -228,9 +229,9 @@ namespace Galactic_Colors_Control_Server if ((current.Poll(10, SelectMode.SelectRead) && current.Available == 0) || !current.Connected) { string username = Utilities.GetName(current); - Logger.Write("Client forcefully disconnected from " + username + " : NotConnected", Logger.logType.info); + logger.Write("Client forcefully disconnected from " + username + " : NotConnected", Logger.logType.info); bool connected = clients[current].status != -1; - Logger.Write("Size: " + clients.Count + "/" + config.size, Logger.logType.debug); + logger.Write("Size: " + clients.Count + "/" + config.size, Logger.logType.debug); current.Close(); // Don't shutdown because the socket may be disposed and its disconnected anyway. clients.Remove(current); if (connected) { Utilities.Broadcast(new EventData(EventTypes.ServerLeave, Common.Strings(username))); } diff --git a/Galactic Colors Control Server/Utilities.cs b/Galactic Colors Control Server/Utilities.cs index cfe562c..ba0131f 100644 --- a/Galactic Colors Control Server/Utilities.cs +++ b/Galactic Colors Control Server/Utilities.cs @@ -20,7 +20,7 @@ namespace Galactic_Colors_Control_Server if (Program.clients.ContainsKey(soc)) return Program.clients[soc].status != -1; - Logger.Write("IsConnect : Unknown client", Logger.logType.error); + Program.logger.Write("IsConnect : Unknown client", Logger.logType.error); return false; } @@ -64,12 +64,12 @@ namespace Galactic_Colors_Control_Server soc.Send(packet.ToBytes()); if (Program.config.logLevel == Logger.logType.dev) { - Logger.Write("Send to " + GetName(soc) + " : " + packet.ToLongString(), Logger.logType.dev); + Program.logger.Write("Send to " + GetName(soc) + " : " + packet.ToLongString(), Logger.logType.dev); } } catch (Exception e) { - Logger.Write("Send exception to " + GetName(soc) + " : " + e.Message, Logger.logType.error); + Program.logger.Write("Send exception to " + GetName(soc) + " : " + e.Message, Logger.logType.error); } } } diff --git a/Galactic Colors Control/Program.cs b/Galactic Colors Control/Program.cs index 5d0aed5..9e3dd12 100644 --- a/Galactic Colors Control/Program.cs +++ b/Galactic Colors Control/Program.cs @@ -165,7 +165,26 @@ namespace Galactic_Colors_Control /// ResultData or Timeout public ResultData Request(string[] args) { - // TODO filter Client Side Requests + switch(args[0]) + { + case "exit": + ExitHost(); + return new ResultData(GetRequestId(), ResultTypes.OK); + + case "ping": + return PingHost(); + + default: + return Execute(args); + } + + } + + /// + /// Send row command to server + /// + private ResultData Execute(string[] args) + { RequestData req = new RequestData(GetRequestId(), args); if (!Send(req)) return new ResultData(req.id, ResultTypes.Error, Common.Strings("Send Exception")); @@ -190,16 +209,16 @@ namespace Galactic_Colors_Control /// Ping Current Server IP /// /// Time in ms or 'Timeout' - private string PingHost() + private ResultData PingHost() { Ping ping = new Ping(); PingReply reply; reply = ping.Send(IP); if (reply.Status == IPStatus.Success) - return reply.RoundtripTime.ToString(); + return new ResultData(GetRequestId(), ResultTypes.OK, Common.SplitArgs(reply.RoundtripTime.ToString() + "ms")); - return "Timeout"; + return new ResultData(GetRequestId(), ResultTypes.Error, Common.SplitArgs("Timeout")); } /// From 5dcd7c328e785347dbc59b28d2b09362cd7f1ee6 Mon Sep 17 00:00:00 2001 From: sheychen Date: Wed, 16 Nov 2016 15:20:55 +0100 Subject: [PATCH 09/11] Multilang and working config --- Galactic Colors Control Common/Logger.cs | 12 +++-- Galactic Colors Control Common/MultiLang.cs | 8 ++++ .../Resources/Lang.csv | 27 ++++++++++- .../ConfigSchema.xsd | 27 +++++++++++ .../Galactic Colors Control Console.csproj | 6 +++ Galactic Colors Control Console/Program.cs | 19 ++++---- Galactic Colors Control GUI/Config.cs | 1 + Galactic Colors Control GUI/ConfigSchema.xsd | 28 ++++++++++++ .../Galactic Colors Control GUI.csproj | 6 +++ Galactic Colors Control GUI/Game.cs | 45 +++++++++---------- .../States/ConnectState.cs | 22 ++++----- .../States/GameState.cs | 15 +++---- .../States/IndentificationState.cs | 14 +++--- .../States/MainMenuState.cs | 11 ++--- .../States/TitleState.cs | 2 +- Galactic Colors Control Server/Config.cs | 1 + .../ConfigSchema.xsd | 1 + Galactic Colors Control Server/Program.cs | 13 +++--- Galactic Colors Control Server/Utilities.cs | 2 +- 19 files changed, 184 insertions(+), 76 deletions(-) create mode 100644 Galactic Colors Control Console/ConfigSchema.xsd create mode 100644 Galactic Colors Control GUI/ConfigSchema.xsd diff --git a/Galactic Colors Control Common/Logger.cs b/Galactic Colors Control Common/Logger.cs index 6e55bf7..a78c31a 100644 --- a/Galactic Colors Control Common/Logger.cs +++ b/Galactic Colors Control Common/Logger.cs @@ -34,20 +34,24 @@ namespace Galactic_Colors_Control_Common private ConsoleColor[] logBackColor; private ConsoleColor[] logForeColor; private Thread Updater; - private logType logLevel; + private logType logLevel = logType.info; private bool _run = true; - public bool run { get { return _run; } } + public bool run { get { return _run; } } + private static bool _debug = false; + private static bool _dev = false; /// /// Create log file and start logger thread /// /// Absolute path to logs directory - public void Initialise(string LogPath, ConsoleColor[] backColor, ConsoleColor[] foreColor, logType LogLevel) + public void Initialise(string LogPath, ConsoleColor[] backColor, ConsoleColor[] foreColor, logType LogLevel, bool debug, bool dev) { logPath = LogPath; logBackColor = backColor; logForeColor = foreColor; logLevel = LogLevel; + _debug = debug; + _dev = dev; if (!Directory.Exists(logPath)) { Directory.CreateDirectory(logPath); @@ -120,7 +124,7 @@ namespace Galactic_Colors_Control_Common /// Log struct private void Write(Log log) { - if (logLevel == logType.debug || logLevel == logType.dev) + if (_debug || _dev) { //Add Source Method log.text = "[" + new StackTrace().GetFrame(2).GetMethod().Name + "]: " + log.text; diff --git a/Galactic Colors Control Common/MultiLang.cs b/Galactic Colors Control Common/MultiLang.cs index 0a413a3..f2bcd4a 100644 --- a/Galactic Colors Control Common/MultiLang.cs +++ b/Galactic Colors Control Common/MultiLang.cs @@ -48,6 +48,14 @@ namespace Galactic_Colors_Control_Common } } + public string GetResultText(ResultData res, int lang) + { + string data = Common.ArrayToString(res.result); + if (res.type == ResultTypes.Error) + data = Get("Error", lang) + ": " + data; + return data; + } + public string Get(string Key, int Lang) { string text = ""; diff --git a/Galactic Colors Control Common/Resources/Lang.csv b/Galactic Colors Control Common/Resources/Lang.csv index 44fada4..380b9cf 100644 --- a/Galactic Colors Control Common/Resources/Lang.csv +++ b/Galactic Colors Control Common/Resources/Lang.csv @@ -1,5 +1,30 @@ Key;Français;English +GCC;Galactic Colors Control;Galactic Colors Control +Client;Client;Client +Server;Serveur;Server +Console;Console;Console +Loading;Chargement;Loading +OK;OK;OK +Yes;Oui;Yes +No;Non;No +EnterHostname;Saisir l'addresse;Enter hostname +EnterMessage;Saisir un message;Enter message +Connect;Connexion;Connect +Back;Retour;Back +Username;Pseudo;Username +Validate;Valider;Validate +GUI;GUI;GUI +Play;Jouer;Play +Options;Options;Options +Exit;Quitter;Exit +Error;Erreur;Error +Hide;Cacher;Hide +Show;Afficher;Show +Chat;Chat;Chat +Use;Utiliser;Use +CantConnect;Connexion impossible. Au revoir;Can't connect sorry. Bye ServerJoin;rejoint le server;join the server PartyJoin;rejoint la partie;join the party ServerLeave;quitte le server;leave the server -PartyLeave;quitte la partie;leave the party \ No newline at end of file +PartyLeave;quitte la partie;leave the party +ServerKick;Exclus du serveur;Kick from server \ No newline at end of file diff --git a/Galactic Colors Control Console/ConfigSchema.xsd b/Galactic Colors Control Console/ConfigSchema.xsd new file mode 100644 index 0000000..cf91447 --- /dev/null +++ b/Galactic Colors Control Console/ConfigSchema.xsd @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Galactic Colors Control Console/Galactic Colors Control Console.csproj b/Galactic Colors Control Console/Galactic Colors Control Console.csproj index f82f6ef..30710b6 100644 --- a/Galactic Colors Control Console/Galactic Colors Control Console.csproj +++ b/Galactic Colors Control Console/Galactic Colors Control Console.csproj @@ -61,6 +61,12 @@ Galactic Colors Control + + + Designer + PreserveNewest + +