diff --git a/MonogameLibrary/UI/Base/DrawableUIElement.cs b/MonogameLibrary/UI/Base/DrawableUIElement.cs index 8835ce0..7e4488c 100644 --- a/MonogameLibrary/UI/Base/DrawableUIElement.cs +++ b/MonogameLibrary/UI/Base/DrawableUIElement.cs @@ -18,6 +18,7 @@ namespace MonogameLibrary.UI.Base public string textureName = ""; public Rectangle rectangle = new Rectangle(0, 0, 10, 10); public Color mainColor = Color.White; + public bool sus = true; public DrawableUIElement(UIManager manager, int layerIndex = 0, string textureName = "") { @@ -29,6 +30,7 @@ namespace MonogameLibrary.UI.Base { if (textureName == "") { + sus = false; texture = new Texture2D(Manager.GraphicsDevice, 1, 1); texture.SetData(new Color[] { mainColor }); } diff --git a/MonogameLibrary/UI/Elements/Bar.cs b/MonogameLibrary/UI/Elements/Bar.cs index 34409b2..96b4067 100644 --- a/MonogameLibrary/UI/Elements/Bar.cs +++ b/MonogameLibrary/UI/Elements/Bar.cs @@ -18,7 +18,7 @@ public class Bar : DrawableUIElement public float percent = 0.5f; private DrawableUIElement barInside; public Color inColor; - public string inTextureName; + public string inTextureName = ""; public Bar(UIManager manager, int layerIndex = 0, string textureName = "") : base(manager, layerIndex, textureName) { @@ -30,8 +30,7 @@ public class Bar : DrawableUIElement { rectangle = new Rectangle(rectangle.X + rectangle.Height / 8, rectangle.Y + rectangle.Height / 8, (int)((rectangle.Width - rectangle.Height / 4) * percent), rectangle.Height / 8 * 7), - mainColor = inColor, - textureName = inTextureName + mainColor = inColor }; } diff --git a/MonogameLibrary/UI/Elements/ItemDisplayButton.cs b/MonogameLibrary/UI/Elements/ItemDisplayButton.cs index c44ffe2..c8b0ed8 100644 --- a/MonogameLibrary/UI/Elements/ItemDisplayButton.cs +++ b/MonogameLibrary/UI/Elements/ItemDisplayButton.cs @@ -29,6 +29,7 @@ public class ItemDisplayButton : Button private ContentManager content; public string discriptions1; public Dictionary resourcesNeededToCraft1; + public TextAligment TextAligment = TextAligment.Left; public ItemDisplayButton(UIManager manager) : base(manager) @@ -46,7 +47,7 @@ public class ItemDisplayButton : Button Label itemName = new Label(Manager) { rectangle = new Rectangle(rectangle.X + rectangle.Height / 3 / 2 + rectangle.Height / 3 * 2, rectangle.Y + rectangle.Height / 3 / 2, rectangle.Width / 3, rectangle.Height / 3 * 2), - fontColor = fontColor1, text = text1, scale = scale1, fontName = fontName1, mainColor = Color.Transparent + fontColor = fontColor1, text = text1, scale = scale1, fontName = fontName1, mainColor = Color.Transparent, textAligment = TextAligment }; Label itemCount = new Label(Manager) { @@ -87,6 +88,10 @@ public class ItemDisplayButton : Button { if (presentState != hoverState) { + if (resourcesNeededToCraft1 == null) + { + resourcesNeededToCraft1 = new Dictionary(); + } hoverWindow = new HoverWindow(Manager) { rectangle = new Rectangle(Mouse.GetState().Position.X, Mouse.GetState().Position.Y, rectangle.Width, rectangle.Height * 10), @@ -97,7 +102,8 @@ public class ItemDisplayButton : Button fontColor2 = fontColor1, fontName2 = fontName1, scale2 = scale1, - itemTextureName1 = itemTextureName + itemTextureName1 = itemTextureName, + textureName = "Textures/GUI/Back" }; hoverWindow.Initialize(content); hoverWindow.LoadTexture(content); diff --git a/MonogameLibrary/UI/Elements/ItemDisplayLabel.cs b/MonogameLibrary/UI/Elements/ItemDisplayLabel.cs index c209753..f3e9aca 100644 --- a/MonogameLibrary/UI/Elements/ItemDisplayLabel.cs +++ b/MonogameLibrary/UI/Elements/ItemDisplayLabel.cs @@ -30,6 +30,7 @@ public class ItemDisplayLabel : DrawableUIElement public Dictionary resourcesNeededToCraft1; public HoverState hoverState = HoverState.None; private ContentManager content; + public TextAligment TextAligment = TextAligment.Left; public ItemDisplayLabel(UIManager manager) : base(manager) @@ -47,7 +48,7 @@ public class ItemDisplayLabel : DrawableUIElement Label itemName = new Label(Manager) { rectangle = new Rectangle(rectangle.X + rectangle.Height / 3 / 2 + rectangle.Height / 3 * 2, rectangle.Y + rectangle.Height / 3 / 2, rectangle.Width / 3, rectangle.Height / 3 * 2), - fontColor = fontColor1, text = text1, scale = scale1, fontName = fontName1, mainColor = Color.Transparent + fontColor = fontColor1, text = text1, scale = scale1, fontName = fontName1, mainColor = Color.Transparent, textAligment = TextAligment }; Label itemCount = new Label(Manager) { @@ -110,7 +111,8 @@ public class ItemDisplayLabel : DrawableUIElement fontColor2 = fontColor1, fontName2 = fontName1, scale2 = scale1, - itemTextureName1 = itemTextureName + itemTextureName1 = itemTextureName, + textureName = "Textures/GUI/Back" }; hoverWindow.Initialize(content); hoverWindow.LoadTexture(content); diff --git a/ZoFo/Content/Content.mgcb b/ZoFo/Content/Content.mgcb index 33fcb2f..cc90965 100644 --- a/ZoFo/Content/Content.mgcb +++ b/ZoFo/Content/Content.mgcb @@ -59,6 +59,36 @@ #begin MapData/TileSets/TilesetNature.tsj /copy:MapData/TileSets/TilesetNature.tsj +#begin sounds/Background menu music.wav +/importer:WavImporter +/processor:SoundEffectProcessor +/processorParam:Quality=Best +/build:sounds/Background menu music.wav + +#begin sounds/Background music.wav +/importer:WavImporter +/processor:SoundEffectProcessor +/processorParam:Quality=Best +/build:sounds/Background music.wav + +#begin sounds/Button click.wav +/importer:WavImporter +/processor:SoundEffectProcessor +/processorParam:Quality=Best +/build:sounds/Button click.wav + +#begin sounds/Craft sound.wav +/importer:WavImporter +/processor:SoundEffectProcessor +/processorParam:Quality=Best +/build:sounds/Craft sound.wav + +#begin sounds/gun-gunshot-01.wav +/importer:WavImporter +/processor:SoundEffectProcessor +/processorParam:Quality=Best +/build:sounds/gun-gunshot-01.wav + #begin sounds/Loot.wav /importer:WavImporter /processor:SoundEffectProcessor @@ -101,6 +131,18 @@ /processorParam:Quality=Best /build:sounds/Zombi stoit.wav +#begin sounds/zombie sound 2.wav +/importer:WavImporter +/processor:SoundEffectProcessor +/processorParam:Quality=Best +/build:sounds/zombie sound 2.wav + +#begin sounds/zombie sound.wav +/importer:WavImporter +/processor:SoundEffectProcessor +/processorParam:Quality=Best +/build:sounds/zombie sound.wav + #begin Textures/Animations/player_down_idle.animation /copy:Textures/Animations/player_down_idle.animation @@ -188,6 +230,33 @@ #begin Textures/Animations/player_right_idle.animation /copy:Textures/Animations/player_right_idle.animation +#begin Textures/Animations/player_run_down.animation +/copy:Textures/Animations/player_run_down.animation + +#begin Textures/Animations/player_run_left_down.animation +/copy:Textures/Animations/player_run_left_down.animation + +#begin Textures/Animations/player_run_left_up.animation +/copy:Textures/Animations/player_run_left_up.animation + +#begin Textures/Animations/player_run_left.animation +/copy:Textures/Animations/player_run_left.animation + +#begin Textures/Animations/player_run_right_down.animation +/copy:Textures/Animations/player_run_right_down.animation + +#begin Textures/Animations/player_run_right_up.animation +/copy:Textures/Animations/player_run_right_up.animation + +#begin Textures/Animations/player_run_right.animation +/copy:Textures/Animations/player_run_right.animation + +#begin Textures/Animations/player_run_right.zip +/copy:Textures/Animations/player_run_right.zip + +#begin Textures/Animations/player_run_up.animation +/copy:Textures/Animations/player_run_up.animation + #begin Textures/Animations/player_running_top_rotate.animation /copy:Textures/Animations/player_running_top_rotate.animation @@ -332,6 +401,30 @@ /processorParam:TextureFormat=Color /build:Textures/AnimationTextures/Zombie/zombie_spritesheet_v2.png +#begin Textures/Effects/explosion.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/Effects/explosion.png + +#begin Textures/GUI/back.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/back.png + #begin Textures/GUI/background/base.png /importer:TextureImporter /processor:TextureProcessor @@ -415,8 +508,20 @@ /processorParam:MakeSquare=False /processorParam:TextureFormat=Color /build:Textures/GUI/background/waiting.png + +#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-on.png +#begin Textures/GUI/Button.png /importer:TextureImporter /processor:TextureProcessor /processorParam:ColorKeyColor=255,0,255,255 @@ -426,7 +531,31 @@ /processorParam:ResizeToPowerOfTwo=False /processorParam:MakeSquare=False /processorParam:TextureFormat=Color -/build:Textures/GUI/checkboxs_off-on.png +/build:Textures/GUI/Button.png + +#begin Textures/GUI/Button2.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/Button2.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_off.png /importer:TextureImporter diff --git a/ZoFo/Content/Textures/Animations/player_down-left_idle.animation b/ZoFo/Content/Textures/Animations/Simple Idles/player_down-left_idle.animation similarity index 100% rename from ZoFo/Content/Textures/Animations/player_down-left_idle.animation rename to ZoFo/Content/Textures/Animations/Simple Idles/player_down-left_idle.animation diff --git a/ZoFo/Content/Textures/Animations/player_down-right_idle.animation b/ZoFo/Content/Textures/Animations/Simple Idles/player_down-right_idle.animation similarity index 100% rename from ZoFo/Content/Textures/Animations/player_down-right_idle.animation rename to ZoFo/Content/Textures/Animations/Simple Idles/player_down-right_idle.animation diff --git a/ZoFo/Content/Textures/Animations/player_down_idle.animation b/ZoFo/Content/Textures/Animations/Simple Idles/player_down_idle.animation similarity index 100% rename from ZoFo/Content/Textures/Animations/player_down_idle.animation rename to ZoFo/Content/Textures/Animations/Simple Idles/player_down_idle.animation diff --git a/ZoFo/Content/Textures/Animations/player_left_idle.animation b/ZoFo/Content/Textures/Animations/Simple Idles/player_left_idle.animation similarity index 100% rename from ZoFo/Content/Textures/Animations/player_left_idle.animation rename to ZoFo/Content/Textures/Animations/Simple Idles/player_left_idle.animation diff --git a/ZoFo/Content/Textures/Animations/player_right_idle.animation b/ZoFo/Content/Textures/Animations/Simple Idles/player_right_idle.animation similarity index 100% rename from ZoFo/Content/Textures/Animations/player_right_idle.animation rename to ZoFo/Content/Textures/Animations/Simple Idles/player_right_idle.animation diff --git a/ZoFo/Content/Textures/Animations/player_top-left_idle.animation b/ZoFo/Content/Textures/Animations/Simple Idles/player_top-left_idle.animation similarity index 100% rename from ZoFo/Content/Textures/Animations/player_top-left_idle.animation rename to ZoFo/Content/Textures/Animations/Simple Idles/player_top-left_idle.animation diff --git a/ZoFo/Content/Textures/Animations/player_top-right_idle.animation b/ZoFo/Content/Textures/Animations/Simple Idles/player_top-right_idle.animation similarity index 100% rename from ZoFo/Content/Textures/Animations/player_top-right_idle.animation rename to ZoFo/Content/Textures/Animations/Simple Idles/player_top-right_idle.animation diff --git a/ZoFo/Content/Textures/Animations/explosion_1.animation b/ZoFo/Content/Textures/Animations/explosion_1.animation new file mode 100644 index 0000000..da9528f --- /dev/null +++ b/ZoFo/Content/Textures/Animations/explosion_1.animation @@ -0,0 +1 @@ +{"id":"explosion_1","textureName":"Textures/Effects/explosion","startSpriteRectangle":{"X":0,"Y":0,"Width":100,"Height":100},"frameSecond":[{"Item1":0,"Item2":1}],"textureFrameInterval":0,"framesCount":33,"isCycle":false,"offset":"0, 0"} diff --git a/ZoFo/Content/Textures/Animations/player_run_down.animation b/ZoFo/Content/Textures/Animations/player_run_down.animation new file mode 100644 index 0000000..6dfae3f --- /dev/null +++ b/ZoFo/Content/Textures/Animations/player_run_down.animation @@ -0,0 +1 @@ +{"id":"player_run_down","textureName":"Textures/AnimationTextures/Character/hr-level1_running","startSpriteRectangle":{"X":0,"Y":528,"Width":88,"Height":132},"frameSecond":[{"Item1":0,"Item2":2}],"textureFrameInterval":0,"framesCount":22,"isCycle":true,"offset":"0, 0"} diff --git a/ZoFo/Content/Textures/Animations/player_run_left.animation b/ZoFo/Content/Textures/Animations/player_run_left.animation new file mode 100644 index 0000000..382a37c --- /dev/null +++ b/ZoFo/Content/Textures/Animations/player_run_left.animation @@ -0,0 +1 @@ +{"id":"player_run_left","textureName":"Textures/AnimationTextures/Character/hr-level1_running","startSpriteRectangle":{"X":0,"Y":792,"Width":88,"Height":132},"frameSecond":[{"Item1":0,"Item2":2}],"textureFrameInterval":0,"framesCount":22,"isCycle":true,"offset":"0, 0"} diff --git a/ZoFo/Content/Textures/Animations/player_run_left_down.animation b/ZoFo/Content/Textures/Animations/player_run_left_down.animation new file mode 100644 index 0000000..4fc1ba6 --- /dev/null +++ b/ZoFo/Content/Textures/Animations/player_run_left_down.animation @@ -0,0 +1 @@ +{"id":"player_run_left_down","textureName":"Textures/AnimationTextures/Character/hr-level1_running","startSpriteRectangle":{"X":0,"Y":660,"Width":88,"Height":132},"frameSecond":[{"Item1":0,"Item2":2}],"textureFrameInterval":0,"framesCount":22,"isCycle":true,"offset":"0, 0"} diff --git a/ZoFo/Content/Textures/Animations/player_run_left_up.animation b/ZoFo/Content/Textures/Animations/player_run_left_up.animation new file mode 100644 index 0000000..2ce06d9 --- /dev/null +++ b/ZoFo/Content/Textures/Animations/player_run_left_up.animation @@ -0,0 +1 @@ +{"id":"player_run_left_up","textureName":"Textures/AnimationTextures/Character/hr-level1_running","startSpriteRectangle":{"X":0,"Y":924,"Width":88,"Height":132},"frameSecond":[{"Item1":0,"Item2":2}],"textureFrameInterval":0,"framesCount":22,"isCycle":true,"offset":"0, 0"} diff --git a/ZoFo/Content/Textures/Animations/player_run_right.animation b/ZoFo/Content/Textures/Animations/player_run_right.animation new file mode 100644 index 0000000..f326ea9 --- /dev/null +++ b/ZoFo/Content/Textures/Animations/player_run_right.animation @@ -0,0 +1 @@ +{"id":"player_run_right","textureName":"Textures/AnimationTextures/Character/hr-level1_running","startSpriteRectangle":{"X":0,"Y":264,"Width":88,"Height":132},"frameSecond":[{"Item1":0,"Item2":2}],"textureFrameInterval":0,"framesCount":22,"isCycle":true,"offset":"0, 0"} diff --git a/ZoFo/Content/Textures/Animations/player_run_right.zip b/ZoFo/Content/Textures/Animations/player_run_right.zip new file mode 100644 index 0000000..ca73be1 Binary files /dev/null and b/ZoFo/Content/Textures/Animations/player_run_right.zip differ diff --git a/ZoFo/Content/Textures/Animations/player_run_right_down.animation b/ZoFo/Content/Textures/Animations/player_run_right_down.animation new file mode 100644 index 0000000..400a15d --- /dev/null +++ b/ZoFo/Content/Textures/Animations/player_run_right_down.animation @@ -0,0 +1 @@ +{"id":"player_run_right_down","textureName":"Textures/AnimationTextures/Character/hr-level1_running","startSpriteRectangle":{"X":0,"Y":396,"Width":88,"Height":132},"frameSecond":[{"Item1":0,"Item2":2}],"textureFrameInterval":0,"framesCount":22,"isCycle":true,"offset":"0, 0"} diff --git a/ZoFo/Content/Textures/Animations/player_run_right_up.animation b/ZoFo/Content/Textures/Animations/player_run_right_up.animation new file mode 100644 index 0000000..2470613 --- /dev/null +++ b/ZoFo/Content/Textures/Animations/player_run_right_up.animation @@ -0,0 +1 @@ +{"id":"player_run_right_up","textureName":"Textures/AnimationTextures/Character/hr-level1_running","startSpriteRectangle":{"X":0,"Y":132,"Width":88,"Height":132},"frameSecond":[{"Item1":0,"Item2":2}],"textureFrameInterval":0,"framesCount":22,"isCycle":true,"offset":"0, 0"} diff --git a/ZoFo/Content/Textures/Animations/player_run_up.animation b/ZoFo/Content/Textures/Animations/player_run_up.animation new file mode 100644 index 0000000..7837205 --- /dev/null +++ b/ZoFo/Content/Textures/Animations/player_run_up.animation @@ -0,0 +1 @@ +{"id":"player_run_up","textureName":"Textures/AnimationTextures/Character/hr-level1_running","startSpriteRectangle":{"X":0,"Y":0,"Width":88,"Height":132},"frameSecond":[{"Item1":0,"Item2":2}],"textureFrameInterval":0,"framesCount":22,"isCycle":true,"offset":"0, 0"} diff --git a/ZoFo/Content/Textures/Animations/zombie_death.animation b/ZoFo/Content/Textures/Animations/zombie_death.animation index 97aaa9c..bb4dab8 100644 --- a/ZoFo/Content/Textures/Animations/zombie_death.animation +++ b/ZoFo/Content/Textures/Animations/zombie_death.animation @@ -1 +1 @@ -{"id":"zombie_death","textureName":"Textures/AnimationTextures/Zombie/zombie_spritesheet_v1","startSpriteRectangle":{"X":0,"Y":96,"Width":32,"Height":32},"frameSecond":[{"Item1":0,"Item2":5}],"textureFrameInterval":0,"framesCount":9,"isCycle":true,"offset":"0, 0"} +{"id":"zombie_death","textureName":"Textures/AnimationTextures/Zombie/zombie_spritesheet_v1","startSpriteRectangle":{"X":0,"Y":96,"Width":32,"Height":32},"frameSecond":[{"Item1":0,"Item2":5}],"textureFrameInterval":0,"framesCount":9,"isCycle":false,"offset":"0, 0"} diff --git a/ZoFo/Content/Textures/Effects/explosion.png b/ZoFo/Content/Textures/Effects/explosion.png new file mode 100644 index 0000000..eb6537f Binary files /dev/null and b/ZoFo/Content/Textures/Effects/explosion.png differ diff --git a/ZoFo/Content/Textures/GUI/Button.png b/ZoFo/Content/Textures/GUI/Button.png new file mode 100644 index 0000000..d1d11e9 Binary files /dev/null and b/ZoFo/Content/Textures/GUI/Button.png differ diff --git a/ZoFo/Content/Textures/GUI/Button2.png b/ZoFo/Content/Textures/GUI/Button2.png new file mode 100644 index 0000000..c8ccc30 Binary files /dev/null and b/ZoFo/Content/Textures/GUI/Button2.png differ diff --git a/ZoFo/Content/Textures/GUI/back.png b/ZoFo/Content/Textures/GUI/back.png new file mode 100644 index 0000000..951ca6c Binary files /dev/null and b/ZoFo/Content/Textures/GUI/back.png differ diff --git a/ZoFo/Content/sounds/Background menu music.wav b/ZoFo/Content/sounds/Background menu music.wav new file mode 100644 index 0000000..ece5b88 Binary files /dev/null and b/ZoFo/Content/sounds/Background menu music.wav differ diff --git a/ZoFo/Content/sounds/Background music.wav b/ZoFo/Content/sounds/Background music.wav new file mode 100644 index 0000000..3b20c6e Binary files /dev/null and b/ZoFo/Content/sounds/Background music.wav differ diff --git a/ZoFo/Content/sounds/Button click.wav b/ZoFo/Content/sounds/Button click.wav new file mode 100644 index 0000000..ee91234 Binary files /dev/null and b/ZoFo/Content/sounds/Button click.wav differ diff --git a/ZoFo/Content/sounds/Craft sound.wav b/ZoFo/Content/sounds/Craft sound.wav new file mode 100644 index 0000000..9ca7686 Binary files /dev/null and b/ZoFo/Content/sounds/Craft sound.wav differ diff --git a/ZoFo/Content/sounds/gun-gunshot-01.wav b/ZoFo/Content/sounds/gun-gunshot-01.wav new file mode 100644 index 0000000..0695eca Binary files /dev/null and b/ZoFo/Content/sounds/gun-gunshot-01.wav differ diff --git a/ZoFo/Content/sounds/zombie sound 2.wav b/ZoFo/Content/sounds/zombie sound 2.wav new file mode 100644 index 0000000..d3df275 Binary files /dev/null and b/ZoFo/Content/sounds/zombie sound 2.wav differ diff --git a/ZoFo/Content/sounds/zombie sound.wav b/ZoFo/Content/sounds/zombie sound.wav new file mode 100644 index 0000000..c4f351d Binary files /dev/null and b/ZoFo/Content/sounds/zombie sound.wav differ diff --git a/ZoFo/GameCore/Client.cs b/ZoFo/GameCore/Client.cs index b7a50c1..1b4fcba 100644 --- a/ZoFo/GameCore/Client.cs +++ b/ZoFo/GameCore/Client.cs @@ -22,10 +22,12 @@ using System.Linq; using System.Web; using ZoFo.GameCore.GUI; using ZoFo.GameCore.GameObjects.Entities.Interactables.Collectables; -using ZoFo.GameCore.GameObjects.MapObjects.StopObjects; -using ZoFo.GameCore.Graphics; +using ZoFo.GameCore.GameObjects.MapObjects.StopObjects; +using ZoFo.GameCore.GameManagers.NetworkManager.SerializableDTO; +using ZoFo.GameCore.Graphics; using Newtonsoft.Json.Linq; using Newtonsoft.Json; +using ZoFo.GameCore.GameManagers.CollisionManager; namespace ZoFo.GameCore { public class Client @@ -40,7 +42,6 @@ namespace ZoFo.GameCore public Client() { networkManager = new ClientNetworkManager(); - networkManager.GetDataSent += OnDataSend; // Подписка на действия инпутменеджера. // Отправляются данные апдейтса с обновлением инпута @@ -48,8 +49,8 @@ namespace ZoFo.GameCore { networkManager.AddData(new UpdateInput() { - InputMovementDirection = AppManager.Instance.InputManager.InputMovementDirection, - InputAttackDirection = AppManager.Instance.InputManager.InputAttackDirection + InputMovementDirection = AppManager.Instance.InputManager.InputMovementDirection.Serialize(), + InputAttackDirection = AppManager.Instance.InputManager.InputAttackDirection.Serialize() }); }; @@ -97,6 +98,21 @@ namespace ZoFo.GameCore List gameObjects = new List(); List players = new List(); List stopObjects = new List(); + List particles = new List(); + + float shakeEffect = 0; + public void AddShaking(float power) + { + shakeEffect += power; + } + public void UpdateShaking() + { + shakeEffect *= 0.99f; + (GraphicsComponent.CameraPosition) += new Microsoft.Xna.Framework.Point( + (int)((Random.Shared.NextDouble() - 0.5) * shakeEffect), + (int)((Random.Shared.NextDouble() - 0.5) * shakeEffect) + ); + } /// /// Клиент должен обнговлять игру анимаций @@ -104,11 +120,15 @@ namespace ZoFo.GameCore /// internal void Update(GameTime gameTime) { + UpdateShaking(); for (int i = 0; i < gameObjects.Count; i++) - { - AppManager.Instance.debugHud.Set("GameTime", gameTime.TotalGameTime.ToString()); + { gameObjects[i].UpdateAnimations(); } + for (int i = 0; i < particles.Count; i++) + { + particles[i].UpdateAnimations(); + } networkManager.SendData();//set to ticks if (myPlayer != null) @@ -119,6 +139,10 @@ namespace ZoFo.GameCore ) ) .ToPoint(); } + public void SendData() + { + networkManager.SendData(); + } internal void Draw(SpriteBatch spriteBatch) { for (int i = 0; i < mapObjects.Count; i++) @@ -127,21 +151,34 @@ namespace ZoFo.GameCore } for (int i = 0; i < stopObjects.Count; i++) { - stopObjects[i].Draw(spriteBatch); + stopObjects[i].Draw(spriteBatch); } for (int i = 0; i < gameObjects.Count; i++) { gameObjects[i].Draw(spriteBatch); } + for (int i = 0; i < particles.Count; i++) + { + particles[i].Draw(spriteBatch); + } + } + internal void UpdatesList(List updates) + { + foreach (var item in updates) + { + GotData(item); + } + } internal void GotData(UpdateData update) { + if (update is UpdateTileCreated) { mapObjects.Add( new MapObject( - (update as UpdateTileCreated).Position, + (update as UpdateTileCreated).Position.GetVector2(), (update as UpdateTileCreated).Size.GetPoint().ToVector2(), (update as UpdateTileCreated).sourceRectangle.GetRectangle(), (update as UpdateTileCreated).tileSetName @@ -151,7 +188,7 @@ namespace ZoFo.GameCore { stopObjects.Add( new StopObject( - (update as UpdateStopObjectCreated).Position, + (update as UpdateStopObjectCreated).Position.GetVector2(), (update as UpdateStopObjectCreated).Size.GetPoint().ToVector2(), (update as UpdateStopObjectCreated).sourceRectangle.GetRectangle(), (update as UpdateStopObjectCreated).tileSetName, @@ -160,36 +197,39 @@ namespace ZoFo.GameCore } else if (update is UpdateGameObjectCreated) { - GameObject created_gameObject; - if((update as UpdateGameObjectCreated).GameObjectType == "Player") + //TODO + Entity created_gameObject; + if ((update as UpdateGameObjectCreated).GameObjectType == "Player") { - created_gameObject = new Player((update as UpdateGameObjectCreated).position); + created_gameObject = new Player((update as UpdateGameObjectCreated).position.GetVector2()); players.Add(created_gameObject as Player); - myPlayer = players[0]; - gameObjects.Add(created_gameObject); - (created_gameObject as Entity).SetIdByClient((update as UpdateGameObjectCreated).IdEntity); - } - else if ((update as UpdateGameObjectCreated).GameObjectType == "Ammo") - gameObjects.Add(new Ammo((update as UpdateGameObjectCreated).position)); - else if ((update as UpdateGameObjectCreated).GameObjectType == "BottleOfWater") - gameObjects.Add(new BottleOfWater((update as UpdateGameObjectCreated).position)); + myPlayer = players[0]; + gameObjects.Add(created_gameObject); + } else { Type t = Type.GetType("ZoFo.GameCore.GameObjects." + (update as UpdateGameObjectCreated).GameObjectType); - GameObject gameObject = Activator.CreateInstance(t, (update as UpdateGameObjectCreated).position) as GameObject; + GameObject gameObject = Activator.CreateInstance(t, (update as UpdateGameObjectCreated).position.GetVector2()) as GameObject; if (gameObject is Entity) (gameObject as Entity).SetIdByClient((update as UpdateGameObjectCreated).IdEntity); gameObjects.Add(gameObject); - } - + } + (gameObjects.Last() as Entity).SetIdByClient((update as UpdateGameObjectCreated).IdEntity); } + else if (update is UpdateGameObjectWithoutIdCreated) + { + Type t = Type.GetType("ZoFo.GameCore.GameObjects." + (update as UpdateGameObjectWithoutIdCreated).GameObjectClassName); + GameObject gameObject = Activator.CreateInstance(t, (update as UpdateGameObjectWithoutIdCreated).position.GetVector2()) as GameObject; + if (gameObject is Particle) + particles.Add(gameObject as Particle); + } else if (update is UpdatePosition) { var ent = FindEntityById(update.IdEntity); if (ent != null) - ent.position = (update as UpdatePosition).NewPosition; + ent.position = (update as UpdatePosition).NewPosition.GetVector2(); } else if (update is UpdateAnimation) { @@ -205,11 +245,65 @@ namespace ZoFo.GameCore if (ent != null) DeleteObject(ent); - } + } else if (update is UpdateGameEnded) { GameEnd(); + } + else if (update is UpdatePlayerParametrs) + { + UpdatePlayerHealth(update as UpdatePlayerParametrs); } + else if (update is UpdateLoot) + { + if ((update as UpdateLoot).quantity == 0) + { + return; + } + var ent = FindEntityById(update.IdEntity); + if (ent != null) + (ent as Player).lootData.AddLoot_Client((update as UpdateLoot).lootName, (update as UpdateLoot).quantity); + } + + } + public void UpdatePlayerHealth(UpdatePlayerParametrs update) + { + + //check on player hp lowered + + if (myPlayer != null) + { + float hpMyPlayerHp = myPlayer.health; + + + var entity = FindEntityById(update.IdEntity); + + if (entity != null) + { + (entity as Player).health = (update as UpdatePlayerParametrs).health; + (entity as Player).rad = (update as UpdatePlayerParametrs).radiatoin; + } + if (entity.Equals(myPlayer)) + { + if (hpMyPlayerHp > myPlayer.health) + { + AppManager.Instance.client.AddShaking((hpMyPlayerHp - myPlayer.health)); + + } + } + + return; + } + + + var ent = FindEntityById(update.IdEntity); + + if (ent != null) + { + (ent as Player).health = (update as UpdatePlayerParametrs).health; + (ent as Player).rad = (update as UpdatePlayerParametrs).radiatoin; + } + } public void GameEnd() @@ -231,7 +325,20 @@ namespace ZoFo.GameCore } return null; } - public void DeleteObject(Entity entity) + + public void DeleteObject(GameObject gameObject) + { + if (gameObject is Entity) + { + DeleteEntity(gameObject as Entity); + } + else if (gameObject is Particle) + { + if (particles.Contains(gameObject)) + particles.Remove(gameObject as Particle); + } + } + public void DeleteEntity(Entity entity) { if (gameObjects.Contains(entity)) diff --git a/ZoFo/GameCore/GUI/AbstractGUI.cs b/ZoFo/GameCore/GUI/AbstractGUI.cs index e8ceb33..6aafbb2 100644 --- a/ZoFo/GameCore/GUI/AbstractGUI.cs +++ b/ZoFo/GameCore/GUI/AbstractGUI.cs @@ -38,7 +38,7 @@ public abstract class AbstractGUI public virtual void LoadContent() { - Manager.LoadContent(AppManager.Instance.Content, "Font"); + Manager.LoadContent(AppManager.Instance.Content, "Fonts/Font"); mouse = AppManager.Instance.Content.Load("Textures/GUI/mouse"); } diff --git a/ZoFo/GameCore/GUI/BaseGUI.cs b/ZoFo/GameCore/GUI/BaseGUI.cs index d46ac63..ed5b58a 100644 --- a/ZoFo/GameCore/GUI/BaseGUI.cs +++ b/ZoFo/GameCore/GUI/BaseGUI.cs @@ -54,14 +54,16 @@ public class BaseGUI : AbstractGUI rectangle = new Rectangle(width / 2 - (height / 16 + (int)(width / 2.5)) / 2, height / 2 - (int)(height / 1.5) / 2, height / 40 + width / 5, (int)(height / 1.5)), - mainColor = Color.LightGray + mainColor = Color.LightGray, + textureName = "Textures/GUI/Back" }; Elements.Add(baseItemBack); DrawableUIElement baseCraftBack = new DrawableUIElement(Manager) { rectangle = new Rectangle(width / 2 + height / 160, height / 2 - (int)(height / 1.5) / 2, height / 40 + width / 5, (int)(height / 1.5)), - mainColor = Color.LightGray + mainColor = Color.LightGray, + textureName = "Textures/GUI/Back" }; Elements.Add(baseCraftBack); @@ -85,7 +87,8 @@ public class BaseGUI : AbstractGUI mainColor = Color.Gray, fontName1 = "Fonts\\Font4", discriptions1 = itemInfo.description, - resourcesNeededToCraft1 = itemInfo.resourcesNeededToCraft + resourcesNeededToCraft1 = itemInfo.resourcesNeededToCraft, + textureName = "Textures/GUI/Button" }; Elements.Add(temp); temp.Initialize(); @@ -134,7 +137,8 @@ public class BaseGUI : AbstractGUI mainColor = Color.Gray, fontName1 = "Fonts\\Font4", discriptions1 = itemInfo.description, - resourcesNeededToCraft1 = itemInfo.resourcesNeededToCraft + resourcesNeededToCraft1 = itemInfo.resourcesNeededToCraft, + textureName = "Textures/GUI/Button" }; Elements.Add(temp); temp.Initialize(); @@ -142,6 +146,7 @@ public class BaseGUI : AbstractGUI ItemDisplayButtonsList.Add(temp); temp.LeftButtonPressed += () => { + AppManager.Instance.SoundManager.StartAmbientSound("Craft sound"); AppManager.Instance.playerData.CraftItem(item.Key); AppManager.Instance.SetGUI(new BaseGUI()); }; @@ -160,10 +165,12 @@ public class BaseGUI : AbstractGUI { fontName = "Fonts\\Font3", scale = 0.4f, text = "<-", fontColor = Color.Black, mainColor = Color.Transparent, rectangle = new Rectangle(width / 30, height / 30, width / 40, width / 40), - textureName = "Textures\\GUI\\checkboxs_off" + textureName = "Textures/GUI/Button2" }; Elements.Add(bTExit); - bTExit.LeftButtonPressed += () => { AppManager.Instance.SetGUI(new MainMenuGUI()); }; + bTExit.LeftButtonPressed += () => { AppManager.Instance.SetGUI(new MainMenuGUI()); + AppManager.Instance.SoundManager.StartAmbientSound("Button click"); + }; } public override void Update(GameTime gameTime) diff --git a/ZoFo/GameCore/GUI/ExitGameGUI.cs b/ZoFo/GameCore/GUI/ExitGameGUI.cs index aca7173..1f14fea 100644 --- a/ZoFo/GameCore/GUI/ExitGameGUI.cs +++ b/ZoFo/GameCore/GUI/ExitGameGUI.cs @@ -36,7 +36,8 @@ public class ExitGameGUI : AbstractGUI scale = 0.3f, fontColor = Color.White, mainColor = Color.Gray, - fontName = "Fonts/Font" + fontName = "Fonts/Font", + textureName = "Textures/GUI/Button" }; endButton.LeftButtonPressed += () => { diff --git a/ZoFo/GameCore/GUI/FinishingGUI.cs b/ZoFo/GameCore/GUI/FinishingGUI.cs index e437e3d..cef6a5c 100644 --- a/ZoFo/GameCore/GUI/FinishingGUI.cs +++ b/ZoFo/GameCore/GUI/FinishingGUI.cs @@ -38,7 +38,8 @@ public class FinishingGUI : AbstractGUI rectangle = new Rectangle(width / 2 - height / 80 - width / 5 / 2, height / 2 - (int)(height / 1.5) / 2, height / 40 + width / 5, (int)(height / 1.5)), - mainColor = Color.LightGray + mainColor = Color.LightGray, + textureName = "Textures/GUI/Back" }; Elements.Add(inventoryBack); @@ -50,7 +51,8 @@ public class FinishingGUI : AbstractGUI scale = 0.2f, fontColor = Color.White, mainColor = Color.Gray, - fontName = "Fonts\\Font" + fontName = "Fonts\\Font", + textureName = "Textures/GUI/Button" }; ExitButton.LeftButtonPressed += () => { AppManager.Instance.SetGUI(new MainMenuGUI()); }; Elements.Add(ExitButton); diff --git a/ZoFo/GameCore/GUI/GameEndedGUI.cs b/ZoFo/GameCore/GUI/GameEndedGUI.cs index abd5835..14bcd68 100644 --- a/ZoFo/GameCore/GUI/GameEndedGUI.cs +++ b/ZoFo/GameCore/GUI/GameEndedGUI.cs @@ -36,7 +36,8 @@ public class GameEndedGUI : AbstractGUI scale = 0.3f, fontColor = Color.White, mainColor = Color.Gray, - fontName = "Fonts/Font" + fontName = "Fonts/Font", + textureName = "Textures/GUI/Button" }; endButton.LeftButtonPressed += () => { diff --git a/ZoFo/GameCore/GUI/HUD.cs b/ZoFo/GameCore/GUI/HUD.cs index 9a88a71..d774554 100644 --- a/ZoFo/GameCore/GUI/HUD.cs +++ b/ZoFo/GameCore/GUI/HUD.cs @@ -17,25 +17,37 @@ public class HUD : AbstractGUI { private Bar hpBar; private Bar radBar; - private AbstractGUI overlayGUI; + public AbstractGUI overlayGUI; protected override void CreateUI() { int width = AppManager.Instance.CurentScreenResolution.X; int height = AppManager.Instance.CurentScreenResolution.Y; - Button pauseButton = new Button(Manager) - { fontName = "Fonts\\Font3", scale = 0.4f, text = "| |", fontColor = Color.Black, mainColor = Color.Transparent, rectangle = new Rectangle(width - width / 30 - width / 40, height / 30, width / 40, width / 40), textureName = "Textures\\GUI\\checkboxs_off"}; - Elements.Add(pauseButton); - pauseButton.LeftButtonPressed += () => + Button pauseButton = new Button(Manager) { - AppManager.Instance.SetGUI(new FinishingGUI()); - //overlayGUI = new PauseGUI(); - //overlayGUI.Initialize(); - //overlayGUI.LoadContent(); + fontName = "Fonts\\Font3", scale = 0.4f, text = "| |", fontColor = Color.Black, + mainColor = Color.Transparent, rectangle = new Rectangle(width - width / 30 - width / 40, height / 30, width / 40, width / 40), + textureName = "Textures/GUI/Button2" + }; + Elements.Add(pauseButton); + pauseButton.LoadTexture(AppManager.Instance.Content); + pauseButton.LeftButtonPressed += () => + { + AppManager.Instance.SoundManager.StartAmbientSound("Button click"); + AppManager.Instance.SetGUI(new PauseGUI()); + //AppManager.Instance.SetGUI(new FinishingGUI()); + overlayGUI = new PauseGUI(); + overlayGUI.Initialize(); + overlayGUI.LoadContent(); }; - Button invButton = new Button(Manager) - { fontName = "Fonts\\Font3", scale = 0.4f, text = "inv", fontColor = Color.Black, mainColor = Color.Transparent, rectangle = new Rectangle(width - width / 30 - width / 40, height / 15 + width / 40, width / 40, width / 40), textureName = "Textures\\GUI\\checkboxs_off"}; + Button invButton = new Button(Manager) + { + fontName = "Fonts\\Font3", scale = 0.4f, text = "inv", fontColor = Color.Black, + mainColor = Color.Transparent, rectangle = new Rectangle(width - width / 30 - width / 40, height / 15 + width / 40, width / 40, width / 40), + textureName = "Textures/GUI/Button2" + }; Elements.Add(invButton); + invButton.LoadTexture(AppManager.Instance.Content); invButton.LeftButtonPressed += () => { overlayGUI = new InventoryGUI(); @@ -63,12 +75,18 @@ public class HUD : AbstractGUI radBar.LoadTexture(AppManager.Instance.Content); } + public override void Update(GameTime gameTime) { overlayGUI?.Update(gameTime); //hpBar.Update(gameTime, AppManager.Instance.client.myPlayer.health / 100f); //radBar.Update(gameTime, AppManager.Instance.client.myPlayer.rad / 100f); - radBar.Update(gameTime, gameTime.TotalGameTime.Seconds / 100f); + if (AppManager.Instance.client.myPlayer != null) + { + radBar.Update(gameTime, AppManager.Instance.client.myPlayer.rad / AppManager.Instance.client.myPlayer.MaxRad); + hpBar.Update(gameTime, AppManager.Instance.client.myPlayer.health / AppManager.Instance.client.myPlayer.MaxHealth); + + } base.Update(gameTime); } diff --git a/ZoFo/GameCore/GUI/InventoryGUI.cs b/ZoFo/GameCore/GUI/InventoryGUI.cs index c20be82..feeb0af 100644 --- a/ZoFo/GameCore/GUI/InventoryGUI.cs +++ b/ZoFo/GameCore/GUI/InventoryGUI.cs @@ -31,7 +31,8 @@ public class InventoryGUI : AbstractGUI rectangle = new Rectangle(width / 2 - height / 80 - width / 5 / 2, height / 2 - (int)(height / 1.5) / 2 - height / 10, height / 40 + width / 5, (int)(height / 1.5)), - mainColor = Color.LightGray + mainColor = Color.LightGray, + textureName = "Textures/GUI/Back" }; Elements.Add(inventoryBack); @@ -43,7 +44,8 @@ public class InventoryGUI : AbstractGUI scale = 0.2f, fontColor = Color.White, mainColor = Color.Gray, - fontName = "Fonts\\Font" + fontName = "Fonts\\Font", + textureName = "Textures/GUI/Button" }; continueButton.LeftButtonPressed += () => { AppManager.Instance.SetGUI(new HUD()); }; Elements.Add(continueButton); @@ -62,14 +64,15 @@ public class InventoryGUI : AbstractGUI (height / 20 + height / 80) * (buttonIndex) - height / 10, (int)(width / 5), (int)(height / 20)), text1 = item.Key, - scale1 = 0.4f, + scale1 = 0.3f, count = item.Value, itemTextureName = itemInfo.textureName, fontColor1 = Color.White, mainColor = Color.Gray, fontName1 = "Fonts\\Font4", discriptions1 = itemInfo.description, - resourcesNeededToCraft1 = itemInfo.resourcesNeededToCraft + resourcesNeededToCraft1 = itemInfo.resourcesNeededToCraft, + textureName = "Texturs/GUI/Button" }; Elements.Add(temp); temp.Initialize(); diff --git a/ZoFo/GameCore/GUI/MainMenuGUI.cs b/ZoFo/GameCore/GUI/MainMenuGUI.cs index 645faf8..11adcbb 100644 --- a/ZoFo/GameCore/GUI/MainMenuGUI.cs +++ b/ZoFo/GameCore/GUI/MainMenuGUI.cs @@ -36,11 +36,12 @@ public class MainMenuGUI : AbstractGUI scale = 0.2f, fontColor = Color.White, mainColor = Color.Gray, - fontName = "Fonts/Font" + fontName = "Fonts/Font", + textureName = "Textures/GUI/Button" }; playButton.LeftButtonPressed += () => { - AppManager.Instance.SoundManager.StartAmbientSound("Loot"); + AppManager.Instance.SoundManager.StartAmbientSound("Button click"); AppManager.Instance.SetGUI(new SelectModeMenu()); }; Elements.Add(playButton); @@ -51,10 +52,12 @@ public class MainMenuGUI : AbstractGUI scale = 0.2f, fontColor = Color.White, mainColor = Color.Gray, - fontName = "Fonts\\Font" + fontName = "Fonts\\Font", + textureName = "Textures/GUI/Button" }; baseButton.LeftButtonPressed += () => { + AppManager.Instance.SoundManager.StartAmbientSound("Button click"); AppManager.Instance.SetGUI(new BaseGUI()); }; Elements.Add(baseButton); @@ -65,11 +68,12 @@ public class MainMenuGUI : AbstractGUI scale = 0.2f, fontColor = Color.White, mainColor = Color.Gray, - fontName = "Fonts/Font" + fontName = "Fonts/Font", + textureName = "Textures/GUI/Button" }; optionButton.LeftButtonPressed += () => { - AppManager.Instance.SoundManager.StartAmbientSound("Loot"); + AppManager.Instance.SoundManager.StartAmbientSound("Button click"); AppManager.Instance.SetGUI(new OptionsGUI()); }; Elements.Add(optionButton); @@ -80,7 +84,8 @@ public class MainMenuGUI : AbstractGUI scale = 0.2f, fontColor = Color.White, mainColor = Color.Gray, - fontName = "Fonts/Font" + fontName = "Fonts/Font", + textureName = "Textures/GUI/Button" }; exitButton.LeftButtonPressed += () => { diff --git a/ZoFo/GameCore/GUI/OptionsGUI.cs b/ZoFo/GameCore/GUI/OptionsGUI.cs index 39db371..7221971 100644 --- a/ZoFo/GameCore/GUI/OptionsGUI.cs +++ b/ZoFo/GameCore/GUI/OptionsGUI.cs @@ -43,6 +43,7 @@ public class OptionsGUI : AbstractGUI label_OverallVolume_Percent.text = Math.Round(slider_OverallVolume.GetSliderValue * 100) + "%"; slider_OverallVolume.SliderChanged += (newVal) => { + label_OverallVolume_Percent.text = Math.Round(slider_OverallVolume.GetSliderValue * 100) + "%"; AppManager.Instance.SettingsManager.SetMainVolume(newVal); }; @@ -64,6 +65,7 @@ public class OptionsGUI : AbstractGUI label_MusicVolume_Percent.text = Math.Round(slider_MusicVolume.GetSliderValue * 100) + "%"; slider_MusicVolume.SliderChanged += (newVal) => { + label_MusicVolume_Percent.text = Math.Round(slider_MusicVolume.GetSliderValue * 100) + "%"; AppManager.Instance.SettingsManager.SetMusicVolume(newVal); }; @@ -85,6 +87,7 @@ public class OptionsGUI : AbstractGUI label_EffectsVolume_Percent.text = Math.Round(slider_EffectsVolume.GetSliderValue * 100) + "%"; slider_EffectsVolume.SliderChanged += (newVal) => { + label_EffectsVolume_Percent.text = Math.Round(slider_EffectsVolume.GetSliderValue * 100) + "%"; AppManager.Instance.SettingsManager.SetSoundEffectsVolume(newVal); }; @@ -109,6 +112,7 @@ public class OptionsGUI : AbstractGUI button_FullScreen.SetIsChecked(AppManager.Instance.SettingsManager.IsFullScreen); button_FullScreen.Checked += (newCheckState) => { + AppManager.Instance.SoundManager.StartAmbientSound("Button click"); AppManager.Instance.SettingsManager.SetIsFullScreen(newCheckState); }; Elements.Add(button_FullScreen); @@ -116,10 +120,15 @@ public class OptionsGUI : AbstractGUI //-------------------------------------- Button bTExit = new Button(Manager) - { fontName = "Fonts/Font3", scale = 0.4f, text = "<-", fontColor = Color.Black, mainColor = Color.Transparent, rectangle = new Rectangle(width / 30, height / 30, width / 40, width / 40), textureName = "Textures/GUI/checkboxs_off"}; + { + fontName = "Fonts/Font3", scale = 0.4f, text = "<-", fontColor = Color.Black, mainColor = Color.Transparent, + rectangle = new Rectangle(width / 30, height / 30, width / 40, width / 40), + textureName = "Textures/GUI/Button2" + }; Elements.Add(bTExit); bTExit.LeftButtonPressed += () => { + AppManager.Instance.SoundManager.StartAmbientSound("Button click"); AppManager.Instance.SetGUI(new MainMenuGUI()); }; diff --git a/ZoFo/GameCore/GUI/PauseGUI.cs b/ZoFo/GameCore/GUI/PauseGUI.cs index d316fb7..1e3c7fd 100644 --- a/ZoFo/GameCore/GUI/PauseGUI.cs +++ b/ZoFo/GameCore/GUI/PauseGUI.cs @@ -27,10 +27,12 @@ public class PauseGUI : AbstractGUI scale = 0.2f, fontColor = Color.White, mainColor = Color.Gray, - fontName = "Fonts\\Font" + fontName = "Fonts\\Font", + textureName = "Textures/GUI/Button" }; continueButton.LeftButtonPressed += () => { + AppManager.Instance.SoundManager.StartAmbientSound("Button click"); AppManager.Instance.SetGUI(new HUD()); }; Elements.Add(continueButton); @@ -41,10 +43,14 @@ public class PauseGUI : AbstractGUI scale = 0.2f, fontColor = Color.White, mainColor = Color.Gray, - fontName = "Fonts\\Font" + fontName = "Fonts\\Font", + textureName = "Textures/GUI/Button" }; exitButton.LeftButtonPressed += () => { + AppManager.Instance.SoundManager.StopAllSounds(); + AppManager.Instance.SoundManager.StartAmbientSound("Button click"); + AppManager.Instance.SoundManager.StartAmbientSound("Background menu music"); AppManager.Instance.SetGUI(new MainMenuGUI()); }; Elements.Add(exitButton); diff --git a/ZoFo/GameCore/GUI/SelectModeMenu.cs b/ZoFo/GameCore/GUI/SelectModeMenu.cs index 5b1320b..b4ee1e0 100644 --- a/ZoFo/GameCore/GUI/SelectModeMenu.cs +++ b/ZoFo/GameCore/GUI/SelectModeMenu.cs @@ -34,18 +34,22 @@ public class SelectModeMenu : AbstractGUI scale = 0.3f, fontColor = Color.White, mainColor = Color.Gray, - fontName = "Fonts/Font" + fontName = "Fonts/Font", + textureName = "Textures/GUI/Button" }; singleButton.LeftButtonPressed += () => { + AppManager.Instance.SoundManager.StopAllSounds(); + AppManager.Instance.SoundManager.StartAmbientSound("Background music"); + AppManager.Instance.SoundManager.StartAmbientSound("Button click"); // single Server server = new Server(); Client client = new Client(); - server.CreateRoom(1); - client.JoinYourself(server.MyIp.Port); AppManager.Instance.SetServer(server); AppManager.Instance.SetClient(client); - AppManager.Instance.ChangeState(GameState.HostPlaying); + server.CreateRoom(false); + client.JoinYourself(server.MyIp.Port); + //AppManager.Instance.ChangeState(GameState.HostPlaying); AppManager.Instance.SetGUI(new HUD()); //server.CreateRoom(1); @@ -64,10 +68,12 @@ public class SelectModeMenu : AbstractGUI scale = 0.3f, fontColor = Color.White, mainColor = Color.Gray, - fontName = "Fonts/Font" + fontName = "Fonts/Font", + textureName = "Textures/GUI/Button" }; optionButton.LeftButtonPressed += () => { + AppManager.Instance.SoundManager.StartAmbientSound("Button click"); AppManager.Instance.SetGUI(new SelectingServerGUI()); // multi @@ -76,10 +82,17 @@ public class SelectModeMenu : AbstractGUI Elements.Add(optionButton); Button bTExit = new Button(Manager) - { fontName = "Fonts/Font3", scale = 0.4f, text = "<-", fontColor = Color.Black, mainColor = Color.Transparent, rectangle = new Rectangle(width / 30, height / 30, width / 40, width / 40), textureName = "Textures/GUI/checkboxs_off"}; + { + fontName = "Fonts/Font3", scale = 0.4f, text = "<-", fontColor = Color.Black, mainColor = Color.Transparent, + rectangle = new Rectangle(width / 30, height / 30, width / 40, width / 40), + textureName = "Textures/GUI/Button2" + }; Elements.Add(bTExit); bTExit.LeftButtonPressed += () => { + + AppManager.Instance.SoundManager.StartAmbientSound("Button click"); + AppManager.Instance.SetGUI(new MainMenuGUI()); }; } diff --git a/ZoFo/GameCore/GUI/SelectingServerGUI.cs b/ZoFo/GameCore/GUI/SelectingServerGUI.cs index 9460341..f2e267c 100644 --- a/ZoFo/GameCore/GUI/SelectingServerGUI.cs +++ b/ZoFo/GameCore/GUI/SelectingServerGUI.cs @@ -36,7 +36,8 @@ public class SelectingServerGUI : AbstractGUI fontColor = Color.White, mainColor = Color.Gray, textAligment = MonogameLibrary.UI.Enums.TextAligment.Left, - fontName = "Fonts/Font3" + fontName = "Fonts/Font3", + textureName = "Textures/GUI/Button" }; ipBox.TextChanged += input => { @@ -61,7 +62,8 @@ public class SelectingServerGUI : AbstractGUI scale = 0.3f, fontColor = Color.White, mainColor = Color.Gray, - fontName = "Fonts/Font" + fontName = "Fonts/Font", + textureName = "Textures/GUI/Button" }; joinButton.LeftButtonPressed += () => { @@ -74,6 +76,7 @@ public class SelectingServerGUI : AbstractGUI { if (int.TryParse(endpoint[1], out port)) { + client.JoinRoom(endpoint[0], port); AppManager.Instance.SetClient(client); AppManager.Instance.SetGUI(new WaitingForPlayersGUI(false)); @@ -95,7 +98,8 @@ public class SelectingServerGUI : AbstractGUI scale = 0.3f, fontColor = Color.White, mainColor = Color.Gray, - fontName = "Fonts/Font" + fontName = "Fonts/Font", + textureName = "Textures/GUI/Button" }; hostButton.LeftButtonPressed += () => { @@ -103,10 +107,10 @@ public class SelectingServerGUI : AbstractGUI // host Server server = new Server(); //Server Logic MultiPlayer Client client = new Client(); - server.CreateRoom(2); - client.JoinYourself(server.MyIp.Port); AppManager.Instance.SetServer(server); AppManager.Instance.SetClient(client); + server.CreateRoom(true); + client.JoinYourself(server.MyIp.Port); string key = server.MyIp.ToString(); AppManager.Instance.debugHud.Set(key, "MultiPlayer"); // ваш код здесь @@ -115,7 +119,11 @@ public class SelectingServerGUI : AbstractGUI Elements.Add(hostButton); Button bTExit = new Button(Manager) - { fontName = "Fonts/Font3", scale = 0.4f, text = "<-", fontColor = Color.Black, mainColor = Color.Transparent, rectangle = new Rectangle(width / 30, height / 30, width / 40, width / 40), textureName = "Textures/GUI/checkboxs_off" }; + { + fontName = "Fonts/Font3", scale = 0.4f, text = "<-", fontColor = Color.Black, mainColor = Color.Transparent, + rectangle = new Rectangle(width / 30, height / 30, width / 40, width / 40), + textureName = "Textures/GUI/Button2" + }; Elements.Add(bTExit); bTExit.LeftButtonPressed += () => { diff --git a/ZoFo/GameCore/GUI/WaitingForPlayersGUI.cs b/ZoFo/GameCore/GUI/WaitingForPlayersGUI.cs index 2764fb1..94bde56 100644 --- a/ZoFo/GameCore/GUI/WaitingForPlayersGUI.cs +++ b/ZoFo/GameCore/GUI/WaitingForPlayersGUI.cs @@ -34,8 +34,8 @@ public class WaitingForPlayersGUI : AbstractGUI // string pcIp = // string pcIp = - ip = new Label(Manager) { rectangle = new Rectangle(width / 2 - (int)(width / 8), height / 7, (int)(width / 4), (int)(height / 20)), text = AppManager.Instance.server.MyIp.ToString(), fontColor = Color.White, mainColor = Color.Transparent, scale = 0.9f, fontName = "Fonts/Font3" }; - Elements.Add(ip); + // ip = new Label(Manager) { rectangle = new Rectangle(width / 2 - (int)(width / 8), height / 7, (int)(width / 4), (int)(height / 20)), text = AppManager.Instance.server.MyIp.ToString(), fontColor = Color.White, mainColor = Color.Transparent, scale = 0.9f, fontName = "Fonts/Font3" }; + // Elements.Add(ip); if (isHost) { ip = new Label(Manager) { rectangle = new Rectangle(width / 2 - (int)(width / 8), height / 7, (int)(width / 4), (int)(height / 20)), text = AppManager.Instance.server.MyIp.ToString(), fontColor = Color.White, mainColor = Color.Transparent, scale = 0.9f, fontName = "Fonts\\Font3" }; @@ -47,12 +47,13 @@ public class WaitingForPlayersGUI : AbstractGUI scale = 0.3f, fontColor = Color.White, mainColor = Color.Gray, - fontName = "Fonts/Font" + fontName = "Fonts/Font", + textureName = "Textures/GUI/Button" }; startButton.LeftButtonPressed += () => { // start - AppManager.Instance.ChangeState(GameState.HostPlaying); + AppManager.Instance.server.StartGame(); // ваш код здесь }; Elements.Add(startButton); @@ -67,19 +68,24 @@ public class WaitingForPlayersGUI : AbstractGUI scale = 0.3f, fontColor = Color.White, mainColor = Color.Gray, - fontName = "Fonts/Font" + fontName = "Fonts/Font", + textureName = "Textures/GUI/Button" }; waitButton.LeftButtonPressed += () => { // start - AppManager.Instance.ChangeState(GameState.ClientPlaying); + AppManager.Instance.SetGUI(new HUD()); // ваш код здесь }; Elements.Add(waitButton); } Button bTExit = new Button(Manager) - { fontName = "Fonts/Font3", scale = 0.4f, text = "<-", fontColor = Color.Black, mainColor = Color.Transparent, rectangle = new Rectangle(width / 30, height / 30, width / 40, width / 40), textureName = "Textures/GUI/checkboxs_off"}; + { + fontName = "Fonts/Font3", scale = 0.4f, text = "<-", fontColor = Color.Black, mainColor = Color.Transparent, + rectangle = new Rectangle(width / 30, height / 30, width / 40, width / 40), + textureName = "Textures/GUI/Button2" + }; Elements.Add(bTExit); bTExit.LeftButtonPressed += () => { diff --git a/ZoFo/GameCore/GameManagers/AppManager.cs b/ZoFo/GameCore/GameManagers/AppManager.cs index db6bcf0..1f657cd 100644 --- a/ZoFo/GameCore/GameManagers/AppManager.cs +++ b/ZoFo/GameCore/GameManagers/AppManager.cs @@ -62,12 +62,14 @@ namespace ZoFo.GameCore.GameManagers ItemManager = new ItemManager.ItemManager(); Instance = this; InputManager = new InputManager(); + SoundManager = new SoundManager(); + SoundManager.LoadSounds(); SettingsManager = new SettingsManager(); SettingsManager.LoadSettings(); - SoundManager = new SoundManager(); + AssetManager = new AssetManager(); - SoundManager.LoadSounds(); - + + SoundManager.StartAmbientSound("Background menu music"); currentGUI = new MainMenuGUI(); debugHud = new DebugHUD(); @@ -103,8 +105,8 @@ namespace ZoFo.GameCore.GameManagers protected override void Update(GameTime gameTime) { - if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || - Keyboard.GetState().IsKeyDown(Keys.Escape)) { server?.CloseConnection(); Exit(); } + if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || + Keyboard.GetState().IsKeyDown(Keys.Escape)) { Exit(); } // debugHud.Set("key", "value"); @@ -139,6 +141,8 @@ namespace ZoFo.GameCore.GameManagers switch (gamestate) { case GameState.ClientPlaying: + client.Draw(_spriteBatch); + break; case GameState.HostPlaying: client.Draw(_spriteBatch); break; diff --git a/ZoFo/GameCore/GameManagers/AssetsManager/AssetManager.cs b/ZoFo/GameCore/GameManagers/AssetsManager/AssetManager.cs index 334957f..5fd12ba 100644 --- a/ZoFo/GameCore/GameManagers/AssetsManager/AssetManager.cs +++ b/ZoFo/GameCore/GameManagers/AssetsManager/AssetManager.cs @@ -12,7 +12,9 @@ public class AssetManager public AssetContainer Player = new() { - Animations = [ "player_look_down" ], + Animations = [ "player_look_down", "player_run_up", "player_run_down", "player_run_right", + "player_run_left", "player_run_right_up", "player_run_left_up", "player_run_right_down", + "player_run_left_down" ], IdleAnimation = "player_look_down" }; } \ No newline at end of file diff --git a/ZoFo/GameCore/GameManagers/CollisionManager/CollisionManager.cs b/ZoFo/GameCore/GameManagers/CollisionManager/CollisionManager.cs index 513c6ae..234e912 100644 --- a/ZoFo/GameCore/GameManagers/CollisionManager/CollisionManager.cs +++ b/ZoFo/GameCore/GameManagers/CollisionManager/CollisionManager.cs @@ -10,9 +10,11 @@ using Microsoft.Xna.Framework; using ZoFo.GameCore.GameManagers.MapManager.MapElements; using ZoFo.GameCore.GameObjects.Entities; using ZoFo.GameCore.GameObjects.Entities.LivingEntities; + using ZoFo.GameCore.GameManagers.NetworkManager.Updates.ServerToClient; -using ZoFo.GameCore.Graphics; -using ZoFo.GameCore.GameObjects.Entities.LivingEntities.Player; +using ZoFo.GameCore.Graphics; +using ZoFo.GameCore.GameManagers.NetworkManager.SerializableDTO; +using ZoFo.GameCore.GameObjects.Entities.LivingEntities.Player; namespace ZoFo.GameCore.GameManagers.CollisionManager { @@ -23,8 +25,27 @@ namespace ZoFo.GameCore.GameManagers.CollisionManager public List ObjectsWithCollisions; public List EntitiesWithMovements; public List ObjectsWithTriggers; + + public List GetEntitiesToUpdate(Player player) + { + float ViewDistance = 500; + List EntitiesInPlayerArea = new List(); + Rectangle ViewArea = new Rectangle((int)(player.position.X), (int)(player.position.Y), + (int)(ViewDistance), (int)(ViewDistance)); + + for (int i = 0; i < ObjectsWithCollisions.Count; i++) + { + if (ViewArea.Contains((float)ObjectsWithCollisions[i].gameObject.position.X, (float)ObjectsWithCollisions[i].gameObject.position.Y)); + { + EntitiesInPlayerArea.Add(ObjectsWithCollisions[i]); + } + } + return EntitiesInPlayerArea; + } + + //чекаем коллизии в листе /// @@ -124,7 +145,7 @@ namespace ZoFo.GameCore.GameManagers.CollisionManager entity.graphicsComponent.ObjectDrawRectangle.X = (int)entity.position.X; entity.graphicsComponent.ObjectDrawRectangle.Y = (int)entity.position.Y; - AppManager.Instance.server.AddData(new UpdatePosition() { NewPosition = entity.position, IdEntity = entity.Id }); + AppManager.Instance.server.AddData(new UpdatePosition() { NewPosition = new SerializableVector2(entity.position), IdEntity = entity.Id }); AppManager.Instance.debugHud.Set("testPos", entity.position.ToString()); //TODO remove } @@ -233,6 +254,12 @@ namespace ZoFo.GameCore.GameManagers.CollisionManager rectangle.Y += (int)origin.Y; return rectangle; } + public static SerializableVector2 Serialize(this Vector2 vector) => new SerializableVector2(vector); + public static Vector2 RandomVector() + { + return new Vector2((float)Random.Shared.NextDouble() - 0.5f, (float)Random.Shared.NextDouble() - 0.5f); + } + } } diff --git a/ZoFo/GameCore/GameManagers/InputManager.cs b/ZoFo/GameCore/GameManagers/InputManager.cs index 2524e5a..e6079b2 100644 --- a/ZoFo/GameCore/GameManagers/InputManager.cs +++ b/ZoFo/GameCore/GameManagers/InputManager.cs @@ -5,18 +5,11 @@ using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; -using System.Formats.Tar; -using System.Linq; -using System.Reflection.Metadata.Ecma335; -using System.Security.Cryptography.X509Certificates; -using System.Text; -using System.Threading.Tasks; using ZoFo.GameCore.GUI; namespace ZoFo.GameCore.GameManagers { public enum ScopeState { Idle, Left, Right, Top, Down, TopLeft, TopRight, DownLeft, DownRight } - public class InputManager { public event Action ShootEvent; // событие удара(когда нажат X, событие срабатывает) @@ -40,6 +33,7 @@ namespace ZoFo.GameCore.GameManagers private bool isInteract; private KeyboardState lastKeyboardState; + private KeyboardState keyBoardState; private GamePadState lastGamePadState; public ScopeState ScopeState { get => currentScopeState; } public string currentControlsState; @@ -161,13 +155,13 @@ namespace ZoFo.GameCore.GameManagers #endregion #region Обработка нажатия выстрела. Вызывает событие ShootEvent - if (keyBoardState.IsKeyDown(Keys.P) && !isShoot) + if ((keyBoardState.IsKeyDown(Keys.P) || keyBoardState.IsKeyDown(Keys.F)) && !isShoot) { isShoot = true; ShootEvent?.Invoke(); Debug.WriteLine("Выстрел"); } - else if (keyBoardState.IsKeyUp(Keys.P)) + else if (keyBoardState.IsKeyUp(Keys.F)) { isShoot = false; } @@ -176,7 +170,6 @@ namespace ZoFo.GameCore.GameManagers #region Обработка взаимодействия с collectable(например лутом). Вызывает событие OnInteract if (keyBoardState.IsKeyDown(Keys.E) && !isInteract) { - OnInteract?.Invoke(); Debug.WriteLine("взаимодействие с Collectable"); } @@ -203,18 +196,33 @@ namespace ZoFo.GameCore.GameManagers DebugHUD.Instance.Set("controls", currentScopeState.ToString()); } #region работа с ScopeState и Vector2 + /// + /// возвращает число от -14 до 16, начиная с + /// + /// + /// + public int ConvertAttackVector2ToState(Vector2 vector){ + int currentSection = (int)Math.Ceiling(Math.Atan2(vector.Y, + vector.X) * (180 / Math.PI) / 360 * 32); + return currentSection; + } public ScopeState ConvertVector2ToState(Vector2 vector) { - //if() - int currentSection = (int)Math.Ceiling(Math.Atan2(vector.Y, + int currentSection = 0; + if(vector.X == 0f && vector.Y == 0f){ + currentScopeState = ScopeState.Idle; + } + else + { + currentSection = (int)Math.Ceiling(Math.Atan2(vector.Y, vector.X) * (180 / Math.PI) / 360 * 16); - - DebugHUD.DebugSet("current section", currentSection.ToString()); - //DebugHUD.DebugSet("y", InputMovementDirection.Y.ToString()); - //DebugHUD.DebugSet("x", InputMovementDirection.X.ToString()); + switch(currentSection) { + case -1: + currentScopeState = ScopeState.Idle; + break; case 0 or 1: currentScopeState = ScopeState.Right; break; @@ -242,8 +250,43 @@ namespace ZoFo.GameCore.GameManagers default: break; } + + DebugHUD.DebugSet("current section", currentSection.ToString()); + DebugHUD.DebugSet("y", vector.Y.ToString()); + DebugHUD.DebugSet("x", vector.X.ToString()); + } return currentScopeState; - } + } + public static Vector2 ConvertStateToVector2(ScopeState scopeState) + { + switch (scopeState) + { + case ScopeState.Idle: + return new Vector2(0, 0); + case ScopeState.Left: + return new Vector2(-1, 0); + case ScopeState.Right: + return new Vector2(1, 0); + case ScopeState.Top: + return new Vector2(0, -1); + case ScopeState.Down: + return new Vector2(0, 1); + case ScopeState.TopLeft: + return new Vector2(-1, -1); + case ScopeState.TopRight: + return new Vector2(-1, 1); + case ScopeState.DownLeft: + return new Vector2(1, -1); + case ScopeState.DownRight: + return new Vector2(1, 1); + default: + return new Vector2(0, 0); + } + + + } #endregion + public bool ButtonClicked(Keys key) => keyBoardState.IsKeyUp(key) && keyBoardState.IsKeyDown(key); } + } \ No newline at end of file diff --git a/ZoFo/GameCore/GameManagers/ItemManager/ItemManager.cs b/ZoFo/GameCore/GameManagers/ItemManager/ItemManager.cs index 0678c21..2b4cc3d 100644 --- a/ZoFo/GameCore/GameManagers/ItemManager/ItemManager.cs +++ b/ZoFo/GameCore/GameManagers/ItemManager/ItemManager.cs @@ -25,11 +25,15 @@ namespace ZoFo.GameCore.GameManagers.ItemManager public void Initialize() { tagItemPairs = new Dictionary(); - tagItemPairs.Add("Ammo", new ItemInfo("Ammo", "деньги в метро", "Textures\\icons\\Collectables\\Ammo",false,null)); - tagItemPairs.Add("wood", new ItemInfo("wood", "бревна кусок", "Textures\\Test\\wood",false,null)); - tagItemPairs.Add("rock", new ItemInfo("rock", "пять галек", "Textures\\Test\\rock", false, null)); - tagItemPairs.Add("steel", new ItemInfo("steel", "метал, метал, \nжелезо, метал", "Textures\\Test\\steel", false, null)); - tagItemPairs.Add("pickaxe", new ItemInfo("steel", "прямой путь к \nстановлению каменьщиком", "Textures\\Test\\pickaxe", true, new Dictionary() + tagItemPairs.Add("rottenflesh", new ItemInfo("rottenflesh", "БУХАТЬ", "Textures/icons/Collectables/RottenFlesh",false,null)); + tagItemPairs.Add("purebottleofwater", new ItemInfo("purebottleofwater", "БУХАТЬ 2", "Textures/icons/Collectables/PureBottleOfWater",false,null)); + tagItemPairs.Add("bottleofwater", new ItemInfo("bottleofwater", "БУХАТЬ", "Textures/icons/Collectables/BottleOfWater",false,null)); + //tagItemPairs.Add("antiradin", new ItemInfo("antiradin", "радиацию опускает", "Textures/icons/Collectables/Ammo",false,null)); + tagItemPairs.Add("ammo", new ItemInfo("ammo", "деньги в метро", "Textures/icons/Collectables/Ammo",false,null)); + tagItemPairs.Add("wood", new ItemInfo("wood", "бревна кусок", "Textures/icons/Collectables/Wood",false,null)); + tagItemPairs.Add("peeble", new ItemInfo("peeble", "пять галек", "Textures/icons/Collectables/Peeble", false, null)); + tagItemPairs.Add("steel", new ItemInfo("steel", "метал, метал, \nжелезо, метал", "Textures/icons/Collectables/Steel", false, null)); + tagItemPairs.Add("pickaxe", new ItemInfo("pickaxe", "прямой путь к \nстановлению каменьщиком", "Textures/Test/pickaxe", true, new Dictionary() { {"wood", 2}, {"steel", 3} diff --git a/ZoFo/GameCore/GameManagers/ItemManager/PlayerData.cs b/ZoFo/GameCore/GameManagers/ItemManager/PlayerData.cs index f58cc30..a4a5c0d 100644 --- a/ZoFo/GameCore/GameManagers/ItemManager/PlayerData.cs +++ b/ZoFo/GameCore/GameManagers/ItemManager/PlayerData.cs @@ -1,7 +1,9 @@ using System; using System.Collections.Generic; +using System.IO; using System.Linq; using System.Text; +using System.Text.Json; using System.Threading.Tasks; namespace ZoFo.GameCore.GameManagers.ItemManager @@ -15,7 +17,7 @@ namespace ZoFo.GameCore.GameManagers.ItemManager { LoadPlayerData(); } - public Dictionary items; + public Dictionary items = new Dictionary(); /// /// Принимает тэг и крафтит этот объект /// @@ -50,11 +52,44 @@ namespace ZoFo.GameCore.GameManagers.ItemManager public void LoadPlayerData() { - //TODO - items = new Dictionary(); - items.Add("wood", 5); - items.Add("steel", 110); - items.Add("rock", 6); + if (File.Exists("Items.txt")) + { + string data; + using (StreamReader reader = new StreamReader("Items.txt")) + { + data = reader.ReadToEnd(); + } + + List itemsDatas = JsonSerializer.Deserialize>(data); + foreach (var item in itemsDatas) + { + items.Add(item.Name, item.Count); + } + } + } + + public void SavePlayerData() + { + var options = new JsonSerializerOptions { WriteIndented = true }; + + List playerItemsDatas = new List(); + foreach (var item in items) + { + playerItemsDatas.Add(new PlayerItemsData { Name = item.Key, Count = item.Value }); + } + + string data = JsonSerializer.Serialize>(playerItemsDatas); + + using (StreamWriter outputFile = new StreamWriter("Items.txt", new FileStreamOptions() { Mode = FileMode.Create, Access = FileAccess.Write } )) + { + outputFile.WriteLine(data); + } } } + + class PlayerItemsData + { + public string Name { get; set; } + public int Count { get; set; } + } } diff --git a/ZoFo/GameCore/GameManagers/MapManager/MapManager.cs b/ZoFo/GameCore/GameManagers/MapManager/MapManager.cs index 49d2b2d..551ed28 100644 --- a/ZoFo/GameCore/GameManagers/MapManager/MapManager.cs +++ b/ZoFo/GameCore/GameManagers/MapManager/MapManager.cs @@ -94,11 +94,12 @@ namespace ZoFo.GameCore.GameManagers.MapManager switch (tile.Type) { + case "Tile": AppManager.Instance.server.RegisterGameObject(new MapObject(position, new Vector2(tileSet.TileWidth, tileSet.TileHeight), sourceRectangle, - "Textures/TileSetImages/" + Path.GetFileName(tileSet.Image).Replace(".png", ""))); + "Content/Textures/TileSetImages/" + Path.GetFileName(tileSet.Image).Replace(".png", ""))); break; case "StopObject": @@ -107,11 +108,11 @@ namespace ZoFo.GameCore.GameManagers.MapManager AppManager.Instance.server.RegisterGameObject(new StopObject(position, new Vector2(tileSet.TileWidth, tileSet.TileHeight), sourceRectangle, - "Textures/TileSetImages/" + Path.GetFileName(tileSet.Image).Replace(".png", ""), + "Content/Textures/TileSetImages/" + Path.GetFileName(tileSet.Image).Replace(".png", ""), collisionRectangles.ToArray())); break; - default: + default: break; } break; diff --git a/ZoFo/GameCore/GameManagers/NetworkManager/ClientNetworkManager.cs b/ZoFo/GameCore/GameManagers/NetworkManager/ClientNetworkManager.cs index 85d8a19..685c40e 100644 --- a/ZoFo/GameCore/GameManagers/NetworkManager/ClientNetworkManager.cs +++ b/ZoFo/GameCore/GameManagers/NetworkManager/ClientNetworkManager.cs @@ -1,3 +1,5 @@ +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Data.SqlTypes; @@ -10,47 +12,52 @@ using System.Text.Json; using System.Threading; using System.Threading.Tasks; using ZoFo.GameCore.GameManagers.NetworkManager.Updates; +using ZoFo.GameCore.GameManagers.NetworkManager.Updates.ServerToClient; +using ZoFo.GameCore.GUI; namespace ZoFo.GameCore.GameManagers.NetworkManager { public class ClientNetworkManager { - private int port = 0; + private int PlayerId; private IPEndPoint endPoint; + private IPEndPoint sendingEP; private Socket socket; List updates = new List(); + private List waitingDatagramm = new List(); + private int currentServerDatagrammId = 0; public delegate void OnDataSent(string Data); public event OnDataSent GetDataSent; // event public bool IsConnected { get { return socket.Connected; } } public IPEndPoint InfoConnect => (IPEndPoint)socket.LocalEndPoint ?? endPoint; - public ClientNetworkManager() { Init(); } - public bool SocketConnected() - { - return socket.Connected; - } - public void Init() //create endPoint, socket { - socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + GetDataSent += AnalyzeData; + socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); + endPoint = new IPEndPoint(GetIp(), 8081); + socket.Bind(endPoint); + Thread thread = new Thread(StartListening); + thread.IsBackground = true; + thread.Start(); } public void SendData() { - for (int i = 0; i < updates.Count; i++) + if (updates != null) { - - AppManager.Instance.server.ProcessIUpdateData(updates[i]); + Datagramm Datagramm = new Datagramm(); + Datagramm.updateDatas = updates; + byte[] bytes = Encoding.UTF8.GetBytes(System.Text.Json.JsonSerializer.Serialize(Datagramm)); //нужно сериализовать + socket.SendTo(bytes, sendingEP); + updates.Clear(); } - updates.Clear(); - return;// TODO remove - byte[] bytes = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(updates)); //нужно сериализовать - socket.Send(bytes); + } public void AddData(UpdateData UpdateData) @@ -58,12 +65,151 @@ namespace ZoFo.GameCore.GameManagers.NetworkManager updates.Add(UpdateData); } - public void StopConnection() - { - socket.Shutdown(SocketShutdown.Both); - socket.Close(); + #region Working With Data RDP + + public void AnalyzeData(string data) + { + JObject jObj = JsonConvert.DeserializeObject(data) as JObject; + JToken token = JToken.FromObject(jObj); + JToken updateDatas = token["updateDatas"]; + if (updateDatas.HasValues) + { + Datagramm Dgramm = new Datagramm(); + Dgramm.isImportant = token["isImportant"].ToObject(); + Dgramm.DatagrammId = token["DatagrammId"].ToObject(); + if (PlayerId == 0) + { + PlayerId = token["PlayerId"].ToObject(); + if (AppManager.Instance.gamestate != GameState.HostPlaying) + { + AppManager.Instance.ChangeState(GameState.ClientPlaying); + } + SendAcknowledgement(Dgramm.DatagrammId); + } + if (Dgramm.isImportant) + { + if (Dgramm.DatagrammId == currentServerDatagrammId + 1) + { + currentServerDatagrammId++; + Dgramm.updateDatas = GetSentUpdates(token["updateDatas"]); + ExecuteDatagramm(Dgramm); + CheckDatagramm(); + } + else if (Dgramm.DatagrammId > currentServerDatagrammId + 1 && + waitingDatagramm.Find(x => x.DatagrammId == Dgramm.DatagrammId) == null) + { + Dgramm.updateDatas = GetSentUpdates(token["updateDatas"]); + waitingDatagramm.Add(Dgramm); + } + SendAcknowledgement(Dgramm.DatagrammId); + } + else + { + Dgramm.updateDatas = GetSentUpdates(token["updateDatas"]); + ExecuteDatagramm(Dgramm); + } + } + + } + public List GetSentUpdates(JToken updatesToken) + { + List data = new List(); + JArray updateDatas = updatesToken as JArray; + UpdateData update = new UpdateData(); + foreach (JObject token in updateDatas.Children()) + { + switch (token["UpdateType"].ToObject()) + { + case "UpdateAnimation": + update = token.ToObject(); + data.Add(update); + break; + case "UpdateEntityHealth": + update = token.ToObject(); + data.Add(update); + break; + case "UpdateGameEnded": + update = token.ToObject(); + data.Add(update); + break; + case "UpdateGameObjectCreated": + update = token.ToObject(); + data.Add(update); + break; + case "UpdateGameObjectWithoutIdCreated": + update = token.ToObject(); + data.Add(update); + break; + case "UpdateGameObjectDeleted": + update = token.ToObject(); + data.Add(update); + break; + case "UpdateInteraction": + update = token.ToObject(); + data.Add(update); + break; + case "UpdateStopObjectCreated": + update = token.ToObject(); + data.Add(update); + break; + case "UpdateInteractionReady": + update = token.ToObject(); + data.Add(update); + break; + case "UpdateLoot": + update = token.ToObject(); + data.Add(update); + break; + case "UpdatePlayerParametrs": + update = token.ToObject(); + data.Add(update); + break; + case "UpdatePosition": + update = token.ToObject(); + data.Add(update); + break; + case "UpdateTileCreated": + update = token.ToObject(); + data.Add(update); + break; + + } + } + + return data; + } + + public void SendAcknowledgement(int DatagrammId) + { + + Datagramm Dgramm = new Datagramm() { DatagrammId = DatagrammId, PlayerId = PlayerId }; + string data = System.Text.Json.JsonSerializer.Serialize(Dgramm); + byte[] buffer = Encoding.UTF8.GetBytes(data); + socket.SendTo(buffer, sendingEP); + + } + void CheckDatagramm() + { + Datagramm orderedDgramm = waitingDatagramm.Find(x => x.DatagrammId == currentServerDatagrammId + 1); + while (orderedDgramm != null) + { + currentServerDatagrammId++; + ExecuteDatagramm(orderedDgramm); + waitingDatagramm.Remove(orderedDgramm); + orderedDgramm = waitingDatagramm.Find(x => x.DatagrammId == currentServerDatagrammId + 1); + } + } + void ExecuteDatagramm(Datagramm Dgramm) + { + + AppManager.Instance.client.UpdatesList(Dgramm.updateDatas); + //Достаёт Update и передает в ивент + } + +#endregion + #region Join /// /// приложение пытается подключиться к комнате /// @@ -71,19 +217,7 @@ namespace ZoFo.GameCore.GameManagers.NetworkManager /// public void JoinRoom(string ip, int port) // multyplayer { - - endPoint = new IPEndPoint(IPAddress.Parse(ip), port); - socket.Connect(endPoint); - SendData(); - Thread listen = new Thread(StartListening); - listen.IsBackground = true; - listen.Start(); - } - public void JoinRoom(IPEndPoint endPoint) // multyplayer - { - - this.endPoint = endPoint; - socket.Connect(endPoint); + sendingEP = new IPEndPoint(IPAddress.Parse(ip), port); SendData(); Thread listen = new Thread(StartListening); listen.IsBackground = true; @@ -95,38 +229,45 @@ namespace ZoFo.GameCore.GameManagers.NetworkManager /// public void JoinYourself(int port) // single player { - endPoint = new IPEndPoint(GetIp(), port); - socket.Connect(endPoint); + sendingEP = AppManager.Instance.server.MyIp; SendData(); Thread listen = new Thread(StartListening); listen.IsBackground = true; listen.Start(); } - + #endregion public static IPAddress GetIp() - { - /*string hostName = Dns.GetHostName(); // Retrive the Name of HOST - var ipList = Dns.GetHostByName(hostName).AddressList; - + { + string hostName = Dns.GetHostName(); // Retrive the Name of HOST + var ipList = Dns.GetHostEntry(hostName).AddressList; + var ipV4List = new List(); foreach (var ip in ipList) { if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { - return ip; - } - }*/ - return IPAddress.Parse("127.0.0.1"); + ipV4List.Add(ip); + } + } + if (ipV4List.Count>0) + { + return ipV4List[ipV4List.Count - 1]; + } + return IPAddress.Loopback; } //поток 2 public void StartListening() { - while(socket.Connected) - { - byte[] bytes = new byte[65535]; - var countAnsw = socket.Receive(bytes); //Вылетает если кто то закрыл - string update = Encoding.UTF8.GetString(bytes, 0, countAnsw); // обновление отосланные сервером - GetDataSent(update); + byte[] buffer = new byte[65535]; + string data; + while (socket != null) + { + EndPoint senderRemote = new IPEndPoint(IPAddress.Any, 0); + int size = socket.ReceiveFrom(buffer, buffer.Length, SocketFlags.None, ref senderRemote); + byte[] correctedBuffer = new byte[size]; + Array.Copy(buffer, correctedBuffer, size); + data = Encoding.UTF8.GetString(correctedBuffer); + GetDataSent(data); } } } diff --git a/ZoFo/GameCore/GameManagers/NetworkManager/SerializableDTO/SerializablePoint.cs b/ZoFo/GameCore/GameManagers/NetworkManager/SerializableDTO/SerializablePoint.cs index 4480a8c..8db620a 100644 --- a/ZoFo/GameCore/GameManagers/NetworkManager/SerializableDTO/SerializablePoint.cs +++ b/ZoFo/GameCore/GameManagers/NetworkManager/SerializableDTO/SerializablePoint.cs @@ -9,10 +9,11 @@ namespace ZoFo.GameCore.GameManagers.NetworkManager.SerializableDTO { public class SerializablePoint { - public int X; - public int Y; + public int X { get; set; } + public int Y { get; set; } public SerializablePoint(Point point) { X = point.X; Y = point.Y;} + public SerializablePoint() { } public Point GetPoint() { return new Point(X, Y);} } } diff --git a/ZoFo/GameCore/GameManagers/NetworkManager/SerializableDTO/SerializableRectangle.cs b/ZoFo/GameCore/GameManagers/NetworkManager/SerializableDTO/SerializableRectangle.cs index 720344e..22ea155 100644 --- a/ZoFo/GameCore/GameManagers/NetworkManager/SerializableDTO/SerializableRectangle.cs +++ b/ZoFo/GameCore/GameManagers/NetworkManager/SerializableDTO/SerializableRectangle.cs @@ -10,24 +10,20 @@ using ZoFo.GameCore.GameManagers.NetworkManager.SerializableDTO; namespace ZoFo.GameCore.GameManagers.NetworkManager.SerializableDTO { [Serializable] - [JsonSerializable(typeof(SerializableRectangle))] public class SerializableRectangle { public SerializablePoint Size { get; set; } public SerializablePoint Location { get; set; } - public int X { get; set; } - public int Y { get; set; } public SerializableRectangle() { } - public SerializableRectangle(Rectangle rectangle) { X = rectangle.X; Y = rectangle.Y; - Size = new SerializablePoint(rectangle.Size); Location = new SerializablePoint(rectangle.Location); } + public SerializableRectangle(Rectangle rectangle) { Size = new SerializablePoint(rectangle.Size); Location = new SerializablePoint(rectangle.Location); } public Rectangle GetRectangle() { - return new Rectangle() { X = X, Y = Y, Size = Size.GetPoint(), Location = Location.GetPoint() }; + return new Rectangle(Location.GetPoint(), Size.GetPoint()); } } } diff --git a/ZoFo/GameCore/GameManagers/NetworkManager/SerializableDTO/SerializableVector2.cs b/ZoFo/GameCore/GameManagers/NetworkManager/SerializableDTO/SerializableVector2.cs new file mode 100644 index 0000000..53414e2 --- /dev/null +++ b/ZoFo/GameCore/GameManagers/NetworkManager/SerializableDTO/SerializableVector2.cs @@ -0,0 +1,28 @@ +using Microsoft.Xna.Framework; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.InteropServices.JavaScript; +using System.Text; +using System.Threading.Tasks; + +namespace ZoFo.GameCore.GameManagers.NetworkManager.SerializableDTO +{ + [Serializable] + public class SerializableVector2 + { + public float X { get; set; } + public float Y { get; set; } + public SerializableVector2(Vector2 vector) + { + X = vector.X; + Y = vector.Y; + } + public Vector2 GetVector2() + { + return new Vector2(X, Y); + } + } + + +} diff --git a/ZoFo/GameCore/GameManagers/NetworkManager/ServerNetworkManager.cs b/ZoFo/GameCore/GameManagers/NetworkManager/ServerNetworkManager.cs index f5c7830..d64b40d 100644 --- a/ZoFo/GameCore/GameManagers/NetworkManager/ServerNetworkManager.cs +++ b/ZoFo/GameCore/GameManagers/NetworkManager/ServerNetworkManager.cs @@ -13,23 +13,32 @@ using System.Text.Json.Serialization; using System.Threading; using System.Threading.Tasks; using ZoFo.GameCore.GameManagers.NetworkManager.Updates; +using ZoFo.GameCore.GameManagers.NetworkManager.SerializableDTO; +using ZoFo.GameCore.GUI; +using Newtonsoft.Json.Linq; +using Newtonsoft.Json; +using ZoFo.GameCore.GameManagers.NetworkManager.Updates.ServerToClient; +using ZoFo.GameCore.GameManagers.NetworkManager.Updates.ClientToServer; namespace ZoFo.GameCore.GameManagers.NetworkManager { public class ServerNetworkManager { - private IPAddress ip = IPAddress.Parse("127.0.0.1"); - private const int port = 0; - private IPEndPoint endPoint; private Socket socket; - private List clients; - public List updates; + private IPAddress ip; + private bool isMultiplayer; + //Player Id to Player endPoint + private List clientsEP; + public IPEndPoint endPoint; + private List commonUpdates; + private List importantUpdates; + private List sendedData; + private List arrivingDataId; + private int currentDatagrammId = 0; public delegate void OnDataSend(string data); public event OnDataSend GetDataSend; // event - Dictionary managerThread; - Thread serverTheread; - public IPEndPoint InfoConnect => (IPEndPoint)socket.LocalEndPoint ?? endPoint; - + Thread serverThread; + int datapackSize = 150; public ServerNetworkManager() { Init(); } /// @@ -37,31 +46,46 @@ namespace ZoFo.GameCore.GameManagers.NetworkManager /// private void Init() { - endPoint = new IPEndPoint(GetIp(), port); - socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); - managerThread = new Dictionary(); - clients = new List(); - updates = new List(); - managerThread = new Dictionary(); + endPoint = new IPEndPoint(GetIp(), 8080); + socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); + clientsEP = new List(); + commonUpdates = new List(); + importantUpdates = new List(); + sendedData = new List(); + arrivingDataId = new List(); + + GetDataSend += AnalyzeData; + socket.Bind(endPoint); + } /// /// Получает IP устройства /// /// - public static IPAddress GetIp() - { - /*string hostName = Dns.GetHostName(); // Retrive the Name of HOST - var ipList = Dns.GetHostByName(hostName).AddressList; + public static IPAddress GetIp() + { + string hostName = Dns.GetHostName(); // Retrive the Name of HOST + var ipList = Dns.GetHostEntry(hostName).AddressList; + + var ipV4List = new List(); foreach (var ip in ipList) { if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) - { - return ip; - } - }*/ - return IPAddress.Parse("127.0.0.1"); + { + ipV4List.Add(ip); + } + } + if (ipV4List.Count > 0) + { + return ipV4List[ipV4List.Count - 1]; + } + return IPAddress.Loopback; + } + public void SetIsMultiplayer(bool isMultiplayer) + { + this.isMultiplayer = isMultiplayer; } /// @@ -69,26 +93,76 @@ namespace ZoFo.GameCore.GameManagers.NetworkManager /// public void SendData() { - for (int i = 0; i < updates.Count; i++) - { + #region Network Sending SinglePlayerFix + //for (int i = 0; i < updates.Count; i++) + //{ - AppManager.Instance.client.GotData(updates[i]); - } - updates.Clear(); - return; //TODO TODO REMOVE TO ADD NETWORK TODO REMOVE TO ADD NETWORK TODO REMOVE TO ADD NETWORK TODO REMOVE TO ADD NETWORK + // AppManager.Instance.client.GotData(updates[i]); + //} + //updates.Clear(); + //return; //TODO TODO REMOVE TO ADD NETWORK TODO REMOVE TO ADD NETWORK TODO REMOVE TO ADD NETWORK TODO REMOVE TO ADD NETWORK //Что это? //по 10 паков за раз TODO FIXITFIXITFIXITFIXITFIXITFIXITFIXITFIXITFIXITFIXITFIXITFIXIT - List datasToSend = new List(); - for (int i = 0; i < 200 && i actualArrivingId = arrivingDataId; + for (int i = 0; i < actualArrivingId.Count; i++) + { + sendedData.Remove(sendedData.Find(x => x.DatagrammId == actualArrivingId[i].DatagrammId + && x.PlayerId == actualArrivingId[i].PlayerId)); + } + arrivingDataId.Clear(); } - for (int i = 0; i < 200 && i< datasToSend.Count; i++) - updates.RemoveAt(0); + List dataToSend; + if (importantUpdates.Count > 0) + { + dataToSend = new List(); + for (int j = 0; j < datapackSize && j < importantUpdates.Count; j++) + dataToSend.Add(importantUpdates[j]); + for (int i = 0; i < clientsEP.Count; i++) + { + Datagramm impDgramm = new Datagramm(); + impDgramm.DatagrammId = currentDatagrammId; + impDgramm.updateDatas = dataToSend; + impDgramm.isImportant = true; + impDgramm.PlayerId = i + 1; + sendedData.Add(impDgramm); + } + for (int j = 0; j < datapackSize && j < dataToSend.Count; j++) + importantUpdates.RemoveAt(0); + currentDatagrammId++; + } + + if (sendedData.Count != 0) + { + + + for (int i = 0; i < clientsEP.Count; i++) + { + foreach (Datagramm Dgramm in sendedData.Where(x => x.PlayerId == i+1)) + { + string impData = System.Text.Json.JsonSerializer.Serialize(Dgramm); + byte[] impBuffer = Encoding.UTF8.GetBytes(impData); + socket.SendTo(impBuffer, clientsEP[i]); + } + } + } + Datagramm unImpDgramm = new Datagramm(); + + dataToSend = new List(); + for (int i = 0; i < 200 && i < commonUpdates.Count; i++) + dataToSend.Add(commonUpdates[i]); + + unImpDgramm.updateDatas = dataToSend; + string data = System.Text.Json.JsonSerializer.Serialize(unImpDgramm); + byte[] buffer = Encoding.UTF8.GetBytes(data); + foreach (EndPoint sendingEP in clientsEP) + { + socket.SendTo(buffer, sendingEP); + } + for (int i = 0; i < 200 && i < dataToSend.Count; i++) + commonUpdates.RemoveAt(0); } /// @@ -97,42 +171,41 @@ namespace ZoFo.GameCore.GameManagers.NetworkManager /// public void AddData(UpdateData data) { - updates.Add(data); - } - - /// - /// По сути конец игры и отключение игроков - /// - public void CloseConnection() - { - foreach (var item in clients) + if (data.isImportant) { - //Закрывает сокеты клиентов - item.Shutdown(SocketShutdown.Both); - item.Close(); + importantUpdates.Add(data); } - foreach (var item in managerThread) - { - foreach (var socket in clients) - { - //Закрывает потоки клиентов - managerThread[socket].Interrupt(); - } + else { + commonUpdates.Add(data); } - //очищает листы - managerThread.Clear(); - clients.Clear(); } /// /// Начинает работу сервера (Ожидает подключений) /// /// - public void Start(object players) + public void Start() { - serverTheread = new Thread(StartWaitingForPlayers); - serverTheread.IsBackground = true; - serverTheread.Start(players); + serverThread = new Thread(StartWaitingForPlayers); + serverThread.IsBackground = true; + serverThread.Start(); + } + public void StartGame() + { + for (int i = 0; i < clientsEP.Count; i++) + { + Datagramm initDgramm = new Datagramm(); + initDgramm.isImportant = true; + initDgramm.DatagrammId = currentDatagrammId; + initDgramm.PlayerId = i + 1; + sendedData.Add(initDgramm); + string data = System.Text.Json.JsonSerializer.Serialize(initDgramm); + byte[] buffer = Encoding.UTF8.GetBytes(data); + socket.SendTo(buffer, clientsEP[i]); + } + currentDatagrammId++; + AppManager.Instance.ChangeState(GameState.HostPlaying); + AppManager.Instance.SetGUI(new HUD());//// } //Потоки Клиентов @@ -140,43 +213,74 @@ namespace ZoFo.GameCore.GameManagers.NetworkManager /// Слушает игроков, которые хотят подключиться /// /// - public void StartWaitingForPlayers(object players) + public void StartWaitingForPlayers() { - int playNumber = (int)players; - - socket.Listen(playNumber); - for (int i = 0; i < playNumber; i++) + byte[] buffer = new byte[65535]; + string data; + while (socket != null) { - Socket client = socket.Accept(); - AppManager.Instance.debugHud.Log($"Connect {client.LocalEndPoint.ToString()}"); - Thread thread = new Thread(StartListening); - thread.IsBackground = true; - thread.Start(client); - managerThread.Add(client, thread); - clients.Add(client); - //AppManager.Instance.ChangeState(GameState.HostPlaying); - //добавляем клиентов в лист + EndPoint senderRemote = (EndPoint)new IPEndPoint(IPAddress.Any, 0); + int size = socket.ReceiveFrom(buffer, buffer.Length, SocketFlags.None, ref senderRemote); + if (AppManager.Instance.gamestate != GameState.HostPlaying && !clientsEP.Contains(senderRemote) && + senderRemote != new IPEndPoint(IPAddress.Any, 0)) + { + clientsEP.Add((IPEndPoint)senderRemote); + AppManager.Instance.debugHud.Log($"Connect {senderRemote.ToString()}"); + if (!isMultiplayer) AppManager.Instance.ChangeState(GameState.HostPlaying); + // Отправлять Init апдейт с информацией об ID игрока и ID датаграмма на сервере + //Можно добавить bool isInit для Датаграммов + } + byte[] correctedBuffer = new byte[size]; + Array.Copy(buffer, correctedBuffer, size); + data = Encoding.UTF8.GetString(correctedBuffer); + GetDataSend(data); + } - AppManager.Instance.ChangeState(GameState.HostPlaying); + } + public void AnalyzeData(string data) + { + JObject jObj = JsonConvert.DeserializeObject(data) as JObject; + JToken token = JToken.FromObject(jObj); + JToken updateDatas = token["updateDatas"]; + Datagramm Dgramm = new Datagramm(); + Dgramm.PlayerId = token["PlayerId"].ToObject(); + if (!updateDatas.HasValues) + { + //Обработка acknowledgement + Dgramm.DatagrammId = token["DatagrammId"].ToObject(); + arrivingDataId.Add(Dgramm); + } + else + { + List updates = GetSentUpdates(updateDatas); + AppManager.Instance.server.UpdatesList(updates); + } + } + public List GetSentUpdates(JToken updatesToken) + { + List data = new List(); + JArray updateDatas = updatesToken as JArray; + UpdateData update = new UpdateData(); + foreach (JObject token in updateDatas.Children()) + { + switch (token["UpdateType"].ToObject()) + { + case "UpdateInput": + update = token.ToObject(); + data.Add(update); + break; + case "UpdateInputInteraction": + update = token.ToObject(); + data.Add(update); + break; + case "UpdateInputShoot": + update = token.ToObject(); + data.Add(update); + break; + } + } + return data; } - /// - /// начать слушать клиентов в самой игре активируют Ивент - /// - /// - private void StartListening(object socket) - { - // obj to Socket - Socket client = (Socket)socket; - while (client.Connected) - { - var buff = new byte[65535]; - var answ = client.Receive(buff); - string response = Encoding.UTF8.GetString(buff, 0, answ); - GetDataSend(response); - } - Task.Delay(-1); - - } } } diff --git a/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ClientToServer/UpdateInput.cs b/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ClientToServer/UpdateInput.cs index 350fd41..3450f13 100644 --- a/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ClientToServer/UpdateInput.cs +++ b/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ClientToServer/UpdateInput.cs @@ -5,14 +5,15 @@ using Microsoft.Xna.Framework; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading.Tasks; +using ZoFo.GameCore.GameManagers.NetworkManager.SerializableDTO; namespace ZoFo.GameCore.GameManagers.NetworkManager.Updates.ClientToServer { public class UpdateInput :UpdateData { // public int IdEntity { get; set; } - public Vector2 InputMovementDirection{get;set;} - public Vector2 InputAttackDirection {get;set;} + public SerializableVector2 InputMovementDirection{get;set;} + public SerializableVector2 InputAttackDirection {get;set;} public UpdateInput() { UpdateType = "UpdateInput"; diff --git a/ZoFo/GameCore/GameManagers/NetworkManager/Updates/Datagramm.cs b/ZoFo/GameCore/GameManagers/NetworkManager/Updates/Datagramm.cs new file mode 100644 index 0000000..9129f34 --- /dev/null +++ b/ZoFo/GameCore/GameManagers/NetworkManager/Updates/Datagramm.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ZoFo.GameCore.GameManagers.NetworkManager.Updates +{ + public class Datagramm + { + public int DatagrammId { get; set; } + public bool isImportant { get; set; } + public List updateDatas { get; set; } + public int PlayerId { get; set; } + } +} diff --git a/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ServerToClient/UpdateGameOBjectWithoutIdCreated.cs b/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ServerToClient/UpdateGameOBjectWithoutIdCreated.cs new file mode 100644 index 0000000..9033279 --- /dev/null +++ b/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ServerToClient/UpdateGameOBjectWithoutIdCreated.cs @@ -0,0 +1,16 @@ + +using Microsoft.Xna.Framework; +using ZoFo.GameCore.GameManagers.NetworkManager.SerializableDTO; + +namespace ZoFo.GameCore.GameManagers.NetworkManager.Updates.ServerToClient +{ + /// + /// Хранит новое сосотяние анимации + /// + public class UpdateGameObjectWithoutIdCreated : UpdateData + { + public UpdateGameObjectWithoutIdCreated() { UpdateType = "UpdateGameObjectWithoutIdCreated"; isImportant = true; } + public string GameObjectClassName { get; set; } + public SerializableVector2 position { get; set; } + } +} diff --git a/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ServerToClient/UpdateGameObjectCreated.cs b/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ServerToClient/UpdateGameObjectCreated.cs index 8e1b5b6..9188f1c 100644 --- a/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ServerToClient/UpdateGameObjectCreated.cs +++ b/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ServerToClient/UpdateGameObjectCreated.cs @@ -4,6 +4,7 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using ZoFo.GameCore.GameManagers.NetworkManager.SerializableDTO; namespace ZoFo.GameCore.GameManagers.NetworkManager.Updates.ServerToClient { @@ -12,9 +13,12 @@ namespace ZoFo.GameCore.GameManagers.NetworkManager.Updates.ServerToClient /// public class UpdateGameObjectCreated : UpdateData { - public UpdateGameObjectCreated() { UpdateType = "UpdateGameObjectCreated"; } - public string GameObjectType; - public string GameObjectId; - public Vector2 position; + public UpdateGameObjectCreated() { UpdateType = "UpdateGameObjectCreated"; isImportant = true; } + + public string GameObjectType { get; set; } + + public string GameObjectId { get; set; } + + public SerializableVector2 position { get; set; } } } diff --git a/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ServerToClient/UpdateGameObjectDeleted.cs b/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ServerToClient/UpdateGameObjectDeleted.cs index 25415e1..121e8df 100644 --- a/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ServerToClient/UpdateGameObjectDeleted.cs +++ b/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ServerToClient/UpdateGameObjectDeleted.cs @@ -11,7 +11,7 @@ namespace ZoFo.GameCore.GameManagers.NetworkManager.Updates.ServerToClient /// public class UpdateGameObjectDeleted : UpdateData { - public UpdateGameObjectDeleted() { UpdateType = "UpdateGameObjectDeleted"; } - public string GameObjectType; + public UpdateGameObjectDeleted() { UpdateType = "UpdateGameObjectDeleted"; isImportant = false; } + public string GameObjectType { get; set; } } } \ No newline at end of file diff --git a/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ServerToClient/UpdateLoot.cs b/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ServerToClient/UpdateLoot.cs index b69a860..0e1a360 100644 --- a/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ServerToClient/UpdateLoot.cs +++ b/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ServerToClient/UpdateLoot.cs @@ -11,12 +11,16 @@ namespace ZoFo.GameCore.GameManagers.NetworkManager.Updates.ServerToClient /// public class UpdateLoot : UpdateData { - public string lootName; - public UpdateLoot() { UpdateType = "UpdateLoot"; } - public UpdateLoot(string lootName) + public string lootName { get; set; } + public int quantity { get; set; } + public UpdateLoot() { UpdateType = "UpdateLoot"; isImportant = true; } + public UpdateLoot(string lootName, int quantity, int id) { UpdateType = "UpdateLoot"; this.lootName = lootName; + this.quantity = quantity; + IdEntity = id; + isImportant = true; } } } diff --git a/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ServerToClient/UpdatePlayerParametrs.cs b/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ServerToClient/UpdatePlayerParametrs.cs index 100c8d0..57c4c2a 100644 --- a/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ServerToClient/UpdatePlayerParametrs.cs +++ b/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ServerToClient/UpdatePlayerParametrs.cs @@ -11,6 +11,8 @@ namespace ZoFo.GameCore.GameManagers.NetworkManager.Updates.ServerToClient /// public class UpdatePlayerParametrs : UpdateData { - public UpdatePlayerParametrs() { UpdateType = "UpdatePlayerParametrs"; } + public UpdatePlayerParametrs() { UpdateType = "UpdatePlayerParametrs"; isImportant = true; } + public float radiatoin { get; set; } + public float health { get; set; } } } diff --git a/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ServerToClient/UpdatePosition.cs b/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ServerToClient/UpdatePosition.cs index 189a299..da2293f 100644 --- a/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ServerToClient/UpdatePosition.cs +++ b/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ServerToClient/UpdatePosition.cs @@ -4,6 +4,7 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using ZoFo.GameCore.GameManagers.NetworkManager.SerializableDTO; using ZoFo.GameCore.GameObjects.Entities.LivingEntities; namespace ZoFo.GameCore.GameManagers.NetworkManager.Updates.ServerToClient @@ -15,6 +16,6 @@ namespace ZoFo.GameCore.GameManagers.NetworkManager.Updates.ServerToClient { public UpdatePosition() { UpdateType = "UpdatePosition"; } - public Vector2 NewPosition { get; set; } + public SerializableVector2 NewPosition { get; set; } } } diff --git a/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ServerToClient/UpdateStopObjectCreated.cs b/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ServerToClient/UpdateStopObjectCreated.cs index a8389e3..c848bce 100644 --- a/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ServerToClient/UpdateStopObjectCreated.cs +++ b/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ServerToClient/UpdateStopObjectCreated.cs @@ -11,9 +11,9 @@ namespace ZoFo.GameCore.GameManagers.NetworkManager.Updates.ServerToClient { internal class UpdateStopObjectCreated : UpdateData { - public UpdateStopObjectCreated() { UpdateType = "UpdateStopObjectCreated"; } + public UpdateStopObjectCreated() { UpdateType = "UpdateStopObjectCreated"; isImportant = true; } public Texture2D TextureTile { get; set; } - public Vector2 Position { get; set; } + public SerializableVector2 Position { get; set; } public SerializablePoint Size { get; set; } public SerializableRectangle sourceRectangle { get; set; } public string tileSetName { get; set; } diff --git a/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ServerToClient/UpdateTileCreated.cs b/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ServerToClient/UpdateTileCreated.cs index 948d5b5..fe97a10 100644 --- a/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ServerToClient/UpdateTileCreated.cs +++ b/ZoFo/GameCore/GameManagers/NetworkManager/Updates/ServerToClient/UpdateTileCreated.cs @@ -17,9 +17,9 @@ namespace ZoFo.GameCore.GameManagers.NetworkManager.Updates.ServerToClient /// public class UpdateTileCreated : UpdateData { - public UpdateTileCreated() { UpdateType = "UpdateTileCreated"; } - public Texture2D TextureTile { get; set; } - public Vector2 Position { get; set; } + public UpdateTileCreated() { UpdateType = "UpdateTileCreated"; isImportant = true; } + [JsonInclude] + public SerializableVector2 Position { get; set; } public SerializablePoint Size { get; set; } public SerializableRectangle sourceRectangle { get; set; } public string tileSetName { get; set; } diff --git a/ZoFo/GameCore/GameManagers/NetworkManager/Updates/UpdateData.cs b/ZoFo/GameCore/GameManagers/NetworkManager/Updates/UpdateData.cs index 65ef2d2..86f3163 100644 --- a/ZoFo/GameCore/GameManagers/NetworkManager/Updates/UpdateData.cs +++ b/ZoFo/GameCore/GameManagers/NetworkManager/Updates/UpdateData.cs @@ -15,19 +15,24 @@ namespace ZoFo.GameCore.GameManagers.NetworkManager.Updates [JsonDerivedType(typeof(UpdateGameEnded))] [JsonDerivedType(typeof(UpdateGameObjectCreated))] [JsonDerivedType(typeof(UpdateGameObjectDeleted))] + [JsonDerivedType(typeof(UpdateInteraction))] + [JsonDerivedType(typeof(UpdateInteractionReady))] [JsonDerivedType(typeof(UpdateLoot))] + [JsonDerivedType(typeof(UpdateGameObjectWithoutIdCreated))] [JsonDerivedType(typeof(UpdatePlayerParametrs))] [JsonDerivedType(typeof(UpdatePosition))] + [JsonDerivedType(typeof(UpdateStopObjectCreated))] [JsonDerivedType(typeof(UpdateTileCreated))] [JsonDerivedType(typeof(UpdateInput))] [JsonDerivedType(typeof(UpdatePlayerExit))] - [JsonDerivedType(typeof(UpdateInteractionReady))] - [JsonDerivedType(typeof(UpdateInteraction))] + [JsonDerivedType(typeof(UpdateInputInteraction))] + [JsonDerivedType(typeof(UpdateInputShoot))] public class UpdateData { public int IdEntity { get; set; } //Id объекта - public string UpdateType { get; protected set; } //тип обновления + public string UpdateType { get; set; } //тип обновления + public bool isImportant { get; set; } public UpdateData() { diff --git a/ZoFo/GameCore/GameManagers/SettingsManager.cs b/ZoFo/GameCore/GameManagers/SettingsManager.cs index 25dd40d..13d870a 100644 --- a/ZoFo/GameCore/GameManagers/SettingsManager.cs +++ b/ZoFo/GameCore/GameManagers/SettingsManager.cs @@ -28,18 +28,21 @@ namespace ZoFo.GameCore.GameManagers public void SetMainVolume(float volume) { settingsContainer.MainVolume = volume; - //AppManager.Instance.SoundManager.Update(); + // AppManager.Instance.SoundManager.Update(); SaveSettings(); } public void SetMusicVolume(float volume) { settingsContainer.MusicVolume = volume; + //AppManager.Instance.SoundManager.Update(); + SaveSettings(); } public void SetSoundEffectsVolume(float volume) { settingsContainer.SoundEffectsVolume = volume; + // AppManager.Instance.SoundManager.Update(); SaveSettings(); } @@ -68,6 +71,7 @@ namespace ZoFo.GameCore.GameManagers } public void SaveSettings() { + AppManager.Instance.SoundManager.Update(); using (StreamWriter streamWriter = new StreamWriter("GameSettings.txt")) { string _str = JsonConvert.SerializeObject(settingsContainer); diff --git a/ZoFo/GameCore/GameObjects/Entities/EntittyForAnimationTests.cs b/ZoFo/GameCore/GameObjects/Entities/EntittyForAnimationTests.cs index 7a9454f..67166c8 100644 --- a/ZoFo/GameCore/GameObjects/Entities/EntittyForAnimationTests.cs +++ b/ZoFo/GameCore/GameObjects/Entities/EntittyForAnimationTests.cs @@ -12,6 +12,7 @@ namespace ZoFo.GameCore.GameObjects { //public override GraphicsComponent graphicsComponent { get; } = new GraphicsComponent(new List { "тут пишите название анимации" }, "сдублируйте " + + public override GraphicsComponent graphicsComponent { get; } = new AnimatedGraphicsComponent(new List { "zombie_idle" }, "zombie_idle"); @@ -19,6 +20,7 @@ namespace ZoFo.GameCore.GameObjects public EntittyForAnimationTests(Vector2 position) : base(position) { graphicsComponent.ObjectDrawRectangle = new Rectangle(0,0,16*20, 16 * 20); + position = new Vector2(10, 10); } diff --git a/ZoFo/GameCore/GameObjects/Entities/Entity.cs b/ZoFo/GameCore/GameObjects/Entities/Entity.cs index 12c40b2..fc7cea8 100644 --- a/ZoFo/GameCore/GameObjects/Entities/Entity.cs +++ b/ZoFo/GameCore/GameObjects/Entities/Entity.cs @@ -40,12 +40,15 @@ namespace ZoFo.GameCore.GameObjects public void StartAnimation(string animationId) { - (graphicsComponent as Graphics.AnimatedGraphicsComponent).StartAnimation(animationId); - AppManager.Instance.server.AddData(new GameManagers.NetworkManager.Updates.ServerToClient.UpdateAnimation() + if (AppManager.Instance.gamestate == GameState.HostPlaying) { - animationId = animationId, - IdEntity = Id - }); + (graphicsComponent as Graphics.AnimatedGraphicsComponent).StartAnimation(animationId); + AppManager.Instance.server.AddData(new GameManagers.NetworkManager.Updates.ServerToClient.UpdateAnimation() + { + animationId = animationId, + IdEntity = Id + }); + } } public override void Draw(SpriteBatch spriteBatch) { @@ -53,6 +56,14 @@ namespace ZoFo.GameCore.GameObjects base.Draw(spriteBatch); } + + public virtual void Delete() + { + if (AppManager.Instance.gamestate == GameState.HostPlaying) + { + AppManager.Instance.server.DeleteObject(this); + } + } } } diff --git a/ZoFo/GameCore/GameObjects/Entities/Interactables/Collectables/Ammo.cs b/ZoFo/GameCore/GameObjects/Entities/Interactables/Collectables/Ammo.cs index 25eddf3..6fb0824 100644 --- a/ZoFo/GameCore/GameObjects/Entities/Interactables/Collectables/Ammo.cs +++ b/ZoFo/GameCore/GameObjects/Entities/Interactables/Collectables/Ammo.cs @@ -13,34 +13,10 @@ using ZoFo.GameCore.GUI; namespace ZoFo.GameCore.GameObjects { - class Ammo : Collectable - { + class Ammo : Collectable + { public override StaticGraphicsComponent graphicsComponent { get; } = new(_path + "Ammo"); - public Ammo(Vector2 position) : base(position) - { - graphicsComponent.ObjectDrawRectangle.Width = 20; - graphicsComponent.ObjectDrawRectangle.Height = 20; - - collisionComponent.triggerRectangle = new Rectangle(0, 0, 20, 20); - } - public override void OnInteraction(GameObject sender) - { - DebugHUD.DebugLog("collected"); - if (AppManager.Instance.client.myPlayer.lootData.loots.Keys.Contains("Ammo")) - { - AppManager.Instance.client.myPlayer.lootData.loots["Ammo"] += 1; - } - else - { - AppManager.Instance.client.myPlayer.lootData.loots.Add("Ammo", 1); - } - AppManager.Instance.server.AddData(new UpdateLoot("Ammo")); - AppManager.Instance.server.DeleteObject(this); - } - public override void Draw(SpriteBatch spriteBatch) - { - DrawDebugRectangle(spriteBatch, collisionComponent.triggerRectangle.SetOrigin(position), Color.Blue); - base.Draw(spriteBatch); - } + public Ammo(Vector2 position) : base(position) { } + } } diff --git a/ZoFo/GameCore/GameObjects/Entities/Interactables/Collectables/Antiradine.cs b/ZoFo/GameCore/GameObjects/Entities/Interactables/Collectables/Antiradine.cs index b8f2bcb..ebba1fd 100644 --- a/ZoFo/GameCore/GameObjects/Entities/Interactables/Collectables/Antiradine.cs +++ b/ZoFo/GameCore/GameObjects/Entities/Interactables/Collectables/Antiradine.cs @@ -11,17 +11,9 @@ using ZoFo.GameCore.Graphics; namespace ZoFo.GameCore.GameObjects.Entities.Interactables.Collectables { - class Antiradine:Collectable + class Antiradine : Collectable { public override StaticGraphicsComponent graphicsComponent { get; } = new("Antiradine"); - public Antiradine(Vector2 position) : base(position) - { - - } - public override void OnInteraction(GameObject sender) - { - AppManager.Instance.server.AddData(new UpdateLoot("Antiradine")); - AppManager.Instance.server.DeleteObject(this); - } + public Antiradine(Vector2 position) : base(position) { } } } diff --git a/ZoFo/GameCore/GameObjects/Entities/Interactables/Collectables/BottleOfWater.cs b/ZoFo/GameCore/GameObjects/Entities/Interactables/Collectables/BottleOfWater.cs index 2e48992..79c7342 100644 --- a/ZoFo/GameCore/GameObjects/Entities/Interactables/Collectables/BottleOfWater.cs +++ b/ZoFo/GameCore/GameObjects/Entities/Interactables/Collectables/BottleOfWater.cs @@ -15,15 +15,7 @@ namespace ZoFo.GameCore.GameObjects public class BottleOfWater : Collectable { public override StaticGraphicsComponent graphicsComponent { get; } = new(_path + "BottleOfWater"); - public BottleOfWater(Vector2 position) : base(position) - { - graphicsComponent.ObjectDrawRectangle.Width = 20; - graphicsComponent.ObjectDrawRectangle.Height = 20; - } - public override void OnInteraction(GameObject sender) - { - AppManager.Instance.server.AddData(new UpdateLoot("BottleOfWater")); - AppManager.Instance.server.DeleteObject(this); - } + public BottleOfWater(Vector2 position) : base(position) { } + } } diff --git a/ZoFo/GameCore/GameObjects/Entities/Interactables/Collectables/Collectable.cs b/ZoFo/GameCore/GameObjects/Entities/Interactables/Collectables/Collectable.cs index 157fefc..ec5d4af 100644 --- a/ZoFo/GameCore/GameObjects/Entities/Interactables/Collectables/Collectable.cs +++ b/ZoFo/GameCore/GameObjects/Entities/Interactables/Collectables/Collectable.cs @@ -1,21 +1,44 @@ using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; using System; +using System.Linq; using ZoFo.GameCore.GameManagers; using ZoFo.GameCore.GameManagers.CollisionManager; using ZoFo.GameCore.GameManagers.NetworkManager.Updates.ServerToClient; +using ZoFo.GameCore.GUI; namespace ZoFo.GameCore.GameObjects; public class Collectable : Interactable { - protected static readonly string _path = "Textures/icons/Collectables/"; - public Collectable(Vector2 position) : base(position) - { + protected static readonly string _path = "Content/Textures/icons/Collectables/"; + public Collectable(Vector2 position) : base(position) { + + graphicsComponent.ObjectDrawRectangle.Width = 20; + graphicsComponent.ObjectDrawRectangle.Height = 20; + + collisionComponent.triggerRectangle.Width = 20; + collisionComponent.triggerRectangle.Height = 20; + + + int size = 10; + collisionComponent.triggerRectangle.X -= size; + collisionComponent.triggerRectangle.Y -= size; + collisionComponent.triggerRectangle.Width += 2*size; + collisionComponent.triggerRectangle.Height += 2*size; } public override void OnInteraction(GameObject sender) { - // - AppManager.Instance.server.AddData(new UpdateLoot()); + DebugHUD.DebugLog("collected"); + string lootname = this.GetType().ToString().ToLower().Split('.').Last(); + (sender as Player).lootData.AddLoot(lootname, 1, (sender as Player).Id); AppManager.Instance.server.DeleteObject(this); + base.OnInteraction(sender); } + public override void Draw(SpriteBatch spriteBatch) + { + DrawDebugRectangle(spriteBatch, collisionComponent.triggerRectangle.SetOrigin(position), Color.Blue); + base.Draw(spriteBatch); + } + } diff --git a/ZoFo/GameCore/GameObjects/Entities/Interactables/Collectables/Peeble.cs b/ZoFo/GameCore/GameObjects/Entities/Interactables/Collectables/Peeble.cs index b031bdd..b2c36e6 100644 --- a/ZoFo/GameCore/GameObjects/Entities/Interactables/Collectables/Peeble.cs +++ b/ZoFo/GameCore/GameObjects/Entities/Interactables/Collectables/Peeble.cs @@ -16,15 +16,6 @@ namespace ZoFo.GameCore.GameObjects { public override StaticGraphicsComponent graphicsComponent { get; } = new(_path + "Peeble"); - public Peeble(Vector2 position) : base(position) - { - graphicsComponent.ObjectDrawRectangle.Width = 20; - graphicsComponent.ObjectDrawRectangle.Height = 20; - } - public override void OnInteraction(GameObject sender) - { - AppManager.Instance.server.AddData(new UpdateLoot("Peeble")); - AppManager.Instance.server.DeleteObject(this); - } + public Peeble(Vector2 position) : base(position) { } } } diff --git a/ZoFo/GameCore/GameObjects/Entities/Interactables/Collectables/PureBottleOfWater.cs b/ZoFo/GameCore/GameObjects/Entities/Interactables/Collectables/PureBottleOfWater.cs index f32d070..045db23 100644 --- a/ZoFo/GameCore/GameObjects/Entities/Interactables/Collectables/PureBottleOfWater.cs +++ b/ZoFo/GameCore/GameObjects/Entities/Interactables/Collectables/PureBottleOfWater.cs @@ -15,15 +15,6 @@ namespace ZoFo.GameCore.GameObjects { public override StaticGraphicsComponent graphicsComponent { get; } = new(_path + "PureBottleOfWater"); - public PureBottleOfWater(Vector2 position) : base(position) - { - graphicsComponent.ObjectDrawRectangle.Width = 20; - graphicsComponent.ObjectDrawRectangle.Height = 20; - } - public override void OnInteraction(GameObject sender) - { - AppManager.Instance.server.AddData(new UpdateLoot("PureBottleOfWater")); - AppManager.Instance.server.DeleteObject(this); - } + public PureBottleOfWater(Vector2 position) : base(position) { } } } diff --git a/ZoFo/GameCore/GameObjects/Entities/Interactables/Collectables/RottenFlesh.cs b/ZoFo/GameCore/GameObjects/Entities/Interactables/Collectables/RottenFlesh.cs index 68a7a0a..71223b9 100644 --- a/ZoFo/GameCore/GameObjects/Entities/Interactables/Collectables/RottenFlesh.cs +++ b/ZoFo/GameCore/GameObjects/Entities/Interactables/Collectables/RottenFlesh.cs @@ -14,15 +14,6 @@ namespace ZoFo.GameCore.GameObjects class RottenFlesh:Collectable { public override StaticGraphicsComponent graphicsComponent { get; } = new(_path + "RottenFlesh"); - public RottenFlesh(Vector2 position) : base(position) - { - graphicsComponent.ObjectDrawRectangle.Width = 20; - graphicsComponent.ObjectDrawRectangle.Height = 20; - } - public override void OnInteraction(GameObject sender) - { - AppManager.Instance.server.AddData(new UpdateLoot("RottenFlesh")); - AppManager.Instance.server.DeleteObject(this); - } + public RottenFlesh(Vector2 position) : base(position) { } } } diff --git a/ZoFo/GameCore/GameObjects/Entities/Interactables/Collectables/Steel.cs b/ZoFo/GameCore/GameObjects/Entities/Interactables/Collectables/Steel.cs index 21f5311..40a3c5c 100644 --- a/ZoFo/GameCore/GameObjects/Entities/Interactables/Collectables/Steel.cs +++ b/ZoFo/GameCore/GameObjects/Entities/Interactables/Collectables/Steel.cs @@ -15,15 +15,7 @@ namespace ZoFo.GameCore.GameObjects { public override StaticGraphicsComponent graphicsComponent { get; } = new(_path + "Steel"); - public Steel(Vector2 position) : base(position) - { - graphicsComponent.ObjectDrawRectangle.Width = 20; - graphicsComponent.ObjectDrawRectangle.Height = 20; - } - public override void OnInteraction(GameObject sender) - { - AppManager.Instance.server.AddData(new UpdateLoot("Steel")); - AppManager.Instance.server.DeleteObject(this); - } + public Steel(Vector2 position) : base(position) { } + } } diff --git a/ZoFo/GameCore/GameObjects/Entities/Interactables/Collectables/Wood.cs b/ZoFo/GameCore/GameObjects/Entities/Interactables/Collectables/Wood.cs index 7cfad32..6c2a945 100644 --- a/ZoFo/GameCore/GameObjects/Entities/Interactables/Collectables/Wood.cs +++ b/ZoFo/GameCore/GameObjects/Entities/Interactables/Collectables/Wood.cs @@ -11,14 +11,5 @@ public class Wood : Collectable { public override StaticGraphicsComponent graphicsComponent { get; } = new(_path + "Wood"); - public Wood(Vector2 position) : base(position) - { - graphicsComponent.ObjectDrawRectangle.Width = 20; - graphicsComponent.ObjectDrawRectangle.Height = 20; - } - public override void OnInteraction(GameObject sender) - { - AppManager.Instance.server.AddData(new UpdateLoot("Wood")); - AppManager.Instance.server.DeleteObject(this); - } + public Wood(Vector2 position) : base(position) { } } \ No newline at end of file diff --git a/ZoFo/GameCore/GameObjects/Entities/Interactables/Interactable.cs b/ZoFo/GameCore/GameObjects/Entities/Interactables/Interactable.cs index 59ba21d..6ce7d6d 100644 --- a/ZoFo/GameCore/GameObjects/Entities/Interactables/Interactable.cs +++ b/ZoFo/GameCore/GameObjects/Entities/Interactables/Interactable.cs @@ -4,6 +4,7 @@ using ZoFo.GameCore.GameManagers.CollisionManager; using ZoFo.GameCore.GameManagers.NetworkManager.Updates.ServerToClient; using ZoFo.GameCore.GameObjects.Entities.LivingEntities.Player; using ZoFo.GameCore.Graphics; +using ZoFo.GameCore.GUI; namespace ZoFo.GameCore.GameObjects; @@ -27,6 +28,6 @@ public class Interactable : Entity public virtual void OnInteraction(GameObject sender) { - + } } \ No newline at end of file diff --git a/ZoFo/GameCore/GameObjects/Entities/LivingEntities/Enemies/Enemy.cs b/ZoFo/GameCore/GameObjects/Entities/LivingEntities/Enemies/Enemy.cs index d602ede..22e4a35 100644 --- a/ZoFo/GameCore/GameObjects/Entities/LivingEntities/Enemies/Enemy.cs +++ b/ZoFo/GameCore/GameObjects/Entities/LivingEntities/Enemies/Enemy.cs @@ -4,18 +4,38 @@ using System.Net.Mime; using System.Reflection; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; +using ZoFo.GameCore.GameManagers; +using ZoFo.GameCore.Graphics; namespace ZoFo.GameCore.GameObjects; public class Enemy : LivingEntity { protected float speed; - protected int health; + protected float health = 5; + public bool isAttacking; + public bool isDying; + public Enemy(Vector2 position) : base(position) { } public override void Update() { - + } + public virtual void TakeDamage(float damage) + { + if (isDying) return; + health -= damage; + if (health < 0) + Die(); + } + public override void Die() + { + isDying = true; + base.Die(); + } + public override void DeathEnd() + { + Delete(); } } \ No newline at end of file diff --git a/ZoFo/GameCore/GameObjects/Entities/LivingEntities/Enemies/Zombie.cs b/ZoFo/GameCore/GameObjects/Entities/LivingEntities/Enemies/Zombie.cs index 09db9b5..ae79885 100644 --- a/ZoFo/GameCore/GameObjects/Entities/LivingEntities/Enemies/Zombie.cs +++ b/ZoFo/GameCore/GameObjects/Entities/LivingEntities/Enemies/Zombie.cs @@ -18,7 +18,7 @@ namespace ZoFo.GameCore.GameObjects class Zombie : Enemy { public override GraphicsComponent graphicsComponent { get; } = new AnimatedGraphicsComponent(new List { "zombie_damaged", "zombie_walk", "zombie_idle", "zombie_attack", "zombie_death" }, "zombie_walk"); - public bool isAttacking; + public Zombie(Vector2 position) : base(position) { health = 5; @@ -29,22 +29,52 @@ namespace ZoFo.GameCore.GameObjects StartAnimation("zombie_walk"); collisionComponent.isTrigger = true; collisionComponent.hasCollision = true; - (graphicsComponent as AnimatedGraphicsComponent).actionOfAnimationEnd += EndAttack; + (graphicsComponent as AnimatedGraphicsComponent).actionOfAnimationEnd += (animationIdEnded)=>{ + if (animationIdEnded == "zombie_attack") + EndAttack(animationIdEnded); + }; collisionComponent.OnTriggerZone += OnPlayerClose; collisionComponent.triggerRectangle = new Rectangle(-5, -5, 40, 40); + (graphicsComponent as AnimatedGraphicsComponent).actionOfAnimationEnd += (str) => + { + if (str == "zombie_death") + DeathEnd(); + }; } public override void Update() - { - Vector2 duration = Vector2.Normalize( - AppManager.Instance.server.players[0].position - position + { + if (isDying) return; + float m = 10000000; + int j = -1; + for (int i = 0; i < AppManager.Instance.server.players.Count; i++) + { + var player = AppManager.Instance.server.players[i]; + if (m > (player.position.X - position.X) * (player.position.X - position.X) + (player.position.Y - position.Y) * (player.position.Y - position.Y)) + { + m = (player.position.X - position.X) * (player.position.X - position.X) + (player.position.Y - position.Y) * (player.position.Y - position.Y); + j = i; + } + } + Vector2 duration = Vector2.Zero; + if (m<= 130000) + { + duration = Vector2.Normalize( + AppManager.Instance.server.players[j].position - position ); + if (Random.Shared.NextDouble() > 0.999) + { + AppManager.Instance.SoundManager.StartSound("zombie sound", position, AppManager.Instance.server.players[0].position, pitch: new Random().Next(-1, 2) * (float)new Random().NextDouble()); + } + } - - - + if (!isAttacking) { velocity += new Vector2(duration.X * speed, duration.Y * speed); } + + + + } public void OnPlayerClose(GameObject sender) { @@ -52,6 +82,8 @@ namespace ZoFo.GameCore.GameObjects if(!isAttacking) { + + AppManager.Instance.SoundManager.StartSound("Zombi napal", position, AppManager.Instance.server.players[0].position,pitch:new Random().Next(-1,2)*(float)new Random().NextDouble()); StartAnimation("zombie_attack"); isAttacking = true; } @@ -60,18 +92,39 @@ namespace ZoFo.GameCore.GameObjects } public void EndAttack(string a) - { + { + if (AppManager.Instance.server is null) return; var damagedPlayers=AppManager.Instance.server.collisionManager.GetPlayersInZone(collisionComponent.triggerRectangle.SetOrigin(position)); //TODO ДАМАЖИТЬ ИГРОКОВ В ЗОНЕ if (damagedPlayers.Length>0) { DebugHUD.DebugLog("End of" + a); - AppManager.Instance.server.DeleteObject(this); + foreach (var item in damagedPlayers) + item.TakeDamage(1); } - isAttacking = false; + + } + + public override void Die() + { + StartAnimation("zombie_death"); + base.Die(); + } + public override void DeathEnd() + { + + Instantiate(new Particle(collisionComponent.stopRectangle.Location.ToVector2() + position + ExtentionClass.RandomVector() * 20)); + Instantiate(new Particle(collisionComponent.stopRectangle.Location.ToVector2() + position + ExtentionClass.RandomVector() * 20)); + Instantiate(new Particle(collisionComponent.stopRectangle.Location.ToVector2() + position + ExtentionClass.RandomVector() * 20)); + + base.DeathEnd(); } public override void Draw(SpriteBatch spriteBatch) { DrawDebugRectangle(spriteBatch, collisionComponent.triggerRectangle.SetOrigin(position), Color.Blue); base.Draw(spriteBatch); } + public override void TakeDamage(float damage) + { + base.TakeDamage(damage); + } } } diff --git a/ZoFo/GameCore/GameObjects/Entities/LivingEntities/LivingEntity.cs b/ZoFo/GameCore/GameObjects/Entities/LivingEntities/LivingEntity.cs index e0039af..0104778 100644 --- a/ZoFo/GameCore/GameObjects/Entities/LivingEntities/LivingEntity.cs +++ b/ZoFo/GameCore/GameObjects/Entities/LivingEntities/LivingEntity.cs @@ -13,12 +13,10 @@ public class LivingEntity : Entity /// Переменная для заявки на передвижения, т.е. то, на сколько вы хотите, чтобы в этом кадре переместился объект /// public Vector2 velocity; - - private InputManager inputManager; + public LivingEntity(Vector2 position) : base(position) - { - inputManager = new InputManager(); + { collisionComponent.hasCollision = true; } @@ -40,17 +38,28 @@ public class LivingEntity : Entity { base.UpdateAnimations(); } - Vector2 prevPosition_forClient; + protected Vector2 prevPosition_forClient; public override void Draw(SpriteBatch spriteBatch) { - if ((position - prevPosition_forClient).X < 0) + if ((positionDraw - prevPosition_forClient).X < 0) graphicsComponent.Flip = SpriteEffects.FlipHorizontally; - else if ((position - prevPosition_forClient).X > 0) + else if ((positionDraw - prevPosition_forClient).X > 0) graphicsComponent.Flip = SpriteEffects.None; base.Draw(spriteBatch); - prevPosition_forClient = position; + prevPosition_forClient = positionDraw; } + public virtual void Die() + { + //deathSound + animationStart + } + public virtual void DeathEnd() + { + //deathSound + animationStart + Delete(); + } + + } diff --git a/ZoFo/GameCore/GameObjects/Entities/LivingEntities/Player/IPlayerWeaponAttack.cs b/ZoFo/GameCore/GameObjects/Entities/LivingEntities/Player/IPlayerWeaponAttack.cs index 3fafa2b..daaa390 100644 --- a/ZoFo/GameCore/GameObjects/Entities/LivingEntities/Player/IPlayerWeaponAttack.cs +++ b/ZoFo/GameCore/GameObjects/Entities/LivingEntities/Player/IPlayerWeaponAttack.cs @@ -8,6 +8,6 @@ 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 index 8180247..075ba4f 100644 --- a/ZoFo/GameCore/GameObjects/Entities/LivingEntities/Player/LootData.cs +++ b/ZoFo/GameCore/GameObjects/Entities/LivingEntities/Player/LootData.cs @@ -3,6 +3,9 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using ZoFo.GameCore.GameManagers; +using ZoFo.GameCore.GameManagers.NetworkManager.Updates.ServerToClient; +using ZoFo.GameCore.GUI; namespace ZoFo.GameCore.GameObjects { @@ -10,9 +13,28 @@ namespace ZoFo.GameCore.GameObjects { public Dictionary loots; - public void AddLoot(string lootName, int quantity) + public void AddLoot(string lootName, int quantity, int id) { - loots.Add(lootName, quantity); + if (lootName == null) + { + DebugHUD.DebugLog("PROBLEM, loot is null"); + DebugHUD.DebugLog("PROBLEM, loot is null"); + DebugHUD.DebugLog("PROBLEM, loot is null"); + return; + } + AppManager.Instance.server.AddData(new UpdateLoot(lootName, quantity, id)); + + if (loots.ContainsKey(lootName)) + loots[lootName] +=quantity; + else + loots.Add(lootName, quantity); + } + public void AddLoot_Client(string lootName, int quantity) + { + if (loots.ContainsKey(lootName)) + loots[lootName] +=quantity; + else + loots.Add(lootName, quantity); } } } diff --git a/ZoFo/GameCore/GameObjects/Entities/LivingEntities/Player/Player.cs b/ZoFo/GameCore/GameObjects/Entities/LivingEntities/Player/Player.cs index f4760c1..ae236ec 100644 --- a/ZoFo/GameCore/GameObjects/Entities/LivingEntities/Player/Player.cs +++ b/ZoFo/GameCore/GameObjects/Entities/LivingEntities/Player/Player.cs @@ -11,6 +11,7 @@ using ZoFo.GameCore.GameManagers.NetworkManager.Updates.ServerToClient; using ZoFo.GameCore.Graphics; using System.Diagnostics; using ZoFo.GameCore.GUI; +using System.Runtime.InteropServices; namespace ZoFo.GameCore.GameObjects; @@ -18,14 +19,21 @@ public class Player : LivingEntity { public Vector2 InputWeaponRotation { get; set; } public Vector2 InputPlayerRotation { get; set; } - - private float speed; - public int health = 100; - public int rad = 0; - public LootData lootData; - - public override GraphicsComponent graphicsComponent { get; } = new AnimatedGraphicsComponent(AppManager.Instance.AssetManager.Player); + private float speed; + public int reloading; + public float health = 100; + public float MaxHealth = 100; + + public override GraphicsComponent graphicsComponent { get; } = new AnimatedGraphicsComponent(AppManager.Instance.AssetManager.Player.Animations, AppManager.Instance.AssetManager.Player.IdleAnimation); + + public AnimatedGraphicsComponent animatedGraphicsComponent => graphicsComponent as AnimatedGraphicsComponent; + + public float rad = 0; + public float MaxRad = 100; + public LootData lootData; + Vector2 prevPosition; + public bool IsTryingToInteract { get; set; } @@ -33,83 +41,255 @@ public class Player : LivingEntity /// Факт того, что плеер в этом апдейте пытается стрелять /// public bool IsTryingToShoot { get; set; } + + ScopeState prevScopeState; public Player(Vector2 position) : base(position) { lootData = new LootData(); lootData.loots = new Dictionary(); graphicsComponent.ObjectDrawRectangle = new Rectangle(0, 0, 30, 30); - collisionComponent.stopRectangle = new Rectangle(0, 20, 30, 10); - speed = 5; + collisionComponent.stopRectangle = new Rectangle(10, 15, 10, 15); + speed = 5; - StartAnimation("player_look_down"); + StartAnimation("player_look_down"); } - public override void Update() + public override void Update() { - #region анимация управления, стрельбы - switch(AppManager.Instance.InputManager.ConvertVector2ToState(InputPlayerRotation)) + #region название current текстуры + var idName = animatedGraphicsComponent.CurrentAnimation.Id; + #endregion + + #region анимация управления подбора лута + DebugHUD.DebugSet("texture name", idName); + if (reloading > 0) + { + reloading--; + + } + + switch (AppManager.Instance.InputManager.ConvertVector2ToState(InputPlayerRotation)) { case ScopeState.Top: - + if (idName != "player_run_up") + StartAnimation("player_run_up"); break; case ScopeState.Down: - - break; + if (idName != "player_run_down") + StartAnimation("player_run_down"); + break; case ScopeState.Right: - //StartAnimation("player_running_top_rotate"); - break; case ScopeState.Left: - - break; + if (idName != "player_run_right") + StartAnimation("player_run_right"); + break; case ScopeState.TopRight: - - break; case ScopeState.TopLeft: - - break; + if (idName != "player_run_right_up") + StartAnimation("player_run_right_up"); + break; case ScopeState.DownRight: - - break; case ScopeState.DownLeft: - - break; + if (idName != "player_run_right_down") + StartAnimation("player_run_right_down"); + break; + case ScopeState.Idle: + if (idName != "player_look_down") + StartAnimation("player_look_down"); + break; + } + if (AppManager.Instance.InputManager.ConvertVector2ToState(InputPlayerRotation) != ScopeState.Idle) + { + prevScopeState = AppManager.Instance.InputManager.ConvertVector2ToState(InputPlayerRotation); + } + else if (AppManager.Instance.InputManager.ConvertVector2ToState(InputPlayerRotation) == ScopeState.Idle && false) + { + + + + + switch (prevScopeState) + { + case ScopeState.Top: + if (idName != "player_look_up_weapon") + StartAnimation("player_look_up_weapon"); + break; + case ScopeState.Down: + if (idName != "player_look_down_weapon") + StartAnimation("player_look_down_weapon"); + break; + case ScopeState.Right: + case ScopeState.Left: + if (idName != "player_look_right_down_weapon") + StartAnimation("player_look_right_down_weapon"); + break; + case ScopeState.TopRight: + case ScopeState.TopLeft: + if (idName != "player_look_right_up_weapon") + StartAnimation("player_look_right_up_weapon"); + break; + case ScopeState.DownRight: + case ScopeState.DownLeft: + if (idName != "player_look_right_down_weapon") + StartAnimation("player_look_right_down_weapon"); + break; + case ScopeState.Idle: + if (idName != "player_look_down") + StartAnimation("player_look_down"); + break; + } + + + + + + } + + + + + #endregion + + #region анимация поворота оружия + int currentAttackSection = AppManager.Instance.InputManager.ConvertAttackVector2ToState(InputWeaponRotation); + switch (currentAttackSection) + { + case 0 or 1: + //right + break; + case 2 or 3: + //down_right_right + break; + case 4 or 5: + //down_right + break; + case 6 or 7: + //down_right_left + break; + case 8 or 9: + //down + break; + case 10 or 11: + //down_left_right + break; + case 12 or 13: + //down_left + break; + case 14 or 15: + //down_left_left + break; + case 16 or -14: + //left + break; + case -13 or -12: + //top_left_left + break; + case -11 or -10: + //top_left + break; + case -9 or -8: + //top_left_right + break; + case -7 or -6: + //top + break; + case -5 or -4: + //top_right_left + break; + case -3 or -2: + //top_right + break; + case -1 or 0: + //top_right_right + break; } #endregion + MovementLogic(); } - public void MovementLogic() + public void WeaponAttack() { - velocity += InputPlayerRotation * speed; + + } + public void MovementLogic() + { + velocity += InputPlayerRotation * speed; + DebugHUD.DebugSet("player pos server", position.ToString()); } public void HandleNewInput(UpdateInput updateInput) { - InputPlayerRotation = updateInput.InputMovementDirection; - InputWeaponRotation = updateInput.InputAttackDirection; - + InputPlayerRotation = updateInput.InputMovementDirection.GetVector2(); + InputWeaponRotation = updateInput.InputAttackDirection.GetVector2(); + DebugHUD.DebugSet("dir", InputWeaponRotation.ToString()); } public void HandleInteract(UpdateInputInteraction updateInputInteraction) { IsTryingToInteract = true; } + + #region MyRegion + + public bool isDying; + public virtual void TakeDamage(float damage) + { + if (isDying) return; + health -= damage; + AppManager.Instance.server.AddData(new UpdatePlayerParametrs() { health = health, radiatoin = rad, IdEntity = Id }); + if (health < 0) + Die(); + } + public override void Die() + { + base.Die(); + } + + #endregion public void HandleShoot(UpdateInputShoot updateInputShoot) { + if (reloading > 0) + return; + reloading = 5; IsTryingToShoot = true; - var rect = collisionComponent.stopRectangle.SetOrigin(position); - rect.Width += 100; - rect.Height += 100; - Entity[] entities = AppManager.Instance.server.collisionManager.GetEntities(rect, this); - if (entities.Length>0) + Entity[] entities = AppManager.Instance.server.collisionManager.GetEntities(GetDamageArea(InputWeaponRotation), this); + if (entities != null) { - DebugHUD.DebugSet("ent[0]", entities[0].ToString()); - if (entities != null) + foreach (Entity entity in entities) { - foreach (Entity entity in entities) + if (entity is Enemy) { - AppManager.Instance.server.DeleteObject(entity); + for (int i = 0; i < 3; i++) + { + Instantiate(new Particle( + ((position - graphicsComponent.ObjectDrawRectangle.Location.ToVector2()) * i / 3f) + + ((entity.position) * (3 - i) / 3f) + )); + + } + (entity as Enemy).TakeDamage(1); } } } } + public override void Draw(SpriteBatch spriteBatch) + { + + DrawDebugRectangle(spriteBatch, GetDamageArea(AppManager.Instance.InputManager.InputAttackDirection), Color.Green); + DrawDebugRectangle(spriteBatch, GetDamageArea(AppManager.Instance.InputManager.InputAttackDirection, 2), Color.Green); + DrawDebugRectangle(spriteBatch, GetDamageArea(AppManager.Instance.InputManager.InputAttackDirection, 3), Color.Green); + base.Draw(spriteBatch); + } + public Rectangle GetDamageArea(Vector2 direction, float mult = 1) + { + direction.Normalize(); + var rect = collisionComponent.stopRectangle.SetOrigin(position); + int size = 10; + rect.X -= size; + rect.Y -= size; + rect.Width += 2 * size; + rect.Height += 2 * size; + rect = rect.SetOrigin(direction * 40 * mult); + return rect; + } } \ No newline at end of file diff --git a/ZoFo/GameCore/GameObjects/Entities/LivingEntities/Player/PlayerAttacks/SwordAttack.cs b/ZoFo/GameCore/GameObjects/Entities/LivingEntities/Player/PlayerAttacks/SwordAttack.cs index 508f02f..9136797 100644 --- a/ZoFo/GameCore/GameObjects/Entities/LivingEntities/Player/PlayerAttacks/SwordAttack.cs +++ b/ZoFo/GameCore/GameObjects/Entities/LivingEntities/Player/PlayerAttacks/SwordAttack.cs @@ -1,13 +1,25 @@ using System; using System.Collections.Generic; +using System.Drawing; using System.Linq; +using System.Numerics; using System.Text; using System.Threading.Tasks; +using ZoFo.GameCore.GameManagers; +using ZoFo.GameCore.GameManagers.CollisionManager; +using ZoFo.GameCore.GameObjects.MapObjects.StopObjects; namespace ZoFo.GameCore.GameObjects.Entities.LivingEntities.Player.PlayerAttacks { internal class SwordAttack : IPlayerWeaponAttack { + Rectangle rectangle; + public SwordAttack(){ + } + public Rectangle Attack(Vector2 position){ + rectangle = new Rectangle((int)position.X, (int)position.Y, 30, 10); + return rectangle; + } } } diff --git a/ZoFo/GameCore/GameObjects/Entities/Particles/Particle.cs b/ZoFo/GameCore/GameObjects/Entities/Particles/Particle.cs new file mode 100644 index 0000000..a165996 --- /dev/null +++ b/ZoFo/GameCore/GameObjects/Entities/Particles/Particle.cs @@ -0,0 +1,32 @@ +using Microsoft.Xna.Framework; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using ZoFo.GameCore.GameManagers; +using ZoFo.GameCore.GameManagers.CollisionManager; +using ZoFo.GameCore.Graphics; + +namespace ZoFo.GameCore.GameObjects +{ + internal class Particle : GameObject + { + public override GraphicsComponent graphicsComponent { get; } = new AnimatedGraphicsComponent(new List { "explosion_1" }, "explosion_1"); + + public Particle(Vector2 position) : base(position) + { + graphicsComponent.ObjectDrawRectangle = new Rectangle(0, 0,60,60).SetOrigin(position); + AppManager.Instance.SoundManager.StartSound("gun-gunshot-01", Vector2.Zero, Vector2.Zero, 0.5f, (float)(Random.Shared.NextDouble()*2-1)); + (graphicsComponent as AnimatedGraphicsComponent).actionOfAnimationEnd += _ => { + + if (AppManager.Instance.client!=null) + { + AppManager.Instance.client.DeleteObject(this); + + } + + }; + } + } +} diff --git a/ZoFo/GameCore/GameObjects/GameObject.cs b/ZoFo/GameCore/GameObjects/GameObject.cs index 5e40de1..b94b084 100644 --- a/ZoFo/GameCore/GameObjects/GameObject.cs +++ b/ZoFo/GameCore/GameObjects/GameObject.cs @@ -24,6 +24,7 @@ public abstract class GameObject graphicsComponent.ObjectDrawRectangle.X = (int)position.X; graphicsComponent.ObjectDrawRectangle.Y = (int)position.Y; + positionDraw = position; } public virtual void UpdateLogic() { @@ -41,6 +42,13 @@ public abstract class GameObject graphicsComponent.Update(); } + public void Instantiate(GameObject gameObject) + { + if (AppManager.Instance.gamestate == GameState.HostPlaying) + { + AppManager.Instance.server.RegisterGameObject(gameObject); + } + } #endregion @@ -54,6 +62,7 @@ public abstract class GameObject public void PlayAnimation_OnClient() { graphicsComponent.Update(); + } /// @@ -65,14 +74,19 @@ public abstract class GameObject graphicsComponent.LoadContent(); } + /// + /// for smooth client draw + /// + public Vector2 positionDraw; /// /// Для клиента /// Обновление, которое вызывается у клиента, для просмотра анимаций /// public virtual void UpdateAnimations() { - graphicsComponent.ObjectDrawRectangle.X = (int)position.X; //Move To place where Updates Sets your position - graphicsComponent.ObjectDrawRectangle.Y = (int)position.Y; + positionDraw = (position * 0.15f + positionDraw*0.85f); + graphicsComponent.ObjectDrawRectangle.X = (int)positionDraw.X; //Move To place where Updates Sets your position + graphicsComponent.ObjectDrawRectangle.Y = (int)positionDraw.Y; PlayAnimation_OnClient(); } diff --git a/ZoFo/GameCore/Graphics/AnimatedGraphicsComponent.cs b/ZoFo/GameCore/Graphics/AnimatedGraphicsComponent.cs index 85c4a7e..b171d4c 100644 --- a/ZoFo/GameCore/Graphics/AnimatedGraphicsComponent.cs +++ b/ZoFo/GameCore/Graphics/AnimatedGraphicsComponent.cs @@ -136,7 +136,16 @@ namespace ZoFo.GameCore.Graphics buildSourceRectangle(); SetInterval(); + } + + public void StartCyclingAnimation(string startedanimationId) + { + currentFrame = 0; + currentAnimation = animations.Find(x => x.Id == startedanimationId); + currentAnimation.IsCycle = true; + buildSourceRectangle(); + SetInterval(); } public void StopAnimation() diff --git a/ZoFo/GameCore/Graphics/StaticGraphicsComponent.cs b/ZoFo/GameCore/Graphics/StaticGraphicsComponent.cs index d7f1dca..8ca7ec1 100644 --- a/ZoFo/GameCore/Graphics/StaticGraphicsComponent.cs +++ b/ZoFo/GameCore/Graphics/StaticGraphicsComponent.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.IO; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; @@ -37,7 +38,7 @@ namespace ZoFo.GameCore.Graphics return; } - texture = AppManager.Instance.Content.Load(_textureName); + texture = AppManager.Instance.Content.Load(Path.Combine(AppContext.BaseDirectory, _textureName)); } public override void Update() diff --git a/ZoFo/GameCore/Server.cs b/ZoFo/GameCore/Server.cs index eaa57fc..67c73c8 100644 --- a/ZoFo/GameCore/Server.cs +++ b/ZoFo/GameCore/Server.cs @@ -29,14 +29,13 @@ namespace ZoFo.GameCore public class Server { private ServerNetworkManager networkManager; - private int ticks = 0; - public IPEndPoint MyIp { get { return networkManager.InfoConnect; } } + private int ticks = 0; + public IPEndPoint MyIp { get { return networkManager.endPoint; } } public Server() { networkManager = new ServerNetworkManager(); - networkManager.GetDataSend += OnDataSend; collisionManager = new CollisionManager(); - + players = new List(); } #region server logic as App @@ -51,6 +50,13 @@ namespace ZoFo.GameCore ProcessIUpdateData(updateDatas[i]); } } + internal void UpdatesList(List updates) + { + foreach (var item in updates) + { + ProcessIUpdateData(item); + } + } /// /// Обработка апдейтсов, которые нам прислал клиент /// @@ -61,24 +67,6 @@ namespace ZoFo.GameCore //ТУТ Switch case будет честное слово switch (updateData.UpdateType) { - case "UpdateAnimation": - break; - case "UpdateEntityHealth": - break; - case "UpdateGameEnded": - break; - case "UpdateGameObjectCreated": - break; - case "UpdateGameObjectDeleted": - break; - case "UpdateInteraction": - break; - case "UpdateInteractionReady": - break; - case "UpdateLoot": - break; - case "UpdatePlayerParametrs": - break; case "UpdateInput": if (players.Count > 0) players[0].HandleNewInput(updateData as UpdateInput);//TODO id instead of 0 @@ -96,10 +84,6 @@ namespace ZoFo.GameCore } } - public void CloseConnection() - { - networkManager.CloseConnection(); - } /// /// Для красоты) Отдел Серверов @@ -115,9 +99,10 @@ namespace ZoFo.GameCore /// Создает комнату и запускает ожидание подключений /// /// - public void CreateRoom(int players) + public void CreateRoom(bool isMultiplayer) { - networkManager.Start(players); + networkManager.SetIsMultiplayer(isMultiplayer); + networkManager.Start(); } #endregion @@ -135,18 +120,14 @@ namespace ZoFo.GameCore collisionManager = new CollisionManager(); gameObjects = new List(); entities = new List(); - players = new List(); + networkManager.StartGame(); new MapManager().LoadMap(); - - //AppManager.Instance.server.RegisterGameObject(new EntittyForAnimationTests(new Vector2(0, 0))); - AppManager.Instance.server.RegisterGameObject(new Player(new Vector2(740, 140))); - for (int i = 0; i < 20; i++) - for (int j = 0; j < 20; j++) - AppManager.Instance.server.RegisterGameObject(new Zombie(new Vector2(1300 + i*70, 1000+j*70))); - - AppManager.Instance.server.RegisterGameObject(new Ammo(new Vector2(140, 440))); - AppManager.Instance.server.RegisterGameObject(new Ammo(new Vector2(240, 440))); - AppManager.Instance.server.RegisterGameObject(new ExitZone(new Vector2(240, 440))); + + AppManager.Instance.server.RegisterGameObject(new Player(new Vector2(760, 140))); + //for (int i = 0; i < 20; i++) + // for (int j = 0; j < 20; j++) + // AppManager.Instance.server.RegisterGameObject(new Zombie(new Vector2(1300 + i*70, 1000+j*70))); + } /// @@ -155,11 +136,11 @@ namespace ZoFo.GameCore public void EndGame() { UpdateGameEnded gameEnded = new UpdateGameEnded(); - networkManager.AddData(gameEnded); - // networkManager.CloseConnection(); + networkManager.AddData(gameEnded); + // networkManager.CloseConnection(); } - public List gameObjects; + public List gameObjects = new List(); public List entities; //entity public List players; public void Update(GameTime gameTime) @@ -187,11 +168,12 @@ namespace ZoFo.GameCore { gameObjects.Add(gameObject); + if (gameObject is StopObject) { AddData(new UpdateStopObjectCreated() { - Position = (gameObject as StopObject).position, + Position = (gameObject as StopObject).position.Serialize(), sourceRectangle = new SerializableRectangle((gameObject as StopObject).sourceRectangle), Size = new SerializablePoint((gameObject as StopObject).graphicsComponent.ObjectDrawRectangle.Size), tileSetName = ((gameObject as StopObject).graphicsComponent as StaticGraphicsComponent)._textureName, @@ -203,33 +185,45 @@ namespace ZoFo.GameCore } return; } + if (gameObject is MapObject) { AddData(new UpdateTileCreated() { - Position = (gameObject as MapObject).position, + Position = new SerializableVector2((gameObject as MapObject).position), sourceRectangle = new SerializableRectangle((gameObject as MapObject).sourceRectangle), Size = new SerializablePoint((gameObject as MapObject).graphicsComponent.ObjectDrawRectangle.Size), tileSetName = ((gameObject as MapObject).graphicsComponent as StaticGraphicsComponent)._textureName }); return; } + + if (gameObject is Particle) + { + + AddData(new UpdateGameObjectWithoutIdCreated() + { + GameObjectClassName = gameObject.GetType().Name, + position = gameObject.position.Serialize() + }); + return; + } if (gameObject is Entity entity) - { + { AddData(new UpdateGameObjectCreated() { GameObjectType = gameObject.GetType().Name, IdEntity = entity.Id, - position = gameObject.position - }); + position = gameObject.position.Serialize() + }); collisionManager.Register(entity.collisionComponent); entities.Add(entity); } - else + else AddData(new UpdateGameObjectCreated() { GameObjectType = gameObject.GetType().Name, - position = gameObject.position + position = gameObject.position.Serialize() }); diff --git a/ZoFo/GameSettings.txt b/ZoFo/GameSettings.txt index f5dcd93..5c15cbb 100644 --- a/ZoFo/GameSettings.txt +++ b/ZoFo/GameSettings.txt @@ -1 +1 @@ -{"IsFullScreen":false,"MainVolume":1.0,"MusicVolume":1.0,"SoundEffectsVolume":1.0,"Resolution":{"X":1440,"Y":900}} \ No newline at end of file +{"IsFullScreen":false,"MainVolume":1.0,"MusicVolume":0.0,"SoundEffectsVolume":1.0,"Resolution":{"X":1440,"Y":900}} \ No newline at end of file diff --git a/ZoFo/ZoFo.csproj b/ZoFo/ZoFo.csproj index 1fd87e3..85b8274 100644 --- a/ZoFo/ZoFo.csproj +++ b/ZoFo/ZoFo.csproj @@ -35,8 +35,8 @@ - - + +