diff --git a/AnimationsFileCreator/AnimationsFileCreator.csproj b/AnimationsFileCreator/AnimationsFileCreator.csproj new file mode 100644 index 0000000..b8c3b86 --- /dev/null +++ b/AnimationsFileCreator/AnimationsFileCreator.csproj @@ -0,0 +1,17 @@ + + + + Exe + net8.0 + + + + + + + + + + + + diff --git a/AnimationsFileCreator/Program.cs b/AnimationsFileCreator/Program.cs new file mode 100644 index 0000000..68768cf --- /dev/null +++ b/AnimationsFileCreator/Program.cs @@ -0,0 +1,72 @@ +using DangerousD.GameCore.Graphics; +using Microsoft.Xna.Framework; +using Newtonsoft.Json; +using System; +using NativeFileDialogSharp; +using System.IO; +using System.Linq; +using System.Reflection.Metadata; +using Zofo.GameCore.ZoFo_grafics; + +namespace AnimationsFileCreator +{ + class Program + { + [STAThread] + static void Main(string[] args) + { + Console.WriteLine("Добро пожаловать в костыльную программу по созданию файлов анимации для игры DungerousD"); + Console.Write("Введите название текстуры (нажмите enter, чтобы выбрать файл во всплывающем окошке): "); + string textureName = Console.ReadLine(); + if (textureName == "") + { + + DialogResult result = Dialog.FileOpen(); + textureName = result.Path.Split('\\').Last(); + textureName = textureName.Split('.')[0]; + } + Console.WriteLine("Введите количество кадров анимации: "); + int framesCount = int.Parse(Console.ReadLine()); + Console.WriteLine("Введите длительность кадра в анимации: "); + int interval = int.Parse(Console.ReadLine()); + Console.WriteLine("Введите начальную позицию X ректенгла анимации: "); + Rectangle rectangle = new Rectangle(); + rectangle.X = int.Parse(Console.ReadLine()); + Console.WriteLine("Введите начальную позицию Y ректенгла анимации: "); + rectangle.Y = int.Parse(Console.ReadLine()); + Console.WriteLine("Введите начальную позицию Width ректенгла анимации: "); + rectangle.Width = int.Parse(Console.ReadLine()); + Console.WriteLine("Введите начальную позицию Height ректенгла анимации: "); + rectangle.Height = int.Parse(Console.ReadLine()); + Console.WriteLine("Введите название для этого файла - id анимации"); + string id = Console.ReadLine(); + Console.WriteLine("Введите 1 если анимация зациклена, и 0 если нет"); + AnimationContainer container = new AnimationContainer(); + + int a = int.Parse(Console.ReadLine()); + if (a==1) + { + container.IsCycle = true; + } + else + { + container.IsCycle = false; + } + Console.WriteLine("Введите отклонение анимации от стандартной (сначала X, потом enter, потом Y): "); + int otklx = int.Parse(Console.ReadLine()); + int otkly = int.Parse(Console.ReadLine()); + container.Offset =new Vector2(otklx,otkly); + container.FramesCount = framesCount; + container.FrameTime = new System.Collections.Generic.List>(); + container.FrameTime.Add(new Tuple(0, interval)); + container.StartSpriteRectangle = rectangle; + container.TextureName = textureName; + container.TextureFrameInterval = 1; + container.Id = id; + string json = JsonConvert.SerializeObject(container); + StreamWriter writer = new StreamWriter("../../../../ZoFo/Content/animations/"+id); + writer.WriteLine(json); + writer.Close(); + } + } +} diff --git a/Install-Package b/Install-Package new file mode 100644 index 0000000..e69de29 diff --git a/MonogameLibrary/MonogameLibrary.csproj b/MonogameLibrary/MonogameLibrary.csproj index 16a23b2..12f2ed5 100644 --- a/MonogameLibrary/MonogameLibrary.csproj +++ b/MonogameLibrary/MonogameLibrary.csproj @@ -1,7 +1,7 @@ - net6.0 + net8.0 enable enable diff --git a/MonogameLibrary/UI/Base/UIManager.cs b/MonogameLibrary/UI/Base/UIManager.cs index 826a0a1..125df25 100644 --- a/MonogameLibrary/UI/Base/UIManager.cs +++ b/MonogameLibrary/UI/Base/UIManager.cs @@ -59,8 +59,8 @@ namespace MonogameLibrary.UI.Base { keyboardState = Keyboard.GetState(); mouseState = Mouse.GetState(); - mouseState = new MouseState((int)(mouseState.X*(float)resolutionInGame.X/resolution.X), - (int)(mouseState.Y * (float)resolutionInGame.Y / resolution.Y), mouseState.ScrollWheelValue, mouseState.LeftButton, mouseState.MiddleButton, mouseState.RightButton, mouseState.XButton1, mouseState.XButton2); + //mouseState = new MouseState((int)(mouseState.X*(float)resolutionInGame.X/resolution.X), + // (int)(mouseState.Y * (float)resolutionInGame.Y / resolution.Y), mouseState.ScrollWheelValue, mouseState.LeftButton, mouseState.MiddleButton, mouseState.RightButton, mouseState.XButton1, mouseState.XButton2); } catch { diff --git a/MonogameLibrary/UI/Elements/CheckBox.cs b/MonogameLibrary/UI/Elements/CheckBox.cs index 5dc400f..5d927ca 100644 --- a/MonogameLibrary/UI/Elements/CheckBox.cs +++ b/MonogameLibrary/UI/Elements/CheckBox.cs @@ -49,9 +49,9 @@ namespace MonogameLibrary.UI.Elements public override void LoadTexture(ContentManager content) { - texture1 = content.Load("textures\\ui\\checkboxs_off"); - texture2 = content.Load("textures\\ui\\checkboxs_off-on"); - texture3 = content.Load("textures\\ui\\checkboxs_on"); + texture1 = content.Load("Textures\\GUI\\checkboxs_off"); + texture2 = content.Load("Textures\\GUI\\checkboxs_off-on"); + texture3 = content.Load("Textures\\GUI\\checkboxs_on"); base.LoadTexture(content); } public override void Draw(SpriteBatch _spriteBatch) diff --git a/MonogameLibrary/UI/Elements/Slider.cs b/MonogameLibrary/UI/Elements/Slider.cs index b496cdf..f614f53 100644 --- a/MonogameLibrary/UI/Elements/Slider.cs +++ b/MonogameLibrary/UI/Elements/Slider.cs @@ -56,7 +56,7 @@ namespace MonogameLibrary.UI.Elements public override void LoadTexture(ContentManager content) { - texture2 = content.Load("textures\\ui\\slider"); + texture2 = content.Load("Textures\\GUI\\checkboxs_off"); base.LoadTexture(content); } diff --git a/ZoFo.sln b/ZoFo.sln index d0636e2..3ea9985 100644 --- a/ZoFo.sln +++ b/ZoFo.sln @@ -1,8 +1,13 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZoFo", "ZoFo\ZoFo.csproj", "{D63272E5-A54D-4C24-AA48-2945CB1D0BBB}" +# Visual Studio Version 17 +VisualStudioVersion = 17.10.35122.118 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ZoFo", "ZoFo\ZoFo.csproj", "{D63272E5-A54D-4C24-AA48-2945CB1D0BBB}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MonogameLibrary", "MonogameLibrary\MonogameLibrary.csproj", "{D6272E15-AD49-468A-BE0F-D812E8697FAC}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MonogameLibrary", "MonogameLibrary\MonogameLibrary.csproj", "{40880E68-4B3A-417B-A39B-95DE46AA2E7E}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AnimationsFileCreator", "AnimationsFileCreator\AnimationsFileCreator.csproj", "{7B143D5C-5198-4ADE-9291-ECC924B78633}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -14,9 +19,16 @@ Global {D63272E5-A54D-4C24-AA48-2945CB1D0BBB}.Debug|Any CPU.Build.0 = Debug|Any CPU {D63272E5-A54D-4C24-AA48-2945CB1D0BBB}.Release|Any CPU.ActiveCfg = Release|Any CPU {D63272E5-A54D-4C24-AA48-2945CB1D0BBB}.Release|Any CPU.Build.0 = Release|Any CPU - {D6272E15-AD49-468A-BE0F-D812E8697FAC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {D6272E15-AD49-468A-BE0F-D812E8697FAC}.Debug|Any CPU.Build.0 = Debug|Any CPU - {D6272E15-AD49-468A-BE0F-D812E8697FAC}.Release|Any CPU.ActiveCfg = Release|Any CPU - {D6272E15-AD49-468A-BE0F-D812E8697FAC}.Release|Any CPU.Build.0 = Release|Any CPU + {40880E68-4B3A-417B-A39B-95DE46AA2E7E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {40880E68-4B3A-417B-A39B-95DE46AA2E7E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {40880E68-4B3A-417B-A39B-95DE46AA2E7E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {40880E68-4B3A-417B-A39B-95DE46AA2E7E}.Release|Any CPU.Build.0 = Release|Any CPU + {7B143D5C-5198-4ADE-9291-ECC924B78633}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {7B143D5C-5198-4ADE-9291-ECC924B78633}.Debug|Any CPU.Build.0 = Debug|Any CPU + {7B143D5C-5198-4ADE-9291-ECC924B78633}.Release|Any CPU.ActiveCfg = Release|Any CPU + {7B143D5C-5198-4ADE-9291-ECC924B78633}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE EndGlobalSection EndGlobal diff --git a/ZoFo/Content/Content.mgcb b/ZoFo/Content/Content.mgcb index ddc4c36..e1730da 100644 --- a/ZoFo/Content/Content.mgcb +++ b/ZoFo/Content/Content.mgcb @@ -13,3 +13,65 @@ #---------------------------------- Content ---------------------------------# +#begin Fonts/Font.spritefont +/importer:FontDescriptionImporter +/processor:FontDescriptionProcessor +/processorParam:PremultiplyAlpha=True +/processorParam:TextureFormat=Compressed +/build:Fonts/Font.spritefont + +#begin Fonts/Font2.spritefont +/importer:FontDescriptionImporter +/processor:FontDescriptionProcessor +/processorParam:PremultiplyAlpha=True +/processorParam:TextureFormat=Compressed +/build:Fonts/Font2.spritefont + +#begin Textures/GUI/checkboxs_off-on.png +/importer:TextureImporter +/processor:TextureProcessor +/processorParam:ColorKeyColor=255,0,255,255 +/processorParam:ColorKeyEnabled=True +/processorParam:GenerateMipmaps=False +/processorParam:PremultiplyAlpha=True +/processorParam:ResizeToPowerOfTwo=False +/processorParam:MakeSquare=False +/processorParam:TextureFormat=Color +/build:Textures/GUI/checkboxs_off-on.png + +#begin Textures/GUI/checkboxs_off.png +/importer:TextureImporter +/processor:TextureProcessor +/processorParam:ColorKeyColor=255,0,255,255 +/processorParam:ColorKeyEnabled=True +/processorParam:GenerateMipmaps=False +/processorParam:PremultiplyAlpha=True +/processorParam:ResizeToPowerOfTwo=False +/processorParam:MakeSquare=False +/processorParam:TextureFormat=Color +/build:Textures/GUI/checkboxs_off.png + +#begin Textures/GUI/checkboxs_on.png +/importer:TextureImporter +/processor:TextureProcessor +/processorParam:ColorKeyColor=255,0,255,255 +/processorParam:ColorKeyEnabled=True +/processorParam:GenerateMipmaps=False +/processorParam:PremultiplyAlpha=True +/processorParam:ResizeToPowerOfTwo=False +/processorParam:MakeSquare=False +/processorParam:TextureFormat=Color +/build:Textures/GUI/checkboxs_on.png + +#begin Textures/GUI/MenuBackground.jpg +/importer:TextureImporter +/processor:TextureProcessor +/processorParam:ColorKeyColor=255,0,255,255 +/processorParam:ColorKeyEnabled=True +/processorParam:GenerateMipmaps=False +/processorParam:PremultiplyAlpha=True +/processorParam:ResizeToPowerOfTwo=False +/processorParam:MakeSquare=False +/processorParam:TextureFormat=Color +/build:Textures/GUI/MenuBackground.jpg + diff --git a/ZoFo/Content/Fonts/CarltineRegular-K7z5l.ttf b/ZoFo/Content/Fonts/CarltineRegular-K7z5l.ttf new file mode 100644 index 0000000..1496983 Binary files /dev/null and b/ZoFo/Content/Fonts/CarltineRegular-K7z5l.ttf differ diff --git a/ZoFo/Content/Fonts/Debrosee-ALPnL.ttf b/ZoFo/Content/Fonts/Debrosee-ALPnL.ttf new file mode 100644 index 0000000..311dd61 Binary files /dev/null and b/ZoFo/Content/Fonts/Debrosee-ALPnL.ttf differ diff --git a/ZoFo/Content/Fonts/Font.spritefont b/ZoFo/Content/Fonts/Font.spritefont new file mode 100644 index 0000000..754d1ee --- /dev/null +++ b/ZoFo/Content/Fonts/Font.spritefont @@ -0,0 +1,60 @@ + + + + + + + Debrosee-ALPnL.ttf + + + 100 + + + 0 + + + true + + + + + + + + + + + + ~ + + + + diff --git a/ZoFo/Content/Fonts/Font2.spritefont b/ZoFo/Content/Fonts/Font2.spritefont new file mode 100644 index 0000000..3aaf8e7 --- /dev/null +++ b/ZoFo/Content/Fonts/Font2.spritefont @@ -0,0 +1,60 @@ + + + + + + + CarltineRegular-K7z5l.ttf + + + 15 + + + 0 + + + true + + + + + + + + + + + + ~ + + + + diff --git a/ZoFo/Content/Textures/GUI/MenuBackground.jpg b/ZoFo/Content/Textures/GUI/MenuBackground.jpg new file mode 100644 index 0000000..79b0abe Binary files /dev/null and b/ZoFo/Content/Textures/GUI/MenuBackground.jpg differ diff --git a/ZoFo/Content/Textures/GUI/checkboxs_off-on.png b/ZoFo/Content/Textures/GUI/checkboxs_off-on.png new file mode 100644 index 0000000..0537fc1 Binary files /dev/null and b/ZoFo/Content/Textures/GUI/checkboxs_off-on.png differ diff --git a/ZoFo/Content/Textures/GUI/checkboxs_off.png b/ZoFo/Content/Textures/GUI/checkboxs_off.png new file mode 100644 index 0000000..f258fcb Binary files /dev/null and b/ZoFo/Content/Textures/GUI/checkboxs_off.png differ diff --git a/ZoFo/Content/Textures/GUI/checkboxs_on.png b/ZoFo/Content/Textures/GUI/checkboxs_on.png new file mode 100644 index 0000000..9f7a350 Binary files /dev/null and b/ZoFo/Content/Textures/GUI/checkboxs_on.png differ diff --git a/ZoFo/Game1.cs b/ZoFo/Game1.cs deleted file mode 100644 index 3c35539..0000000 --- a/ZoFo/Game1.cs +++ /dev/null @@ -1,52 +0,0 @@ -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; -using Microsoft.Xna.Framework.Input; - -namespace ZoFo; - -public class Game1 : Game -{ - private GraphicsDeviceManager _graphics; - private SpriteBatch _spriteBatch; - - public Game1() - { - _graphics = new GraphicsDeviceManager(this); - Content.RootDirectory = "Content"; - IsMouseVisible = true; - } - - protected override void Initialize() - { - // TODO: Add your initialization logic here - - base.Initialize(); - } - - protected override void LoadContent() - { - _spriteBatch = new SpriteBatch(GraphicsDevice); - - // TODO: use this.Content to load your game content here - } - - protected override void Update(GameTime gameTime) - { - if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || - Keyboard.GetState().IsKeyDown(Keys.Escape)) - Exit(); - - // TODO: Add your update logic here - - base.Update(gameTime); - } - - protected override void Draw(GameTime gameTime) - { - GraphicsDevice.Clear(Color.CornflowerBlue); - - // TODO: Add your drawing code here - - base.Draw(gameTime); - } -} \ No newline at end of file diff --git a/ZoFo/GameCore/Client.cs b/ZoFo/GameCore/Client.cs new file mode 100644 index 0000000..5ee0546 --- /dev/null +++ b/ZoFo/GameCore/Client.cs @@ -0,0 +1,42 @@ + +using System.Collections.Generic; +using System.Text.Json; +using ZoFo.GameCore.GameManagers.NetworkManager; +using ZoFo.GameCore.GameManagers.NetworkManager.Updates; + +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using System; + +namespace ZoFo.GameCore +{ + public class Client + { + ClientNetworkManager networkManager; + public Client() + { + networkManager = new ClientNetworkManager(); + networkManager.GetDataSent += OnDataSend; + } + + public void OnDataSend(string data) + { + List updateDatas = JsonSerializer.Deserialize>(data); + // тут будет switch + } + + public void GameEndedUnexpectedly(){ } + + public void JoinRoom(){ } + + public void JoinYourself(){ } + + internal void Update(GameTime gameTime) + { + } + + internal void Draw(SpriteBatch spriteBatch) + { + } + } +} \ No newline at end of file diff --git a/ZoFo/GameCore/GUI/AbstractGUI.cs b/ZoFo/GameCore/GUI/AbstractGUI.cs index 5208c96..2c2d7f6 100644 --- a/ZoFo/GameCore/GUI/AbstractGUI.cs +++ b/ZoFo/GameCore/GUI/AbstractGUI.cs @@ -1,6 +1,56 @@ -namespace ZoFo.GameCore.GUI; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Xml; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Content; +using Microsoft.Xna.Framework.Graphics; +using Microsoft.Xna.Framework.Input; +using MonogameLibrary.UI.Base; +using MonogameLibrary.UI.Elements; +using ZoFo.GameCore.GameManagers; -public class AbstractGUI +namespace ZoFo.GameCore.GUI; + +public abstract class AbstractGUI { - + protected UIManager Manager = new(); + protected List Elements = new(); + private List ActiveElements; + protected DrawableUIElement SelectedElement; + private bool isStartedPrint = false; + private bool isPressed = false; + + public AbstractGUI() + { + } + + protected abstract void CreateUI(); + private GraphicsDevice graphicsDevice; + public virtual void Initialize() + { + Manager.Initialize(AppManager.Instance.GraphicsDevice); + CreateUI(); + } + + public virtual void LoadContent() + { + Manager.LoadContent(AppManager.Instance.Content, "Font"); + } + + public virtual void Update(GameTime gameTime) + { + Manager.Update(gameTime); + } + + public virtual void Draw(SpriteBatch spriteBatch) + { + Manager.Draw(spriteBatch); + } + + public virtual void ResolutioChenges() + { + + } } \ No newline at end of file diff --git a/ZoFo/GameCore/GUI/BaseGUI.cs b/ZoFo/GameCore/GUI/BaseGUI.cs new file mode 100644 index 0000000..cb159db --- /dev/null +++ b/ZoFo/GameCore/GUI/BaseGUI.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Xml; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Content; +using Microsoft.Xna.Framework.Graphics; +using Microsoft.Xna.Framework.Input; +using MonogameLibrary.UI.Base; +using MonogameLibrary.UI.Elements; + + +namespace ZoFo.GameCore.GUI; + +public class BaseGUI : AbstractGUI +{ + protected override void CreateUI() + { + // int width = AppManager.Instance.inGameHUDHelperResolution.X; + // int height = AppManager.Instance.inGameHUDHelperResolution.Y; + } + + public override void Update(GameTime gameTime) + { + + } +} \ No newline at end of file diff --git a/ZoFo/GameCore/GUI/DebugHUD.cs b/ZoFo/GameCore/GUI/DebugHUD.cs new file mode 100644 index 0000000..de4a587 --- /dev/null +++ b/ZoFo/GameCore/GUI/DebugHUD.cs @@ -0,0 +1,72 @@ +using System.Collections.Generic; +using System.Linq; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using MonogameLibrary.UI.Elements; +using static System.String; +using ZoFo.GameCore.GameManagers; + +namespace ZoFo.GameCore.GUI; + +public class DebugHUD +{ + private SpriteFont _spriteFont; + private Dictionary _text = new(); + private List _log = new(); + + public void Initialize() + { + } + + public void LoadContent() + { + _spriteFont = AppManager.Instance.Content.Load("Fonts\\Font2"); + } + + public void Update(GameTime gameTime) + { + } + + public void Draw(SpriteBatch spriteBatch) + { + var keysString = Join("\n", _text.Select(el => el.Key + ": " + el.Value).ToList()); + spriteBatch.Begin(); + spriteBatch.DrawString( + _spriteFont, + keysString, + new Vector2(10, 10), + Color.Cyan, + 0, + Vector2.Zero, + 1, + SpriteEffects.None, + 0 + ); + spriteBatch.DrawString( + _spriteFont, + Join("\n", _log), + new Vector2(10, 10 + _spriteFont.MeasureString(keysString).Y), + Color.Green, + 0, + Vector2.Zero, + 1, + SpriteEffects.None, + 0 + ); + spriteBatch.End(); + } + + public void Set(string key, string value) + { + _text[key] = value; + } + + public void Log(string value) + { + _log.Add(value); + if (_log.Count > 30) + { + _log.RemoveAt(0); + } + } +} \ No newline at end of file diff --git a/ZoFo/GameCore/GUI/GameEndedGUI.cs b/ZoFo/GameCore/GUI/GameEndedGUI.cs new file mode 100644 index 0000000..03897ea --- /dev/null +++ b/ZoFo/GameCore/GUI/GameEndedGUI.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Xml; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Content; +using Microsoft.Xna.Framework.Graphics; +using Microsoft.Xna.Framework.Input; +using MonogameLibrary.UI.Base; +using MonogameLibrary.UI.Elements; + +namespace ZoFo.GameCore.GUI; + +public class GameEndedGUI : AbstractGUI +{ + protected override void CreateUI() + { + // int width = AppManager.Instance.inGameHUDHelperResolution.X; + // int height = AppManager.Instance.inGameHUDHelperResolution.Y; + } + + public override void Update(GameTime gameTime) + { + + } +} \ No newline at end of file diff --git a/ZoFo/GameCore/GUI/HUD.cs b/ZoFo/GameCore/GUI/HUD.cs new file mode 100644 index 0000000..c20ead1 --- /dev/null +++ b/ZoFo/GameCore/GUI/HUD.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Xml; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Content; +using Microsoft.Xna.Framework.Graphics; +using Microsoft.Xna.Framework.Input; +using MonogameLibrary.UI.Base; +using MonogameLibrary.UI.Elements; + +namespace ZoFo.GameCore.GUI; + +public class HUD +{ + protected UIManager Manager = new(); + protected List Elements = new(); + private List ActiveElements; + protected DrawableUIElement SelectedElement; + private bool isStartedPrint = false; + private bool isPressed = false; + + private GraphicsDevice graphicsDevice; + public virtual void Initialize() + { + + } + + public virtual void LoadContent() + { + + } + + public virtual void Update(GameTime gameTime) + { + + } + + public virtual void Draw(SpriteBatch spriteBatch) + { + Manager.Draw(spriteBatch); + } +} \ No newline at end of file diff --git a/ZoFo/GameCore/GUI/InventoryGUI.cs b/ZoFo/GameCore/GUI/InventoryGUI.cs new file mode 100644 index 0000000..c085803 --- /dev/null +++ b/ZoFo/GameCore/GUI/InventoryGUI.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Xml; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Content; +using Microsoft.Xna.Framework.Graphics; +using Microsoft.Xna.Framework.Input; +using MonogameLibrary.UI.Base; +using MonogameLibrary.UI.Elements; + +namespace ZoFo.GameCore.GUI; + +public class InventoryGUI : AbstractGUI +{ + protected override void CreateUI() + { + // int width = AppManager.Instance.inGameHUDHelperResolution.X; + // int height = AppManager.Instance.inGameHUDHelperResolution.Y; + } + + public override void Update(GameTime gameTime) + { + + } +} \ No newline at end of file diff --git a/ZoFo/GameCore/GUI/MainMenuGUI.cs b/ZoFo/GameCore/GUI/MainMenuGUI.cs new file mode 100644 index 0000000..45c3e65 --- /dev/null +++ b/ZoFo/GameCore/GUI/MainMenuGUI.cs @@ -0,0 +1,81 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Xml; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Content; +using Microsoft.Xna.Framework.Graphics; +using Microsoft.Xna.Framework.Input; +using MonogameLibrary.UI.Base; +using MonogameLibrary.UI.Elements; +using ZoFo.GameCore.GameManagers; + +namespace ZoFo.GameCore.GUI; + +public class MainMenuGUI : AbstractGUI +{ + private DrawableUIElement menuBackground; + protected override void CreateUI() + { + int width = AppManager.Instance.CurentScreenResolution.X; + int height = AppManager.Instance.CurentScreenResolution.Y; + + menuBackground = new DrawableUIElement(Manager) { rectangle = new Rectangle(0, 0, width, height), mainColor = Color.White, textureName = "Textures\\GUI\\MenuBackground" }; + Elements.Add(menuBackground); + menuBackground.LoadTexture(AppManager.Instance.Content); + + Elements.Add(new Label(Manager) { rectangle = new Rectangle(width / 2 - (int)(width / 8), height / 5, (int)(width / 4), (int)(height / 20)), text = "ZoFo", fontColor = Color.White, mainColor = Color.Transparent, scale = 0.9f, fontName = "Fonts\\Font"}); + + + Button playButton = new Button(Manager) + { + rectangle = new Rectangle(width / 2 - (int)(width / 10), height / 3 + height / 20 + height / 40, (int)(width / 5), (int)(height / 20)), + text = "Play", + scale = 0.2f, + fontColor = Color.White, + mainColor = Color.Gray, + fontName = "Fonts\\Font" + }; + playButton.LeftButtonPressed += () => + { + + }; + Elements.Add(playButton); + Button optionButton = new Button(Manager) + { + rectangle = new Rectangle(width / 2 - (int)(width / 10), height / 3 + (height / 20 + height / 40) * 2, (int)(width / 5), (int)(height / 20)), + text = "Options", + scale = 0.2f, + fontColor = Color.White, + mainColor = Color.Gray, + fontName = "Fonts\\Font" + }; + optionButton.LeftButtonPressed += () => + { + AppManager.Instance.SetGUI(new OptionsGUI()); + }; + Elements.Add(optionButton); + Button exitButton = new Button(Manager) + { + rectangle = new Rectangle(width / 2 - (int)(width / 10), height / 3 + (height / 20 + height / 40) * 3, (int)(width / 5), (int)(height / 20)), + text = "Exit", + scale = 0.2f, + fontColor = Color.White, + mainColor = Color.Gray, + fontName = "Fonts\\Font" + }; + exitButton.LeftButtonPressed += () => + { + AppManager.Instance.Exit(); + }; + Elements.Add(exitButton); + + + } + + public override void Update(GameTime gameTime) + { + base.Update(gameTime); + } +} \ No newline at end of file diff --git a/ZoFo/GameCore/GUI/OptionsGUI.cs b/ZoFo/GameCore/GUI/OptionsGUI.cs new file mode 100644 index 0000000..11f8c5e --- /dev/null +++ b/ZoFo/GameCore/GUI/OptionsGUI.cs @@ -0,0 +1,104 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Xml; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Content; +using Microsoft.Xna.Framework.Graphics; +using Microsoft.Xna.Framework.Input; +using MonogameLibrary.UI.Base; +using MonogameLibrary.UI.Elements; +using ZoFo.GameCore.GameManagers; + +namespace ZoFo.GameCore.GUI; + +public class OptionsGUI : AbstractGUI +{ + private DrawableUIElement menuBackground; + protected override void CreateUI() + { + int width = AppManager.Instance.CurentScreenResolution.X; + int height = AppManager.Instance.CurentScreenResolution.Y; + + menuBackground = new DrawableUIElement(Manager) { rectangle = new Rectangle(0, 0, width, height), mainColor = Color.White, textureName = "Textures\\GUI\\MenuBackground" }; + Elements.Add(menuBackground); + menuBackground.LoadTexture(AppManager.Instance.Content); + + Elements.Add(new Label(Manager) { rectangle = new Rectangle(width / 2 - (int)(width / 8), height / 5, (int)(width / 4), (int)(height / 20)), text = "Options", fontColor = Color.White, mainColor = Color.Transparent, scale = 0.9f, fontName = "Fonts\\Font"}); + + + + Label label_OverallVolume = new Label(Manager) + { fontName = "Fonts\\Font", scale = 0.2f, text = "All Volume", fontColor = Color.White, rectangle = new Rectangle(width / 3, height / 3, 50, 50), mainColor = Color.Transparent, textAligment = MonogameLibrary.UI.Enums.TextAligment.Left }; + Elements.Add(label_OverallVolume); + + var slider_OverallVolume = new Slider(Manager) + { rectangle = new Rectangle(width / 2, height / 3, width / 10, height / 20), indentation = 4, textureName = "Textures\\GUI\\checkbox_on", MinValue = 0, MaxValue = 1 }; + slider_OverallVolume.SliderChanged += (newVal) => + { + + }; + Elements.Add(slider_OverallVolume); + + Label label_MusicVolume = new Label(Manager) + { fontName = "Fonts\\Font", scale = 0.2f, text = "Music Volume", fontColor = Color.White, rectangle = new Rectangle(width / 3, height / 3 + (height / 20 + height / 40) * 1, 50, 50), mainColor = Color.Transparent, textAligment = MonogameLibrary.UI.Enums.TextAligment.Left }; + Elements.Add(label_MusicVolume); + + var slider_MusicVolume = new Slider(Manager) + { rectangle = new Rectangle(width / 2, height / 3 + (height / 20 + height / 40) * 1, width / 10, height / 20), indentation = 4, textureName = "Textures\\GUI\\checkboxs_on", MinValue = 0, MaxValue = 1 }; + slider_MusicVolume.SliderChanged += (newVal) => + { + + }; + Elements.Add(slider_MusicVolume); + + + Label label_EffectsVolume = new Label(Manager) + { fontName = "Fonts\\Font", scale = 0.2f, text = "Effects Volume", fontColor = Color.White, rectangle = new Rectangle(width / 3, height / 3 + (height / 20 + height / 40) * 2, 50, 50), mainColor = Color.Transparent, textAligment = MonogameLibrary.UI.Enums.TextAligment.Left }; + Elements.Add(label_EffectsVolume); + + var slider_EffectsVolume = new Slider(Manager) + { rectangle = new Rectangle(width / 2, height / 3 + (height / 20 + height / 40) * 2, width / 10, height / 20), indentation = 4, textureName = "Textures\\GUI\\checkboxs_on", MinValue = 0, MaxValue = 1 }; + slider_EffectsVolume.SliderChanged += (newVal) => + { + + }; + Elements.Add(slider_EffectsVolume); + + Label lblSwitchMode = new Label(Manager) + { fontName = "Fonts\\Font", scale = 0.2f, text = "Left/Right Mode", fontColor = Color.White, rectangle = new Rectangle(width / 3, height / 3 + (height / 20 + height / 40) * 3, 50, 50), mainColor = Color.Transparent}; + Elements.Add(lblSwitchMode); + + //var button_left_right_mode = new CheckBox(Manager) { rectangle = new Rectangle(rightBorder - checkboxlength, lblSwitchMode.rectangle.Y - 12, checkboxlength, checkboxlength) }; + //button_left_right_mode.Checked += (newCheckState) => { }; + //Elements.Add(button_left_right_mode); + + + Label label_IsFullScreen = new Label(Manager) + { fontName = "Fonts\\Font", scale = 0.2f, text = "Full Screen", fontColor = Color.White, rectangle = new Rectangle(width / 3, height / 3 + (height / 20 + height / 40) * 4, 50, 50), mainColor = Color.Transparent}; + Elements.Add(label_IsFullScreen); + + var button_FullScreen = new CheckBox(Manager) { rectangle = new Rectangle(width / 2, height / 3 + (height / 20 + height / 40) * 4, width / 30, width / 30) }; + button_FullScreen.Checked += (newCheckState) => + { + + }; + Elements.Add(button_FullScreen); + + + Button bTExit = new Button(Manager) + { fontName = "Fonts\\Font", scale = 0.2f, text = "<-", rectangle = new Rectangle(width / 30, height / 30, 40, 40), textureName = "Textures\\GUI\\checkboxs_off" }; + Elements.Add(bTExit); + bTExit.LeftButtonPressed += () => + { + + }; + + } + + public override void Update(GameTime gameTime) + { + base.Update(gameTime); + } +} \ No newline at end of file diff --git a/ZoFo/GameCore/GUI/SelectModeMenu.cs b/ZoFo/GameCore/GUI/SelectModeMenu.cs new file mode 100644 index 0000000..b08e782 --- /dev/null +++ b/ZoFo/GameCore/GUI/SelectModeMenu.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Xml; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Content; +using Microsoft.Xna.Framework.Graphics; +using Microsoft.Xna.Framework.Input; +using MonogameLibrary.UI.Base; +using MonogameLibrary.UI.Elements; + +namespace ZoFo.GameCore.GUI; + +public class SelectModeMenu : AbstractGUI +{ + protected override void CreateUI() + { + // int width = AppManager.Instance.inGameHUDHelperResolution.X; + // int height = AppManager.Instance.inGameHUDHelperResolution.Y; + } + + public override void Update(GameTime gameTime) + { + + } +} \ No newline at end of file diff --git a/ZoFo/GameCore/GUI/SelectingServerGUI.cs b/ZoFo/GameCore/GUI/SelectingServerGUI.cs new file mode 100644 index 0000000..0a7f049 --- /dev/null +++ b/ZoFo/GameCore/GUI/SelectingServerGUI.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Xml; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Content; +using Microsoft.Xna.Framework.Graphics; +using Microsoft.Xna.Framework.Input; +using MonogameLibrary.UI.Base; +using MonogameLibrary.UI.Elements; + +namespace ZoFo.GameCore.GUI; + +public class SelectingServerGUI : AbstractGUI +{ + protected override void CreateUI() + { + // int width = AppManager.Instance.inGameHUDHelperResolution.X; + // int height = AppManager.Instance.inGameHUDHelperResolution.Y; + } + + public override void Update(GameTime gameTime) + { + + } +} \ No newline at end of file diff --git a/ZoFo/GameCore/GUI/WaitingForPlayersGUI.cs b/ZoFo/GameCore/GUI/WaitingForPlayersGUI.cs new file mode 100644 index 0000000..893efc6 --- /dev/null +++ b/ZoFo/GameCore/GUI/WaitingForPlayersGUI.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Xml; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Content; +using Microsoft.Xna.Framework.Graphics; +using Microsoft.Xna.Framework.Input; +using MonogameLibrary.UI.Base; +using MonogameLibrary.UI.Elements; + +namespace ZoFo.GameCore.GUI; + +public class WaitingForPlayersGUI : AbstractGUI +{ + protected override void CreateUI() + { + // int width = AppManager.Instance.inGameHUDHelperResolution.X; + // int height = AppManager.Instance.inGameHUDHelperResolution.Y; + } + + public override void Update(GameTime gameTime) + { + + } +} \ No newline at end of file diff --git a/ZoFo/GameCore/GameManagers/AppManager.cs b/ZoFo/GameCore/GameManagers/AppManager.cs new file mode 100644 index 0000000..3be4402 --- /dev/null +++ b/ZoFo/GameCore/GameManagers/AppManager.cs @@ -0,0 +1,162 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection.Metadata; +using System.Text; +using System.Threading.Tasks; +using DangerousD.GameCore.Graphics; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using Microsoft.Xna.Framework.Input; +using ZoFo.GameCore.GameManagers.ItemManager; +using ZoFo.GameCore.GUI; +using static System.Collections.Specialized.BitVector32; +using MonogameLibrary.UI.Base; + +namespace ZoFo.GameCore.GameManagers +{ + public enum GameState { NotPlaying, HostPlaying, ClientPlaying } + public class AppManager : Game + { + private GraphicsDeviceManager _graphics; + private SpriteBatch _spriteBatch; + + + + public static AppManager Instance { get; private set; } + public GameState gamestate; + public AbstractGUI currentGUI; + public DebugHUD debugHud; + public Point CurentScreenResolution = new Point(1920, 1080); + public Client client; + public Server server; + + + #region Managers + + public InputManager InputManager; + public ItemManager.ItemManager ItemManager; + + public AnimationBuilder animationBuilder{get;set; } + + #endregion + + public AppManager() + { + _graphics = new GraphicsDeviceManager(this); + SetResolution(CurentScreenResolution.X, CurentScreenResolution.Y); + FulscrreenSwitch(); + + + Content.RootDirectory = "Content"; + IsMouseVisible = true; + + Instance = this; + InputManager = new InputManager(); + + + + currentGUI = new MainMenuGUI(); + debugHud = new DebugHUD(); + + } + + protected override void Initialize() + { + currentGUI.Initialize(); + debugHud.Initialize(); + + + + base.Initialize(); + } + + protected override void LoadContent() + { + _spriteBatch = new SpriteBatch(GraphicsDevice); + debugHud.LoadContent(); + currentGUI.LoadContent(); + + + + } + + protected override void Update(GameTime gameTime) + { + if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || + Keyboard.GetState().IsKeyDown(Keys.Escape)) + Exit(); + + debugHud.Set("key", "value"); + + InputManager.Update(); + currentGUI.Update(gameTime); + switch (gamestate) + { + case GameState.NotPlaying: + break; + case GameState.HostPlaying: + server.Update(gameTime); + client.Update(gameTime); + break; + case GameState.ClientPlaying: + server.Update(gameTime); + break; + default: + break; + } + + base.Update(gameTime); + } + + protected override void Draw(GameTime gameTime) + { + GraphicsDevice.Clear(Color.CornflowerBlue); + + + + debugHud.Draw(_spriteBatch); + currentGUI.Draw(_spriteBatch); + switch (gamestate) + { + case GameState.ClientPlaying: + case GameState.HostPlaying: + client.Draw(_spriteBatch); + break; + case GameState.NotPlaying: + default: + break; + } + + base.Draw(gameTime); + } + public void ChangeState(GameState gameState) + { + this.gamestate = gameState; + } + public void SetGUI(AbstractGUI gui) + { + currentGUI = gui; + currentGUI.Initialize(); + currentGUI.LoadContent(); + + //TODO + } + + public void GameEnded(Dictionary lootIGot) + { + //TODO + } + + public void SetResolution(int x, int y) + { + _graphics.PreferredBackBufferWidth = x; + _graphics.PreferredBackBufferHeight = y; + } + + public void FulscrreenSwitch() + { + _graphics.IsFullScreen = !_graphics.IsFullScreen; + } + } +} diff --git a/ZoFo/GameCore/GameManagers/CollisionManager/CollisionComponent.cs b/ZoFo/GameCore/GameManagers/CollisionManager/CollisionComponent.cs new file mode 100644 index 0000000..0ba9816 --- /dev/null +++ b/ZoFo/GameCore/GameManagers/CollisionManager/CollisionComponent.cs @@ -0,0 +1,58 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Linq; +using System.Reflection.Metadata; +using System.Text; +using System.Threading.Tasks; +using ZoFo.GameCore.GameObjects.Entities.LivingEntities.Player; + +namespace ZoFo.GameCore.GameManagers.CollisionManager +{ + public class CollisionComponent + { + //поля + public Rectangle Bounds { get; set; } + + //остановлен ли перс + bool doesStop; + Rectangle stopRectangle; + + // triggers for rectangle + bool isTrigger; + Rectangle triggerRectangle; + + //delegate + public delegate void EventHandler(object sender, EventArgs e); + + public CollisionComponent(int x, int y, int width, int height) + { + Bounds = new Rectangle(x, y, width, height); + } + + + //events + public event EventHandler OnTriggerEnter; + public event EventHandler OnTriggerZone; + public event EventHandler OnTriggerExit; + + // methods-event + public void TriggerEnter(object component, Player player, + EventArgs e) + { + + } + public void TriggerZone(object component,Player player, + EventArgs e) + { + + } + public void TriggerExit(object component,Player player, + EventArgs e) + { + + } + + + } +} diff --git a/ZoFo/GameCore/GameManagers/CollisionManager/CollisionManager.cs b/ZoFo/GameCore/GameManagers/CollisionManager/CollisionManager.cs new file mode 100644 index 0000000..8cf63f2 --- /dev/null +++ b/ZoFo/GameCore/GameManagers/CollisionManager/CollisionManager.cs @@ -0,0 +1,57 @@ +using Microsoft.VisualBasic; +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using ZoFo.GameCore.GameObjects; +using ZoFo.GameCore.GameManagers.CollisionManager; +using Microsoft.Xna.Framework; +using ZoFo.GameCore.GameManagers.MapManager.MapElements; + +namespace ZoFo.GameCore.GameManagers.CollisionManager +{ + public class CollisionManager + { + public List CollisionComponent; + public List TriggerComponent; + + + + public static bool CheckComponentCollision(List collisionComponents, CollisionComponent component) + { + foreach (var collisionComponent in collisionComponents) + { + if (component.Bounds.IntersectsWith(collisionComponent.Bounds)) + { + return true; + } + } + + return false; + } + + public void UpdateComponentCollision(List collisionComponents) + { + + } + + public void UpdatePositions() + { + + } + + //public void GetObjectInArea(Rectangle area) + //{ + + //} + + //public void Register(Rectangle rectangle) + //{ + + //} + + + } +} diff --git a/ZoFo/GameCore/GameManagers/InputManager.cs b/ZoFo/GameCore/GameManagers/InputManager.cs new file mode 100644 index 0000000..642aefc --- /dev/null +++ b/ZoFo/GameCore/GameManagers/InputManager.cs @@ -0,0 +1,229 @@ +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Input; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ZoFo.GameCore.GameManagers +{ + public enum ScopeState { Up, Middle, Down } + public enum ControlsState { Gamepad, Keyboard } + public class InputManager + { + public delegate void Delegat(); + public event Delegat MovEventJump; + public event Delegat MovEventDown; + public event Delegat ShootEvent; + + Vector2 vectorMovementDirection; + ScopeState scopeState; // Положение оружия. Up, Middle, Down. + ControlsState controlsState; + private bool _overrideControls = false; + private bool _cheatsEnabled = false; + public bool InvincibilityCheat { get; private set; } = false; + public bool CollisionsCheat { get; private set; } = false; + public bool InfiniteAmmoCheat { get; private set; } = false; + + private bool isJumpDown; // Блокирует физическое нажатие прыжка и спуска + private bool isShoot; + + private KeyboardState lastKeyboardState; + private GamePadState lastGamePadState; + + + public Vector2 VectorMovementDirection { get => vectorMovementDirection; } + public ScopeState ScopeState { get => scopeState; } + public string currentControlsState; + + public InputManager() + { + this.isJumpDown = false; + this.isShoot = false; + scopeState = ScopeState.Middle; + controlsState = ControlsState.Keyboard; + vectorMovementDirection = new Vector2(0, 0); + } + public void Update() + { + if (_cheatsEnabled) + { + //AppManager.Instance.DebugHUD.Set("cheats", _cheatsEnabled.ToString()); + //AppManager.Instance.DebugHUD.Set("invincible", InvincibilityCheat.ToString()); + //AppManager.Instance.DebugHUD.Set("infinite ammo", InfiniteAmmoCheat.ToString()); //TODO + } + + #region Работа с GamePad + if (_overrideControls ? controlsState == ControlsState.Gamepad : GamePad.GetState(0).IsConnected) + { + controlsState = ControlsState.Gamepad; + + #region Обработка гейм-пада. Задает Vector2 vectorMovementDirection являющийся вектором отклонения левого стика. + GamePadState gamePadState = GamePad.GetState(0); + vectorMovementDirection = gamePadState.ThumbSticks.Left; + #endregion + + #region читы + if (gamePadState.Triggers.Left >= 0.9 && gamePadState.Triggers.Right >= 0.9) + _cheatsEnabled = true; + if (_cheatsEnabled) + { + if (gamePadState.Buttons.Y == ButtonState.Pressed && lastGamePadState.Buttons.Y == ButtonState.Released) + InvincibilityCheat = !InvincibilityCheat; + if (gamePadState.Buttons.B == ButtonState.Pressed && lastGamePadState.Buttons.B == ButtonState.Released) + CollisionsCheat = !CollisionsCheat; + //TODO: infinite ammo cheat by gamepad + } + #endregion // Cheats + + #region Обработка нажатия прыжка и спуска. Вызывает события MovEvent. + if (vectorMovementDirection.Y < -0.2 && gamePadState.Buttons.A == ButtonState.Pressed && !isJumpDown) + { + isJumpDown = true; + MovEventDown?.Invoke(); + Debug.WriteLine("Спуск"); + } + else if (gamePadState.Buttons.A == ButtonState.Pressed && lastGamePadState.Buttons.A == ButtonState.Released) + { + MovEventJump?.Invoke(); + Debug.WriteLine("Прыжок"); + } + #endregion + + #region Обработка положения оружия. Задает значение полю scopeState. + if (vectorMovementDirection.Y >= 0.7) + { + scopeState = ScopeState.Up; + } + else if (vectorMovementDirection.Y <= -0.7 && !isJumpDown) + { + scopeState = ScopeState.Down; + } + else + { + scopeState = ScopeState.Middle; + } + #endregion + + #region Обработка нажатия выстрела. Вызывает событие ShootEvent + if (gamePadState.Buttons.X == ButtonState.Pressed && !isJumpDown && !isShoot) + { + isShoot = true; + ShootEvent?.Invoke(); + Debug.WriteLine("Выстрел"); + } + else if (gamePadState.Buttons.X == ButtonState.Released && !isJumpDown) + { + isShoot = false; + } + #endregion + + lastGamePadState = gamePadState; + } + #endregion + #region Работа с KeyBoard + else + { + controlsState = ControlsState.Keyboard; + + #region Состояние клавиатуры + KeyboardState keyBoardState = Keyboard.GetState(); // Состояние клавиатуры + #endregion + + #region читы + if (keyBoardState.IsKeyDown(Keys.LeftShift) && keyBoardState.IsKeyDown(Keys.RightShift)) + _cheatsEnabled = true; + if (_cheatsEnabled) + { + if (keyBoardState.IsKeyDown(Keys.I) && lastKeyboardState.IsKeyUp(Keys.I)) + InvincibilityCheat = !InvincibilityCheat; + if (keyBoardState.IsKeyDown(Keys.C) && lastKeyboardState.IsKeyUp(Keys.C)) + CollisionsCheat = !CollisionsCheat; + if (keyBoardState.IsKeyDown(Keys.N) && lastKeyboardState.IsKeyUp(Keys.N)) + InfiniteAmmoCheat = !InfiniteAmmoCheat; + + List lvls = new List() { Keys.D0, Keys.D1, Keys.D2, Keys.D3, Keys.D4, Keys.D5, Keys.D6, Keys.D7, Keys.D8, Keys.D9 }; + + for (int i = 0; i < lvls.Count; i++) + { + //if (keyBoardState.IsKeyDown(lvls[i]) && lastKeyboardState.IsKeyUp(lvls[i])) //TODO + // AppManager.Instance.Restart($"lvl{i}"); + } + } + #endregion // Cheats + + #region Обработка движения вправо-влево. Меняет у вектора vectorMovementDirection значение X на -1/0/1. + if (keyBoardState.IsKeyDown(Keys.Left)) + { + vectorMovementDirection.X = -1; + } + else if (keyBoardState.IsKeyDown(Keys.Right)) + { + vectorMovementDirection.X = 1; + } + else + { + vectorMovementDirection.X = 0; + } + #endregion + + #region Обработка прыжка и спуска. Вызываются события MovEvent. + if (keyBoardState.IsKeyDown(Keys.LeftShift) && !isJumpDown && keyBoardState.IsKeyDown(Keys.Down)) + { + isJumpDown = true; + MovEventDown?.Invoke(); + Debug.WriteLine("Спуск"); + } + else if (keyBoardState.IsKeyDown(Keys.LeftShift) && !isJumpDown) + { + isJumpDown = true; + MovEventJump?.Invoke(); + Debug.WriteLine("Прыжок"); + } + else if (keyBoardState.IsKeyUp(Keys.LeftShift)) + { + isJumpDown = false; + } + #endregion + + #region Обработка положения оружия. Задает значение полю scopeState. + if (keyBoardState.IsKeyDown(Keys.Up)) + { + scopeState = ScopeState.Up; + } + else if (keyBoardState.IsKeyDown(Keys.Down) && !isJumpDown) + { + scopeState = ScopeState.Down; + } + else + { + scopeState = ScopeState.Middle; + } + #endregion + + #region Обработка нажатия выстрела. Вызывает событие ShootEvent + if (keyBoardState.IsKeyDown(Keys.X) && !isJumpDown && !isShoot) + { + isShoot = true; + ShootEvent?.Invoke(); + Debug.WriteLine("Выстрел"); + } + else if (keyBoardState.IsKeyUp(Keys.X) && !isJumpDown) + { + isShoot = false; + } + #endregion + + SetState(ControlsState.Keyboard); + lastKeyboardState = keyBoardState; + } + #endregion + } + public void SetState(ControlsState controlsState) + { + currentControlsState = controlsState.ToString(); + } + } +} diff --git a/ZoFo/GameCore/GameManagers/ItemManager/EquippableItemInfo.cs b/ZoFo/GameCore/GameManagers/ItemManager/EquippableItemInfo.cs new file mode 100644 index 0000000..5bffce5 --- /dev/null +++ b/ZoFo/GameCore/GameManagers/ItemManager/EquippableItemInfo.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ZoFo.GameCore.GameManagers.ItemManager +{ + class EquippableItemInfo : ItemInfo + { + bool IsEquiped; //экипирован ли предмет + public EquippableItemInfo(string tag) : base(tag) + { + + } + } +} diff --git a/ZoFo/GameCore/GameManagers/ItemManager/ItemInfo.cs b/ZoFo/GameCore/GameManagers/ItemManager/ItemInfo.cs new file mode 100644 index 0000000..375d745 --- /dev/null +++ b/ZoFo/GameCore/GameManagers/ItemManager/ItemInfo.cs @@ -0,0 +1,37 @@ +using Microsoft.Xna.Framework.Graphics; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ZoFo.GameCore.GameManagers.ItemManager +{ + class ItemInfo + { + //поля + string tag; + string textureName; + Texture2D itemTexture; + bool isCraftable; + Dictionary resourcesNeededToCraft; + public ItemInfo (string tag) + { + this.tag = tag; + } + public ItemInfo(string tag,string textureName,bool isCraftable, Dictionary resourcesNeededToCraft) + { + this.tag = tag; + this.textureName = textureName; + + this.isCraftable = isCraftable; + this.resourcesNeededToCraft = resourcesNeededToCraft; + } + //методы + public void LoadTexture() + { + //я что-то хз как это + itemTexture=AppManager.Instance.Content.Load(textureName); + } + } +} diff --git a/ZoFo/GameCore/GameManagers/ItemManager/ItemManager.cs b/ZoFo/GameCore/GameManagers/ItemManager/ItemManager.cs new file mode 100644 index 0000000..6d00e0c --- /dev/null +++ b/ZoFo/GameCore/GameManagers/ItemManager/ItemManager.cs @@ -0,0 +1,33 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ZoFo.GameCore.GameManagers.ItemManager +{ + public class ItemManager + { + //поля + Dictionary tagItemPairs; + //методы + ItemInfo GetItemInfo(string tag) + { + return tagItemPairs.GetValueOrDefault(tag); + } + void LoadItemTextures() + { + foreach (var item in tagItemPairs) + { + item.Value.LoadTexture(); + } + } + void Initialize() + { + tagItemPairs.Add("wood", new ItemInfo("wood","wood",false,null)); + tagItemPairs.Add("rock", new ItemInfo("rock", "rock", false, null)); + tagItemPairs.Add("steel", new ItemInfo("steel", "steel", false, null)); + } + + } +} diff --git a/ZoFo/GameCore/GameManagers/ItemManager/PlayerData.cs b/ZoFo/GameCore/GameManagers/ItemManager/PlayerData.cs new file mode 100644 index 0000000..1dfc351 --- /dev/null +++ b/ZoFo/GameCore/GameManagers/ItemManager/PlayerData.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ZoFo.GameCore.GameManagers.ItemManager +{ + /// + /// Класс хранит информацю о количестве ресурсов у игрока + /// + internal class PlayerData + { + Dictionary items; + /// + /// Принимает тэг и крафтит этот объект + /// + /// + public void CraftItem(string itemTag) + { + //TODO + } + } +} diff --git a/ZoFo/GameCore/GameManagers/ItemManager/WeaponItemInfo.cs b/ZoFo/GameCore/GameManagers/ItemManager/WeaponItemInfo.cs new file mode 100644 index 0000000..3917575 --- /dev/null +++ b/ZoFo/GameCore/GameManagers/ItemManager/WeaponItemInfo.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ZoFo.GameCore.GameManagers.ItemManager +{ + class WeaponItemInfo: EquippableItemInfo + { + //поля + float damage; + + public WeaponItemInfo(string tag) : base(tag) + { + } + } +} diff --git a/ZoFo/GameCore/GameManagers/MapManager/MapElements/Chunk.cs b/ZoFo/GameCore/GameManagers/MapManager/MapElements/Chunk.cs new file mode 100644 index 0000000..6337d3c --- /dev/null +++ b/ZoFo/GameCore/GameManagers/MapManager/MapElements/Chunk.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ZoFo.GameCore.GameManagers.MapManager.MapElements +{ + public class Chunk + { + public int[] Data { get; set; } + public int Height { get; set; } + public int Width { get; set; } + public int X { get; set; } + public int Y { get; set; } + } +} diff --git a/ZoFo/GameCore/GameManagers/MapManager/MapElements/Layer.cs b/ZoFo/GameCore/GameManagers/MapManager/MapElements/Layer.cs new file mode 100644 index 0000000..f598efe --- /dev/null +++ b/ZoFo/GameCore/GameManagers/MapManager/MapElements/Layer.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ZoFo.GameCore.GameManagers.MapManager.MapElements +{ + public class Layer + { + public List Chunks { get; set; } + public int Height { get; set; } + public int Width { get; set; } + public int Id { get; set; } + public bool Visibility { get; set; } + } +} diff --git a/ZoFo/GameCore/GameManagers/MapManager/MapElements/TileMap.cs b/ZoFo/GameCore/GameManagers/MapManager/MapElements/TileMap.cs new file mode 100644 index 0000000..6c7e958 --- /dev/null +++ b/ZoFo/GameCore/GameManagers/MapManager/MapElements/TileMap.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ZoFo.GameCore.GameManagers.MapManager.MapElements +{ + public class TileMap + { + public bool Infinite { get; set; } + public int TileHeight { get; set; } + public int TileWidth { get; set; } + public List TileSets { get; set; } + public List Layers { get; set; } + } +} diff --git a/ZoFo/GameCore/GameManagers/MapManager/MapElements/TileSet.cs b/ZoFo/GameCore/GameManagers/MapManager/MapElements/TileSet.cs new file mode 100644 index 0000000..61eddce --- /dev/null +++ b/ZoFo/GameCore/GameManagers/MapManager/MapElements/TileSet.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ZoFo.GameCore.GameManagers.MapManager.MapElements +{ + public class TileSet + { + public string Image { get; set; } + public string Name { get; set; } + public int ImageHeight { get; set; } + public int ImageWidth { get; set; } + public int Margin { get; set; } + public int Spacing { get; set; } + public int TileCount { get; set; } + public int TileHeight { get; set; } + public int TileWidth { get; set; } + public int Columns { get; set; } + public int FirstGid { get; set; } + } +} diff --git a/ZoFo/GameCore/GameManagers/MapManager/MapElements/TileSetInfo.cs b/ZoFo/GameCore/GameManagers/MapManager/MapElements/TileSetInfo.cs new file mode 100644 index 0000000..f53d448 --- /dev/null +++ b/ZoFo/GameCore/GameManagers/MapManager/MapElements/TileSetInfo.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ZoFo.GameCore.GameManagers.MapManager.MapElements +{ + public class TileSetInfo + { + public int FirstGid { get; set; } + public string Source { get; set; } + } +} diff --git a/ZoFo/GameCore/GameManagers/MapManager/MapManager.cs b/ZoFo/GameCore/GameManagers/MapManager/MapManager.cs new file mode 100644 index 0000000..74f559e --- /dev/null +++ b/ZoFo/GameCore/GameManagers/MapManager/MapManager.cs @@ -0,0 +1,72 @@ +using Microsoft.Xna.Framework; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +using ZoFo.GameCore.GameManagers.MapManager.MapElements; + +namespace ZoFo.GameCore.GameManagers.MapManager +{ + public class MapManager + { + private static readonly string _path = "/{0}.tmj"; + private List _tileSets = new List(); + + public void LoadMap(string mapName = "main") + { + TileMap tileMap; + using (StreamReader reader = new StreamReader(string.Format(_path, mapName))) + { + string data = reader.ReadToEnd(); + tileMap = JsonSerializer.Deserialize(data); + } + + List tileSets = new List(); + foreach (TileSetInfo tileSetInfo in tileMap.TileSets) + { + TileSet tileSet = LoadTileSet(tileSetInfo.Source); + tileSet.FirstGid = tileSetInfo.FirstGid; + tileSets.Add(tileSet); + } + + foreach (var chunk in tileMap.Layers[0].Chunks) + { + int i = 0; + foreach (var id in chunk.Data) + { + foreach (var tileSet in tileSets) + { + if (tileSet.FirstGid - id < 0) + { + int number = id - tileSet.FirstGid; + + int relativeColumn = number % tileSet.Columns * tileSet.TileWidth; + int relativeRow = number / tileSet.Columns * tileSet.TileHeight; + + Rectangle sourceRectangle = new Rectangle(relativeColumn * tileSet.TileWidth, relativeRow * tileSet.TileHeight, + relativeColumn * tileSet.TileWidth + tileSet.TileWidth, relativeRow * tileSet.TileHeight + tileSet.TileHeight); + + Vector2 position = new Vector2(i % chunk.Width, i / chunk.Height); + } + } + i++; + } + } + + } + + private TileSet LoadTileSet(string path) + { + using (StreamReader reader = new StreamReader(path)) + { + string data = reader.ReadToEnd(); + return JsonSerializer.Deserialize(data); + } + } + + } +} diff --git a/ZoFo/GameCore/GameManagers/NetworkManager/ClientNetworkManager.cs b/ZoFo/GameCore/GameManagers/NetworkManager/ClientNetworkManager.cs new file mode 100644 index 0000000..ea57f60 --- /dev/null +++ b/ZoFo/GameCore/GameManagers/NetworkManager/ClientNetworkManager.cs @@ -0,0 +1,85 @@ +using System; +using System.Collections.Generic; +using System.Data.SqlTypes; +using System.Net; +using System.Net.Sockets; +using System.Security.Cryptography.X509Certificates; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using ZoFo.GameCore.GameManagers.NetworkManager.Updates; + + +namespace ZoFo.GameCore.GameManagers.NetworkManager +{ + public class ClientNetworkManager + { + private int port = 7632; + private EndPoint endPoint; + private Socket socket; + List updates = new List(); + public delegate void OnDataSent(string Data); + public event OnDataSent GetDataSent; // event + public void Init() //create endPoint, socket + { + socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + } + + public void SendData() + { + while(socket.Connected) + { + byte[] bytes = Encoding.UTF8.GetBytes(updates.ToString()); + socket.Send(bytes); + } + } + + public void StopConnection() + { + socket.Shutdown(SocketShutdown.Both); + socket.Close(); + } + + /// + /// приложение пытается подключиться к комнате + /// + /// + /// + public void JoinRoom(string ip) // multyplayer + { + endPoint = new IPEndPoint(IPAddress.Parse(ip), port); + + socket.Connect(endPoint); + + SendData(); + Thread listen = new Thread(StartListening); + listen.Start(); + } + + /// + /// создается + /// + public void JoinYourself() // single player + { + endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), port); + + socket.Connect(endPoint); + + SendData(); + Thread listen = new Thread(StartListening); + listen.Start(); + } + + //поток 2 + public void StartListening() + { + while(socket.Connected) + { + byte[] bytes = new byte[2048]; + var countAnsw = socket.Receive(bytes); + string update = Encoding.UTF8.GetString(bytes, 0, countAnsw); // обновление отосланные сервером + GetDataSent(update); + } + } + } +} \ No newline at end of file diff --git a/ZoFo/GameCore/GameManagers/NetworkManager/ServerNetworkManager.cs b/ZoFo/GameCore/GameManagers/NetworkManager/ServerNetworkManager.cs new file mode 100644 index 0000000..8cfd461 --- /dev/null +++ b/ZoFo/GameCore/GameManagers/NetworkManager/ServerNetworkManager.cs @@ -0,0 +1,108 @@ +using Microsoft.Xna.Framework.Graphics; +using Microsoft.Xna.Framework.Graphics.PackedVector; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Text; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading; +using System.Threading.Tasks; +using ZoFo.GameCore.GameManagers.NetworkManager.Updates; + +namespace ZoFo.GameCore.GameManagers.NetworkManager +{ + public class ServerNetworkManager + { + private IPAddress ip = IPAddress.Any; + private int port = 7632; + private IPEndPoint endPoint; + private Socket socket; + private List clients; + private List updates; + public delegate void OnDataSend(string data); + public event OnDataSend GetDataSend; // event + Dictionary managerThread; + + public void Init() //create Socket + { + endPoint = new IPEndPoint(ip, port); + socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + managerThread = new Dictionary(); + } + /// + /// отправляет клиенту Data + /// + public void SendData() + { + string data = JsonSerializer.Serialize(updates); + var databytes = Encoding.UTF8.GetBytes(data); + foreach (var item in clients) + { + item.SendAsync(databytes); + } + } + /// + /// добавляет в лист updates новую data + /// + /// + public void AddData(IUpdateData data) + { + updates.Add(data); + } + + public void CloseConnection() //По сути коне игры и отключение игроков + { + foreach (var item in clients) + { + //Закрывает сокеты клиентов + item.Shutdown(SocketShutdown.Both); + item.Close(); + } + foreach (var item in managerThread) + { + foreach (var socket in clients) + { + //Закрывает потоки клиентов + managerThread[socket].Interrupt(); + } + } + //очищает листы + managerThread.Clear(); + clients.Clear(); + } + + //Потоки Клиентов + public void StartWaitingForPlayers(object players)//Слушает игроков, которые хотят подключиться + { + int playNumber = (int)players; + socket.Bind(endPoint); + socket.Listen(playNumber); + for (int i = 0; i < playNumber; i++) + { + Socket client = socket.Accept(); + Thread thread = new Thread(StartListening); + thread.Start(client); + managerThread.Add(client, thread); + clients.Add(client); //добавляем клиентов в лист + } + + } + private void StartListening(object socket)//начать слушать клиентов в самой игре активируют Ивент + { + // obj to Socket + Socket client = (Socket)socket; + while (client.Connected) + { + var buff = new byte[1024]; + var answ = client.Receive(buff); + string response = Encoding.UTF8.GetString(buff, 0, answ); + GetDataSend(response); + } + Thread.Sleep(-1); + + } + } +} diff --git a/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ClientToServer/UpdateInput.cs b/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ClientToServer/UpdateInput.cs new file mode 100644 index 0000000..81af1d9 --- /dev/null +++ b/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ClientToServer/UpdateInput.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ZoFo.GameCore.GameManagers.NetworkManager.Updates.ClientToServer +{ + public class UpdateInput :IUpdateData + { + public int IdEntity { get; set; } + public string UpdateType { get; set; } + } +} diff --git a/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ClientToServer/UpdatePlayerExit.cs b/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ClientToServer/UpdatePlayerExit.cs new file mode 100644 index 0000000..ba6c6ca --- /dev/null +++ b/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ClientToServer/UpdatePlayerExit.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ZoFo.GameCore.GameManagers.NetworkManager.Updates.ClientToServer +{ + public class UpdatePlayerExit : IUpdateData + { + public int IdEntity { get; set; } + public string UpdateType { get; set; } + } +} diff --git a/ZoFo/GameCore/GameManagers/NetworkManager/Updates/IUpdateData.cs b/ZoFo/GameCore/GameManagers/NetworkManager/Updates/IUpdateData.cs new file mode 100644 index 0000000..a90aaf4 --- /dev/null +++ b/ZoFo/GameCore/GameManagers/NetworkManager/Updates/IUpdateData.cs @@ -0,0 +1,27 @@ + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.Tasks; +using ZoFo.GameCore.GameManagers.NetworkManager.Updates.ClientToServer; +using ZoFo.GameCore.GameManagers.NetworkManager.Updates.ServerToClient; + +namespace ZoFo.GameCore.GameManagers.NetworkManager.Updates +{ + [JsonDerivedType(typeof(UpdateAnimation))] + [JsonDerivedType(typeof(UpdateEntityHealth))] + [JsonDerivedType(typeof(UpdateGameEnded))] + [JsonDerivedType(typeof(UpdateGameObjectCreated))] + [JsonDerivedType(typeof(UpdateLoot))] + [JsonDerivedType(typeof(UpdatePlayerParametrs))] + [JsonDerivedType(typeof(UpdatePosition))] + [JsonDerivedType(typeof(UpdateInput))] + [JsonDerivedType(typeof(UpdatePlayerExit))] + public interface IUpdateData + { + public int IdEntity { get; set; } //Id объекта + public string UpdateType { get; set; } //тип обновления + } +} diff --git a/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ServerToClient/UpdateAnimation.cs b/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ServerToClient/UpdateAnimation.cs new file mode 100644 index 0000000..6f07770 --- /dev/null +++ b/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ServerToClient/UpdateAnimation.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ZoFo.GameCore.GameManagers.NetworkManager.Updates.ServerToClient +{ + public class UpdateAnimation : IUpdateData //хранит новую анимации + { + public int IdEntity { get; set; } + public string UpdateType { get; set; } + } +} diff --git a/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ServerToClient/UpdateEntityHealth.cs b/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ServerToClient/UpdateEntityHealth.cs new file mode 100644 index 0000000..618770e --- /dev/null +++ b/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ServerToClient/UpdateEntityHealth.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ZoFo.GameCore.GameManagers.NetworkManager.Updates.ServerToClient +{ + public class UpdateEntityHealth : IUpdateData//хранит новое хп entity + { + public int IdEntity { get; set; } + public string UpdateType { get; set; } + } +} diff --git a/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ServerToClient/UpdateGameEnded.cs b/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ServerToClient/UpdateGameEnded.cs new file mode 100644 index 0000000..10173b7 --- /dev/null +++ b/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ServerToClient/UpdateGameEnded.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ZoFo.GameCore.GameManagers.NetworkManager.Updates.ServerToClient +{ + public class UpdateGameEnded : IUpdateData //хранит полученый лут и уведомляет о конце игры + { + public int IdEntity { get; set; } + public string UpdateType { get; set; } + } +} diff --git a/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ServerToClient/UpdateGameObjectCreated.cs b/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ServerToClient/UpdateGameObjectCreated.cs new file mode 100644 index 0000000..4cf8a42 --- /dev/null +++ b/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ServerToClient/UpdateGameObjectCreated.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ZoFo.GameCore.GameManagers.NetworkManager.Updates.ServerToClient +{ + public class UpdateGameObjectCreated : IUpdateData //Хранит объект, который только отправили + { + public int IdEntity { get; set; } + public string UpdateType { get; set; } + } +} diff --git a/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ServerToClient/UpdateLoot.cs b/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ServerToClient/UpdateLoot.cs new file mode 100644 index 0000000..e7f8a51 --- /dev/null +++ b/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ServerToClient/UpdateLoot.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ZoFo.GameCore.GameManagers.NetworkManager.Updates.ServerToClient +{ + public class UpdateLoot : IUpdateData //Хранит лут + { + public int IdEntity { get; set; } + public string UpdateType { get; set; } + } +} diff --git a/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ServerToClient/UpdatePlayerParametrs.cs b/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ServerToClient/UpdatePlayerParametrs.cs new file mode 100644 index 0000000..36a2544 --- /dev/null +++ b/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ServerToClient/UpdatePlayerParametrs.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ZoFo.GameCore.GameManagers.NetworkManager.Updates.ServerToClient +{ + public class UpdatePlayerParametrs : IUpdateData //Хранит хп, радиацию + { + public int IdEntity { get; set; } + public string UpdateType { get; set; } + } +} diff --git a/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ServerToClient/UpdatePosition.cs b/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ServerToClient/UpdatePosition.cs new file mode 100644 index 0000000..fda8a39 --- /dev/null +++ b/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ServerToClient/UpdatePosition.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ZoFo.GameCore.GameManagers.NetworkManager.Updates.ServerToClient +{ + public class UpdatePosition : IUpdateData //Хранит новую позицию + { + public int IdEntity { get; set; } + public string UpdateType { get; set; } + } +} diff --git a/ZoFo/GameCore/GameManagers/NetworkManager/Updates/Update.cs b/ZoFo/GameCore/GameManagers/NetworkManager/Updates/Update.cs deleted file mode 100644 index d52f59e..0000000 --- a/ZoFo/GameCore/GameManagers/NetworkManager/Updates/Update.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace ZoFo.GameCore.GameManagers.NetworkManager.Updates; - -public class Update -{ - -} \ No newline at end of file diff --git a/ZoFo/GameCore/GameManagers/SettingsManager.cs b/ZoFo/GameCore/GameManagers/SettingsManager.cs new file mode 100644 index 0000000..25dd40d --- /dev/null +++ b/ZoFo/GameCore/GameManagers/SettingsManager.cs @@ -0,0 +1,93 @@ +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using Microsoft.Xna; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Xna.Framework; +using Newtonsoft.Json.Serialization; +using Microsoft.Xna.Framework.Graphics; + +namespace ZoFo.GameCore.GameManagers +{ + public class SettingsManager //нужно что-то менять с разрешением + { + private SettingsContainer settingsContainer = new SettingsContainer(); + public bool IsFullScreen { get => settingsContainer.IsFullScreen; } + public float MainVolume { get => settingsContainer.MainVolume; } + public float MusicVolume { get => settingsContainer.MusicVolume; } + public float SoundEffectsVolume { get => settingsContainer.SoundEffectsVolume; } + public Point Resolution { get => settingsContainer.Resolution; } + public void SetResolution(Point resolution) + { + settingsContainer.Resolution = resolution; + //AppManager.Instance.resolution = resolution; + } + public void SetMainVolume(float volume) + { + settingsContainer.MainVolume = volume; + //AppManager.Instance.SoundManager.Update(); + SaveSettings(); + } + public void SetMusicVolume(float volume) + { + settingsContainer.MusicVolume = volume; + SaveSettings(); + + } + public void SetSoundEffectsVolume(float volume) + { + settingsContainer.SoundEffectsVolume = volume; + SaveSettings(); + + } + public void SetIsFullScreen(bool isFullScreen) + { + settingsContainer.IsFullScreen = isFullScreen; + //AppManager.Instance.SetIsFullScreen(isFullScreen); + SaveSettings(); + } + public void LoadSettings() + { + if (!File.Exists("GameSettings.txt")) + { + SaveSettings(); + return; + } + + settingsContainer = JsonConvert.DeserializeObject(File.ReadAllText("GameSettings.txt")); + SetIsFullScreen(settingsContainer.IsFullScreen); + SetMainVolume(settingsContainer.MainVolume); + SetMusicVolume(settingsContainer.MusicVolume); + SetResolution(settingsContainer.Resolution); + SetSoundEffectsVolume(settingsContainer.SoundEffectsVolume); + + + } + public void SaveSettings() + { + using (StreamWriter streamWriter = new StreamWriter("GameSettings.txt")) + { + string _str = JsonConvert.SerializeObject(settingsContainer); + streamWriter.Write(_str); + } + } + + } + [Serializable] + public class SettingsContainer + { + [JsonProperty("IsFullScreen")] + public bool IsFullScreen { get; set; } = false; + [JsonProperty("MainVolume")] + public float MainVolume { get; set; } = 1; + [JsonProperty("MusicVolume")] + public float MusicVolume { get; set; } = 1; + [JsonProperty("SoundEffectsVolume")] + public float SoundEffectsVolume { get; set; } = 1; + [JsonProperty("Resolution")] + public Point Resolution { get; set; } = new Point(GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width, GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height); + } +} \ No newline at end of file diff --git a/ZoFo/GameCore/GameManagers/SoundManager.cs b/ZoFo/GameCore/GameManagers/SoundManager.cs new file mode 100644 index 0000000..d99211e --- /dev/null +++ b/ZoFo/GameCore/GameManagers/SoundManager.cs @@ -0,0 +1,131 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.IO; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Audio; +using Microsoft.Xna.Framework.Content; +using System.Linq; +using DangerousD.GameCore.Graphics; +using Newtonsoft.Json; +using Microsoft.Xna.Framework.Media; + +namespace ZoFo.GameCore.GameManagers +{ + public class SoundManager + { + public Dictionary Sounds = new Dictionary(); // словарь со звуками где строка - название файла + public List PlayingSounds = new List(); // список со всеми звуками, которые проигрываются + public static float MaxSoundDistance = 100; // максимальная дальность звука(возможно не нужна) + + public void LoadSounds() // метод для загрузки звуков из папки + { + var k = Directory.GetFiles("../../..//Content//sounds").Where(x => x.EndsWith("mp3")); + + if (k.Count() > 0) + { + + string[] soundFiles = k.Select(x => x.Split("\\").Last().Split("/").Last().Replace(".mp3", "")).ToArray();// папка со звуками там где exe + foreach (var soundFile in soundFiles) + { + Sounds.Add(soundFile, AppManager.Instance.Content.Load("sounds//" + soundFile)); + } + + } + + if (k.Count() > 0) + { + + } + } + + public void StartAmbientSound(string soundName) // запустить звук у которого нет позиции + { + var sound = new Sound(Sounds[soundName].CreateInstance(), Vector2.One, true); + // ждать пока настройки появятся sound.SoundEffect.Volume = sound.baseVolume * AppManager.Instance.SettingsManager.MusicVolume * AppManager.Instance.SettingsManager.MainVolume; + sound.SoundEffect.IsLooped = false; + + sound.SoundEffect.Play(); + PlayingSounds.Add(sound); + + /*/ if (AppManager.Instance.multiPlayerStatus == MultiPlayerStatus.Host) + { + AppManager.Instance.NetworkTasks.Add(new Network.NetworkTask(Vector2.Zero, soundName)); + }/*/ //Ждать пока закончат работу с сетями + } + public void StartSound(string soundName, Vector2 soundPos, Vector2 playerPos, float baseVolume = 1, float pitch = 0) // запустить звук у которого есть позиция + { + var sound = new Sound(Sounds[soundName].CreateInstance(), soundPos, false) { baseVolume = baseVolume, basePich = pitch }; + sound.SoundEffect.IsLooped = false; + //ждать пока настройки появятся sound.SoundEffect.Volume = sound.baseVolume * AppManager.Instance.SettingsManager.SoundEffectsVolume * AppManager.Instance.SettingsManager.MainVolume; + sound.SoundEffect.Pitch = pitch; + sound.SoundEffect.Play(); + PlayingSounds.Add(sound); + + /*/ if (AppManager.Instance.multiPlayerStatus == MultiPlayerStatus.Host) + { + AppManager.Instance.NetworkTasks.Add(new Network.NetworkTask(soundPos, soundName)); + }/*/ //Ждать пока закончат работу с сетями + } + public void StopAllSounds() // остановка всех звуков + { + foreach (var sound in PlayingSounds) + sound.SoundEffect.Stop(); + PlayingSounds.Clear(); + } + + public void Update() // апдейт, тут происходит изменение громкости + { + for (int i = 0; i < PlayingSounds.Count; i++) + { + //PlayingSounds[i].UpdateVolume(Vector2.Zero); + if (PlayingSounds[i].SoundEffect.State == SoundState.Stopped) + { + PlayingSounds.Remove(PlayingSounds[i]); + i--; + } + } + return; + + /*/var player = AppManager.Instance.GameManager.GetPlayer1; + if (player != null) + { + for (int i = 0; i < PlayingSounds.Count; i++) + { + if (!PlayingSounds[i].isAmbient) + PlayingSounds[i].SoundEffect.Volume = (float)(MaxSoundDistance - PlayingSounds[i].GetDistanceVol(player.Pos)) / MaxSoundDistance; + if (PlayingSounds[i].SoundEffect.State == SoundState.Stopped) + PlayingSounds.Remove(PlayingSounds[i]); + } + }/*/ + } + } + + public class Sound + { + public SoundEffectInstance SoundEffect { get; set; } + public Vector2 Position { get; set; } // позиция для эффекта + public bool isAmbient { get; } + public float baseVolume { get; set; } = 1; + public float basePich { get; set; } = 0; + public Sound(SoundEffectInstance soundEffect, Vector2 position, bool isAmbient) // конструктор для эффектов по типу криков зомби + { + this.isAmbient = isAmbient; + SoundEffect = soundEffect; + Position = position; + } + /*/public void UpdateVolume(Vector2 playerPos) + { + if (isAmbient) + SoundEffect.Volume = baseVolume * AppManager.Instance.SettingsManager.MusicVolume * AppManager.Instance.SettingsManager.MainVolume; + else + SoundEffect.Volume = baseVolume * AppManager.Instance.SettingsManager.SoundEffectsVolume * AppManager.Instance.SettingsManager.MainVolume;// * (float)Math.Clamp(1 - GetDistanceVol(playerPos),0,1); + + }/*/ + + public double GetDistanceVol(Vector2 playerPos) // получение дистанции до объедка от игрока + { + return Math.Sqrt(Math.Pow(Position.X - playerPos.X, 2) + Math.Pow(Position.Y - playerPos.Y, 2)) - SoundManager.MaxSoundDistance; + } + } +} diff --git a/ZoFo/GameCore/GameObjects/Entities/Entity.cs b/ZoFo/GameCore/GameObjects/Entities/Entity.cs new file mode 100644 index 0000000..10283c5 --- /dev/null +++ b/ZoFo/GameCore/GameObjects/Entities/Entity.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using ZoFo.GameCore.GameManagers.CollisionManager; +using ZoFo.GameCore.ZoFo_graphics; + +namespace ZoFo.GameCore.GameObjects.Entities +{ + public abstract class Entity : GameObject + { + protected override GraphicsComponent graphicsComponent => null; + public CollisionComponent collisionComponent { get; protected set; } + public int Id { get; set; } + public void CollisionComponent() + { + + } + + public void AnimationComponent() + { + + } + + public void UpdateLogic() + { + + } + + } +} + +//вектор +//вилосити +//поситион +//текстура diff --git a/ZoFo/GameCore/GameObjects/Entities/Interactables/Collectables/Collectable.cs b/ZoFo/GameCore/GameObjects/Entities/Interactables/Collectables/Collectable.cs new file mode 100644 index 0000000..843258f --- /dev/null +++ b/ZoFo/GameCore/GameObjects/Entities/Interactables/Collectables/Collectable.cs @@ -0,0 +1,7 @@ +using System; + +namespace ZoFo.GameCore.GameObjects.Entities.Interactables.Collectables; +public class Collectable : Entity +{ + +} diff --git a/ZoFo/GameCore/GameObjects/Entities/LivingEntities/Enemies/Enemy.cs b/ZoFo/GameCore/GameObjects/Entities/LivingEntities/Enemies/Enemy.cs new file mode 100644 index 0000000..9a3b320 --- /dev/null +++ b/ZoFo/GameCore/GameObjects/Entities/LivingEntities/Enemies/Enemy.cs @@ -0,0 +1,11 @@ +using System; +using System.Collections.Generic; +using System.Net.Mime; +using System.Reflection; +using Microsoft.Xna.Framework.Content; + +namespace ZoFo.GameCore.GameObjects.Entities.LivingEntities.Enemies; +public class Enemy : LivingEntity +{ + +} \ No newline at end of file diff --git a/ZoFo/GameCore/GameObjects/Entities/LivingEntities/LivingEntity.cs b/ZoFo/GameCore/GameObjects/Entities/LivingEntities/LivingEntity.cs new file mode 100644 index 0000000..d09be3a --- /dev/null +++ b/ZoFo/GameCore/GameObjects/Entities/LivingEntities/LivingEntity.cs @@ -0,0 +1,22 @@ +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using System; +using ZoFo.GameCore.GameObjects.Entities; +using ZoFo.GameCore.ZoFo_graphics; + +namespace ZoFo.GameCore.GameObjects.Entities.LivingEntities; +public class LivingEntity : Entity +{ + public Vector2 velocity; + + + public void TextureLoad(SpriteBatch spriteBatch) + { + + } + +} + + + + diff --git a/ZoFo/GameCore/GameObjects/Entities/LivingEntities/Player/IPlayerWeaponAttack.cs b/ZoFo/GameCore/GameObjects/Entities/LivingEntities/Player/IPlayerWeaponAttack.cs new file mode 100644 index 0000000..3fafa2b --- /dev/null +++ b/ZoFo/GameCore/GameObjects/Entities/LivingEntities/Player/IPlayerWeaponAttack.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ZoFo.GameCore.GameObjects.Entities.LivingEntities.Player +{ + internal interface IPlayerWeaponAttack + { + + } +} diff --git a/ZoFo/GameCore/GameObjects/Entities/LivingEntities/Player/LootData.cs b/ZoFo/GameCore/GameObjects/Entities/LivingEntities/Player/LootData.cs new file mode 100644 index 0000000..5336e7b --- /dev/null +++ b/ZoFo/GameCore/GameObjects/Entities/LivingEntities/Player/LootData.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ZoFo.GameCore.GameObjects.Entities.LivingEntities.Player +{ + internal class LootData + { + public Dictionary loots; + public void AddLoot(object lootObject, int quantity) + { + + } + } +} diff --git a/ZoFo/GameCore/GameObjects/Entities/LivingEntities/Player/Player.cs b/ZoFo/GameCore/GameObjects/Entities/LivingEntities/Player/Player.cs new file mode 100644 index 0000000..a1333ea --- /dev/null +++ b/ZoFo/GameCore/GameObjects/Entities/LivingEntities/Player/Player.cs @@ -0,0 +1,7 @@ +using System; + +namespace ZoFo.GameCore.GameObjects.Entities.LivingEntities.Player; +public class Player : LivingEntity +{ + +} diff --git a/ZoFo/GameCore/GameObjects/Entities/LivingEntities/Player/PlayerAttacks/GunAttack.cs b/ZoFo/GameCore/GameObjects/Entities/LivingEntities/Player/PlayerAttacks/GunAttack.cs new file mode 100644 index 0000000..ffa2869 --- /dev/null +++ b/ZoFo/GameCore/GameObjects/Entities/LivingEntities/Player/PlayerAttacks/GunAttack.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ZoFo.GameCore.GameObjects.Entities.LivingEntities.Player.PlayerAttacks +{ + internal class GunAttack : IPlayerWeaponAttack + { + + } +} diff --git a/ZoFo/GameCore/GameObjects/Entities/LivingEntities/Player/PlayerAttacks/HandAttack.cs b/ZoFo/GameCore/GameObjects/Entities/LivingEntities/Player/PlayerAttacks/HandAttack.cs new file mode 100644 index 0000000..b993cc0 --- /dev/null +++ b/ZoFo/GameCore/GameObjects/Entities/LivingEntities/Player/PlayerAttacks/HandAttack.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ZoFo.GameCore.GameObjects.Entities.LivingEntities.Player.PlayerAttacks +{ + internal class HandAttack : IPlayerWeaponAttack + { + + } +} diff --git a/ZoFo/GameCore/GameObjects/Entities/LivingEntities/Player/PlayerAttacks/SwordAttack.cs b/ZoFo/GameCore/GameObjects/Entities/LivingEntities/Player/PlayerAttacks/SwordAttack.cs new file mode 100644 index 0000000..508f02f --- /dev/null +++ b/ZoFo/GameCore/GameObjects/Entities/LivingEntities/Player/PlayerAttacks/SwordAttack.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ZoFo.GameCore.GameObjects.Entities.LivingEntities.Player.PlayerAttacks +{ + internal class SwordAttack : IPlayerWeaponAttack + { + + } +} diff --git a/ZoFo/GameCore/GameObjects/Entities/LivingEntities/Projectiles/Bullet.cs b/ZoFo/GameCore/GameObjects/Entities/LivingEntities/Projectiles/Bullet.cs new file mode 100644 index 0000000..83643f0 --- /dev/null +++ b/ZoFo/GameCore/GameObjects/Entities/LivingEntities/Projectiles/Bullet.cs @@ -0,0 +1,7 @@ +using System; + +namespace ZoFo.GameCore.GameObjects.Entities.LivingEntities.Projectiles; +public class Bullet : Projectile +{ + +} diff --git a/ZoFo/GameCore/GameObjects/Entities/LivingEntities/Projectiles/Projectile.cs b/ZoFo/GameCore/GameObjects/Entities/LivingEntities/Projectiles/Projectile.cs new file mode 100644 index 0000000..dba7dae --- /dev/null +++ b/ZoFo/GameCore/GameObjects/Entities/LivingEntities/Projectiles/Projectile.cs @@ -0,0 +1,7 @@ +using System; + +namespace ZoFo.GameCore.GameObjects.Entities.LivingEntities.Projectiles; +public class Projectile : LivingEntity +{ + +} diff --git a/ZoFo/GameCore/GameObjects/Entities/LivingEntities/Projectiles/Rock.cs b/ZoFo/GameCore/GameObjects/Entities/LivingEntities/Projectiles/Rock.cs new file mode 100644 index 0000000..caf91a4 --- /dev/null +++ b/ZoFo/GameCore/GameObjects/Entities/LivingEntities/Projectiles/Rock.cs @@ -0,0 +1,7 @@ +using System; + +namespace ZoFo.GameCore.GameObjects.Entities.LivingEntities.Projectiles; +public class Rock : Projectile +{ + +} diff --git a/ZoFo/GameCore/GameObjects/GameObject.cs b/ZoFo/GameCore/GameObjects/GameObject.cs index 510f160..813c583 100644 --- a/ZoFo/GameCore/GameObjects/GameObject.cs +++ b/ZoFo/GameCore/GameObjects/GameObject.cs @@ -1,6 +1,15 @@ -namespace ZoFo.GameCore.GameObjects; + +using Microsoft.Xna.Framework; +using ZoFo.GameCore.ZoFo_graphics; -public class GameObject +namespace ZoFo.GameCore.GameObjects; + +public abstract class GameObject { - + public Vector2 position; + public Vector2 rotation; + + protected abstract GraphicsComponent graphicsComponent { get; } + public void Draw() { } + } \ No newline at end of file diff --git a/ZoFo/GameCore/GameObjects/StopObjects/StopObject.cs b/ZoFo/GameCore/GameObjects/StopObjects/StopObject.cs new file mode 100644 index 0000000..85f95b4 --- /dev/null +++ b/ZoFo/GameCore/GameObjects/StopObjects/StopObject.cs @@ -0,0 +1,8 @@ +using System; + +namespace ZoFo.GameCore.GameObjects.StopObjects; + +public class StopObject +{ + +} diff --git a/ZoFo/GameCore/GameObjects/Tiles/Tile.cs b/ZoFo/GameCore/GameObjects/Tiles/Tile.cs new file mode 100644 index 0000000..16cc1c9 --- /dev/null +++ b/ZoFo/GameCore/GameObjects/Tiles/Tile.cs @@ -0,0 +1,8 @@ +using System; + +namespace ZoFo.GameCore.GameObjects; + +public class Tile +{ + +} diff --git a/ZoFo/GameCore/Server.cs b/ZoFo/GameCore/Server.cs new file mode 100644 index 0000000..337f46c --- /dev/null +++ b/ZoFo/GameCore/Server.cs @@ -0,0 +1,63 @@ +using Microsoft.Xna.Framework; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +using ZoFo.GameCore.GameManagers.NetworkManager; +using ZoFo.GameCore.GameManagers.NetworkManager.Updates; +using ZoFo.GameCore.GameManagers.NetworkManager.Updates.ServerToClient; +using ZoFo.GameCore.GameObjects; +using ZoFo.GameCore.GameObjects.Entities; + +namespace ZoFo.GameCore +{ + public class Server + { + private List gameObjects; + private ServerNetworkManager networkManager; + private List entity; //entity + public Server() + { + networkManager = new ServerNetworkManager(); + networkManager.GetDataSend += OnDataSend; + } + public void OnDataSend(string data) + { + List updateDatas = JsonSerializer.Deserialize>(data); + + //ТУТ Switch case будет честное слово + } + /// + /// Для красоты) Отдел Серверов + /// + /// + public void AddData(IUpdateData data)//добавляет в лист updates новую data + { + networkManager.AddData(data); + } + public void CreateRoom(int players) //Создает комнату и запускает ожидание подключений + { + networkManager.StartWaitingForPlayers(players); + } + + // public void StartGame() { } принудительный запуск + public void EndGame() //Добавляет UpdateGameEnded и отключает игроков + { + UpdateGameEnded gameEnded = new UpdateGameEnded(); + networkManager.AddData(gameEnded); + networkManager.CloseConnection(); + } + + + public void Update(GameTime gameTime) + { + } + + public void RegisterEntity(GameObject gameObject) + { + gameObjects.Add(gameObject); + } + } +} diff --git a/ZoFo/GameCore/ZoFo_grafics/AnimationBuilder.cs b/ZoFo/GameCore/ZoFo_grafics/AnimationBuilder.cs new file mode 100644 index 0000000..d18303c --- /dev/null +++ b/ZoFo/GameCore/ZoFo_grafics/AnimationBuilder.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.IO; +using Newtonsoft.Json; +using Zofo.GameCore.ZoFo_grafics; + +namespace DangerousD.GameCore.Graphics +{ + public class AnimationBuilder + { + public List Animations { get; private set; } + public void LoadAnimations() + { + Animations = new List(); + string[] animationFilesNames = Directory.GetFiles("../../../Content/animations"); + + StreamReader reader; + foreach (var fileName in animationFilesNames) + { + reader = new StreamReader(fileName); + string json = reader.ReadToEnd(); + AnimationContainer animation = JsonConvert.DeserializeObject(json); + Animations.Add(animation); + reader.Close(); + } + + } + } +} diff --git a/ZoFo/GameCore/ZoFo_grafics/AnimationContainer.cs b/ZoFo/GameCore/ZoFo_grafics/AnimationContainer.cs new file mode 100644 index 0000000..36596d0 --- /dev/null +++ b/ZoFo/GameCore/ZoFo_grafics/AnimationContainer.cs @@ -0,0 +1,32 @@ +using Microsoft.Xna.Framework; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Text; + +namespace Zofo.GameCore.ZoFo_grafics +{ + [Serializable] + public class AnimationContainer + { + [JsonProperty("id")] + public string Id { get; set; } + [JsonProperty("textureName")] + public string TextureName { get; set; } + [JsonProperty("startSpriteRectangle")] + public Rectangle StartSpriteRectangle { get; set; } + [JsonProperty("frameSecond")] + public List> FrameTime { get; set; } + [JsonProperty("textureFrameInterval")] + public int TextureFrameInterval { get; set; } + [JsonProperty("framesCount")] + public int FramesCount { get; set; } + [JsonProperty("isCycle")] + public bool IsCycle { get; set; } + [JsonProperty("offset")] + public Vector2 Offset { get; set; } + + + + } +} diff --git a/ZoFo/GameCore/ZoFo_grafics/GraphicsComponent.cs b/ZoFo/GameCore/ZoFo_grafics/GraphicsComponent.cs new file mode 100644 index 0000000..a60cee1 --- /dev/null +++ b/ZoFo/GameCore/ZoFo_grafics/GraphicsComponent.cs @@ -0,0 +1,282 @@ +using ZoFo.GameCore.GameObjects; +using ZoFo.GameCore.GameManagers; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Content; +using Microsoft.Xna.Framework.Graphics; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Cryptography.X509Certificates; +using System.Text; +using Zofo.GameCore.ZoFo_grafics; + +namespace ZoFo.GameCore.ZoFo_graphics +{ + + public class GraphicsComponent + { + public event Action actionOfAnimationEnd; + private List animations; + private List textures; + private List texturesNames; + private AnimationContainer currentAnimation; + static public int scaling = 4; + public int parentId; + public AnimationContainer CurrentAnimation + { + get + { + return currentAnimation; + } + } + public string LastAnimation { get; set; } + public string GetCurrentAnimation + { + get { return currentAnimation.Id; } + } + + private AnimationContainer neitralAnimation; + //private SpriteBatch _spriteBatch; + + private int currentFrame; + public int CurrentFrame + { + get + { + return currentFrame; + } + } + private int interval; + private int lastInterval; + private Rectangle sourceRectangle; + public GraphicsComponent(List animationsId, string neitralAnimationId) + { + //this._spriteBatch = _spriteBatch; + currentFrame = 0; + lastInterval = 1; + LoadAnimations(animationsId, neitralAnimationId); + currentAnimation = neitralAnimation; + SetInterval(); + buildSourceRectangle(); + } + + public GraphicsComponent(string textureName) + { + animations = new List(); + textures = new List(); + var texture = AppManager.Instance.Content.Load(textureName); + textures.Add(texture); + AnimationContainer animationContainer = new AnimationContainer(); + animationContainer.StartSpriteRectangle = new Rectangle(0, 0, texture.Width, texture.Height); + animationContainer.TextureFrameInterval = 0; + animationContainer.TextureName = texture.Name; + animationContainer.IsCycle = true; + animationContainer.FramesCount = 1; + animationContainer.FrameTime = new List>() { new Tuple(0, 10) }; + animationContainer.Id = texture.Name; + currentAnimation = animationContainer; + neitralAnimation = animationContainer; + animations.Add(animationContainer); + } + + private void LoadAnimations(List animationsId, string neitralAnimationId) + { + animations = new List(); + foreach (var id in animationsId) + { + animations.Add(AppManager.Instance.animationBuilder.Animations.Find(x => x.Id == id)); + if (id == neitralAnimationId) + { + neitralAnimation = animations.Last(); + } + } + } + + public void LoadContent() + { + textures = new List(); + texturesNames = new List(); + + foreach (var animation in animations) + { + if (!texturesNames.Contains(animation.TextureName)) + { + texturesNames.Add(animation.TextureName); + textures.Add(AppManager.Instance.Content.Load(animation.TextureName)); + } + } + } + + public void StartAnimation(string startedanimationId) + { + /* + if (AppManager.Instance.multiPlayerStatus != MultiPlayerStatus.SinglePlayer) + { + LivingEntity entity = AppManager.Instance.GameManager.livingEntities.Find(x => x.id == parentId); + if (((entity is Player) || AppManager.Instance.multiPlayerStatus == MultiPlayerStatus.Host) && startedanimationId != GetCurrentAnimation) + { + AppManager.Instance.NetworkTasks.Add(new NetworkTask(parentId, startedanimationId, Vector2.Zero)); + } + } + */ + currentFrame = 0; + currentAnimation = animations.Find(x => x.Id == startedanimationId); + + buildSourceRectangle(); + SetInterval(); + } + + public void StopAnimation() + { + currentFrame = 0; + interval = 0; + currentAnimation = neitralAnimation; + buildSourceRectangle(); + SetInterval(); + } + + public void Update() + { + if (interval == 0) + { + currentFrame++; + if (currentAnimation.FramesCount <= currentFrame) + { + if (!currentAnimation.IsCycle) + { + if (actionOfAnimationEnd != null) + { + actionOfAnimationEnd(currentAnimation.Id); + } + currentAnimation = neitralAnimation; + + } + + currentFrame = 0; + + } + + buildSourceRectangle(); + SetInterval(); + } + + interval--; + } + + public void DrawAnimation(Rectangle destinationRectangle, SpriteBatch _spriteBatch) + { + Texture2D texture = textures[texturesNames.FindIndex(x => x == currentAnimation.TextureName)]; + float scale; + if (currentAnimation.Offset.X != 0) + { + destinationRectangle.X -= (int)currentAnimation.Offset.X; + scale = destinationRectangle.Height / sourceRectangle.Height; + destinationRectangle.Width = (int)(sourceRectangle.Width * scale); + + } + else if (currentAnimation.Offset.Y != 0) + { + destinationRectangle.Y -= (int)currentAnimation.Offset.Y; + scale = destinationRectangle.Width / sourceRectangle.Width; + destinationRectangle.Height = (int)(sourceRectangle.Height * scale); + } + + destinationRectangle.X -= CameraPosition.X; + destinationRectangle.Y -= CameraPosition.Y; + + destinationRectangle = Scaling(destinationRectangle); + _spriteBatch.Draw(texture, + destinationRectangle, sourceRectangle, Color.White); + } + public void DrawAnimation(Rectangle destinationRectangle, SpriteBatch _spriteBatch, Rectangle sourceRectangle) + { + Texture2D texture = textures[texturesNames.FindIndex(x => x == currentAnimation.TextureName)]; + float scale; + if (currentAnimation.Offset.X != 0) + { + destinationRectangle.X -= (int)currentAnimation.Offset.X; + scale = destinationRectangle.Height / sourceRectangle.Height; + destinationRectangle.Width = (int)(sourceRectangle.Width * scale); + + } + else if (currentAnimation.Offset.Y != 0) + { + destinationRectangle.Y -= (int)currentAnimation.Offset.Y; + scale = destinationRectangle.Width / sourceRectangle.Width; + destinationRectangle.Height = (int)(sourceRectangle.Height * scale); + } + + destinationRectangle.X -= CameraPosition.X; + destinationRectangle.Y -= CameraPosition.Y; + + destinationRectangle = Scaling(destinationRectangle); + _spriteBatch.Draw(texture, + destinationRectangle, sourceRectangle, Color.White); + } + private Rectangle Scaling(Rectangle destinationRectangle) + { + destinationRectangle.X *= scaling; + destinationRectangle.Y *= scaling; + destinationRectangle.Width *= scaling; + destinationRectangle.Height *= scaling; + return destinationRectangle; + } + private void buildSourceRectangle() + { + sourceRectangle = new Rectangle(); + if (currentAnimation == null) + { + currentAnimation = neitralAnimation; + } + sourceRectangle.X = currentAnimation.StartSpriteRectangle.X + currentFrame * + (currentAnimation.StartSpriteRectangle.Width + currentAnimation.TextureFrameInterval); + sourceRectangle.Y = currentAnimation.StartSpriteRectangle.Y; + sourceRectangle.Height = currentAnimation.StartSpriteRectangle.Height; + sourceRectangle.Width = currentAnimation.StartSpriteRectangle.Width; + } + + private void SetInterval() + { + Tuple i = currentAnimation.FrameTime.Find(x => x.Item1 == currentFrame); + if (i != null) + { + interval = i.Item2; + lastInterval = interval; + } + else + { + interval = lastInterval; + } + } + public static void SetCameraPosition(Vector2 playerPosition) + { + CameraPosition = (playerPosition).ToPoint(); + CameraPosition.X -= 200; + CameraPosition.Y -= 120; + + // TODO + /* + if (CameraPosition.X > AppManager.Instance.GameManager.CameraBorder.Y - 460) + { + CameraPosition.X = (int)AppManager.Instance.GameManager.CameraBorder.Y - 460; + } + + if (CameraPosition.Y < AppManager.Instance.GameManager.CameraBorder.Z) + { + CameraPosition.Y = (int)AppManager.Instance.GameManager.CameraBorder.Z; + } + if (CameraPosition.X < AppManager.Instance.GameManager.CameraBorder.X) + { + CameraPosition.X = (int)AppManager.Instance.GameManager.CameraBorder.X; + } + if (CameraPosition.Y > AppManager.Instance.GameManager.CameraBorder.W - 240) + { + CameraPosition.Y = (int)AppManager.Instance.GameManager.CameraBorder.W - 240; + } + + AppManager.Instance.DebugHUD.Set("CameraPosition", $"{CameraPosition.X}, {CameraPosition.Y}"); + */ + } + public static Point CameraPosition = new Point(-700, 300); + } +} diff --git a/ZoFo/Program.cs b/ZoFo/Program.cs index c1f32ef..deeb5db 100644 --- a/ZoFo/Program.cs +++ b/ZoFo/Program.cs @@ -1,2 +1,2 @@ -using var game = new ZoFo.Game1(); +using var game = new ZoFo.GameCore.GameManagers.AppManager(); game.Run(); \ No newline at end of file diff --git a/ZoFo/ZoFo.csproj b/ZoFo/ZoFo.csproj index ef2682f..4c3c3f7 100644 --- a/ZoFo/ZoFo.csproj +++ b/ZoFo/ZoFo.csproj @@ -1,4 +1,4 @@ - + WinExe net8.0 @@ -11,22 +11,31 @@ Icon.ico - - + + + - - + + - - + + + + + + + + + + - - + + \ No newline at end of file diff --git a/macos-fix-mgcb.sh b/macos-fix-mgcb.sh new file mode 100755 index 0000000..a2ec83b --- /dev/null +++ b/macos-fix-mgcb.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash + +brew install freetype +brew install freeimage +mgcb_ver=$(ls ~/.nuget/packages/dotnet-mgcb/) +mgcb_path=~/.nuget/packages/dotnet-mgcb/$mgcb_ver/tools/net6.0/any/ + +rm $mgcb_path/libfreetype6.dylib $mgcb_path/libFreeImage.dylib + +ln -s /opt/homebrew/lib/libfreetype.dylib $mgcb_path/libfreetype6.dylib +ln -s /opt/homebrew/lib/libfreeimage.dylib $mgcb_path/libFreeImage.dylib