Merge branch 'Development' into Collision

This commit is contained in:
SergoDobro 2024-08-16 00:36:01 +03:00 committed by GitHub
commit 9e4a14a92e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
35 changed files with 564 additions and 66 deletions

View file

@ -59,8 +59,8 @@ namespace MonogameLibrary.UI.Base
{ {
keyboardState = Keyboard.GetState(); keyboardState = Keyboard.GetState();
mouseState = Mouse.GetState(); mouseState = Mouse.GetState();
mouseState = new MouseState((int)(mouseState.X*(float)resolutionInGame.X/resolution.X), //mouseState = new MouseState((int)(mouseState.X*(float)resolutionInGame.X/resolution.X),
(int)(mouseState.Y * (float)resolutionInGame.Y / resolution.Y), mouseState.ScrollWheelValue, mouseState.LeftButton, mouseState.MiddleButton, mouseState.RightButton, mouseState.XButton1, mouseState.XButton2); // (int)(mouseState.Y * (float)resolutionInGame.Y / resolution.Y), mouseState.ScrollWheelValue, mouseState.LeftButton, mouseState.MiddleButton, mouseState.RightButton, mouseState.XButton1, mouseState.XButton2);
} }
catch catch
{ {

View file

@ -13,3 +13,29 @@
#---------------------------------- Content ---------------------------------# #---------------------------------- Content ---------------------------------#
#begin Fonts/Font.spritefont
/importer:FontDescriptionImporter
/processor:FontDescriptionProcessor
/processorParam:PremultiplyAlpha=True
/processorParam:TextureFormat=Compressed
/build:Fonts/Font.spritefont
#begin Fonts/Font2.spritefont
/importer:FontDescriptionImporter
/processor:FontDescriptionProcessor
/processorParam:PremultiplyAlpha=True
/processorParam:TextureFormat=Compressed
/build:Fonts/Font2.spritefont
#begin Textures/GUI/MenuBackground.jpg
/importer:TextureImporter
/processor:TextureProcessor
/processorParam:ColorKeyColor=255,0,255,255
/processorParam:ColorKeyEnabled=True
/processorParam:GenerateMipmaps=False
/processorParam:PremultiplyAlpha=True
/processorParam:ResizeToPowerOfTwo=False
/processorParam:MakeSquare=False
/processorParam:TextureFormat=Color
/build:Textures/GUI/MenuBackground.jpg

Binary file not shown.

Binary file not shown.

View file

@ -0,0 +1,60 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
This file contains an xml description of a font, and will be read by the XNA
Framework Content Pipeline. Follow the comments to customize the appearance
of the font in your game, and to change the characters which are available to draw
with.
-->
<XnaContent xmlns:Graphics="Microsoft.Xna.Framework.Content.Pipeline.Graphics">
<Asset Type="Graphics:FontDescription">
<!--
Modify this string to change the font that will be imported.
-->
<FontName>Debrosee-ALPnL.ttf</FontName>
<!--
Size is a float value, measured in points. Modify this value to change
the size of the font.
-->
<Size>100</Size>
<!--
Spacing is a float value, measured in pixels. Modify this value to change
the amount of spacing in between characters.
-->
<Spacing>0</Spacing>
<!--
UseKerning controls the layout of the font. If this value is true, kerning information
will be used when placing characters.
-->
<UseKerning>true</UseKerning>
<!--
Style controls the style of the font. Valid entries are "Regular", "Bold", "Italic",
and "Bold, Italic", and are case sensitive.
-->
<Style>Regular</Style>
<!--
If you uncomment this line, the default character will be substituted if you draw
or measure text that contains characters which were not included in the font.
-->
<!-- <DefaultCharacter>*</DefaultCharacter> -->
<!--
CharacterRegions control what letters are available in the font. Every
character from Start to End will be built and made available for drawing. The
default range is from 32, (ASCII space), to 126, ('~'), covering the basic Latin
character set. The characters are ordered according to the Unicode standard.
See the documentation for more information.
-->
<CharacterRegions>
<CharacterRegion>
<Start>&#32;</Start>
<End>&#126;</End>
</CharacterRegion>
</CharacterRegions>
</Asset>
</XnaContent>

View file

@ -0,0 +1,60 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
This file contains an xml description of a font, and will be read by the XNA
Framework Content Pipeline. Follow the comments to customize the appearance
of the font in your game, and to change the characters which are available to draw
with.
-->
<XnaContent xmlns:Graphics="Microsoft.Xna.Framework.Content.Pipeline.Graphics">
<Asset Type="Graphics:FontDescription">
<!--
Modify this string to change the font that will be imported.
-->
<FontName>CarltineRegular-K7z5l.ttf</FontName>
<!--
Size is a float value, measured in points. Modify this value to change
the size of the font.
-->
<Size>15</Size>
<!--
Spacing is a float value, measured in pixels. Modify this value to change
the amount of spacing in between characters.
-->
<Spacing>0</Spacing>
<!--
UseKerning controls the layout of the font. If this value is true, kerning information
will be used when placing characters.
-->
<UseKerning>true</UseKerning>
<!--
Style controls the style of the font. Valid entries are "Regular", "Bold", "Italic",
and "Bold, Italic", and are case sensitive.
-->
<Style>Regular</Style>
<!--
If you uncomment this line, the default character will be substituted if you draw
or measure text that contains characters which were not included in the font.
-->
<!-- <DefaultCharacter>*</DefaultCharacter> -->
<!--
CharacterRegions control what letters are available in the font. Every
character from Start to End will be built and made available for drawing. The
default range is from 32, (ASCII space), to 126, ('~'), covering the basic Latin
character set. The characters are ordered according to the Unicode standard.
See the documentation for more information.
-->
<CharacterRegions>
<CharacterRegion>
<Start>&#32;</Start>
<End>&#126;</End>
</CharacterRegion>
</CharacterRegions>
</Asset>
</XnaContent>

Binary file not shown.

After

Width:  |  Height:  |  Size: 592 KiB

View file

@ -1,14 +1,42 @@
using System.Collections.Generic;
using System.Text.Json;
using ZoFo.GameCore.GameManagers.NetworkManager;
using ZoFo.GameCore.GameManagers.NetworkManager.Updates;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
namespace ZoFo.GameCore namespace ZoFo.GameCore
{ {
public class Client public class Client
{ {
public void OnDataSend(string Data){ } ClientNetworkManager networkManager;
public Client()
{
networkManager = new ClientNetworkManager();
networkManager.GetDataSent += OnDataSend;
}
public void OnDataSend(string data)
{
List<IUpdateData> updateDatas = JsonSerializer.Deserialize<List<IUpdateData>>(data);
// тут будет switch
}
public void GameEndedUnexpectedly(){ } public void GameEndedUnexpectedly(){ }
public void JoinRoom(){ } public void JoinRoom(){ }
public void JoinYourself(){ } public void JoinYourself(){ }
internal void Update(GameTime gameTime)
{
}
internal void Draw(SpriteBatch spriteBatch)
{
}
} }
} }

View file

@ -9,6 +9,7 @@ using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Input;
using MonogameLibrary.UI.Base; using MonogameLibrary.UI.Base;
using MonogameLibrary.UI.Elements; using MonogameLibrary.UI.Elements;
using ZoFo.GameCore.GameManagers;
namespace ZoFo.GameCore.GUI; namespace ZoFo.GameCore.GUI;
@ -29,22 +30,27 @@ public abstract class AbstractGUI
private GraphicsDevice graphicsDevice; private GraphicsDevice graphicsDevice;
public virtual void Initialize() public virtual void Initialize()
{ {
// Manager.Initialize(AppManager.Instance.GraphicsDevice); Manager.Initialize(AppManager.Instance.GraphicsDevice);
CreateUI(); CreateUI();
} }
public virtual void LoadContent() public virtual void LoadContent()
{ {
Manager.LoadContent(AppManager.Instance.Content, "Font");
} }
public virtual void Update(GameTime gameTime) public virtual void Update(GameTime gameTime)
{ {
Manager.Update(gameTime);
} }
public virtual void Draw(SpriteBatch spriteBatch) public virtual void Draw(SpriteBatch spriteBatch)
{ {
Manager.Draw(spriteBatch); Manager.Draw(spriteBatch);
} }
public virtual void ResolutioChenges()
{
}
} }

View file

@ -0,0 +1,72 @@
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using MonogameLibrary.UI.Elements;
using static System.String;
using ZoFo.GameCore.GameManagers;
namespace ZoFo.GameCore.GUI;
public class DebugHUD
{
private SpriteFont _spriteFont;
private Dictionary<string, string> _text = new();
private List<string> _log = new();
public void Initialize()
{
}
public void LoadContent()
{
_spriteFont = AppManager.Instance.Content.Load<SpriteFont>("Fonts\\Font2");
}
public void Update(GameTime gameTime)
{
}
public void Draw(SpriteBatch spriteBatch)
{
var keysString = Join("\n", _text.Select(el => el.Key + ": " + el.Value).ToList());
spriteBatch.Begin();
spriteBatch.DrawString(
_spriteFont,
keysString,
new Vector2(10, 10),
Color.Cyan,
0,
Vector2.Zero,
1,
SpriteEffects.None,
0
);
spriteBatch.DrawString(
_spriteFont,
Join("\n", _log),
new Vector2(10, 10 + _spriteFont.MeasureString(keysString).Y),
Color.Green,
0,
Vector2.Zero,
1,
SpriteEffects.None,
0
);
spriteBatch.End();
}
public void Set(string key, string value)
{
_text[key] = value;
}
public void Log(string value)
{
_log.Add(value);
if (_log.Count > 30)
{
_log.RemoveAt(0);
}
}
}

View file

@ -9,19 +9,74 @@ using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Input;
using MonogameLibrary.UI.Base; using MonogameLibrary.UI.Base;
using MonogameLibrary.UI.Elements; using MonogameLibrary.UI.Elements;
using ZoFo.GameCore.GameManagers;
namespace ZoFo.GameCore.GUI; namespace ZoFo.GameCore.GUI;
public class MainMenuGUI : AbstractGUI public class MainMenuGUI : AbstractGUI
{ {
private DrawableUIElement menuBackground;
Color mainBackgroundColor = Color.White;
protected override void CreateUI() protected override void CreateUI()
{ {
// int width = AppManager.Instance.inGameHUDHelperResolution.X; int width = AppManager.Instance.CurentScreenResolution.X;
// int height = AppManager.Instance.inGameHUDHelperResolution.Y; int height = AppManager.Instance.CurentScreenResolution.Y;
menuBackground = new DrawableUIElement(Manager) { rectangle = new Rectangle(0, 0, width, height), mainColor = mainBackgroundColor, textureName = "Textures\\GUI\\MenuBackground" };
Elements.Add(menuBackground);
menuBackground.LoadTexture(AppManager.Instance.Content);
Elements.Add(new Label(Manager) { rectangle = new Rectangle(width / 2 - (int)(width / 8), height / 5, (int)(width / 4), (int)(height / 20)), text = "ZoFo", fontColor = Color.White, mainColor = Color.Transparent, scale = 0.9f, fontName = "Fonts\\Font"});
Button playButton = new Button(Manager)
{
rectangle = new Rectangle(width / 2 - (int)(width / 10), height / 3 + height / 20 + height / 40, (int)(width / 5), (int)(height / 20)),
text = "Play",
scale = 0.2f,
fontColor = Color.White,
mainColor = Color.Gray,
fontName = "Fonts\\Font"
};
playButton.LeftButtonPressed += () =>
{
};
Elements.Add(playButton);
Button optionButton = new Button(Manager)
{
rectangle = new Rectangle(width / 2 - (int)(width / 10), height / 3 + (height / 20 + height / 40) * 2, (int)(width / 5), (int)(height / 20)),
text = "Options",
scale = 0.2f,
fontColor = Color.White,
mainColor = Color.Gray,
fontName = "Fonts\\Font"
};
optionButton.LeftButtonPressed += () =>
{
};
Elements.Add(optionButton);
Button exitButton = new Button(Manager)
{
rectangle = new Rectangle(width / 2 - (int)(width / 10), height / 3 + (height / 20 + height / 40) * 3, (int)(width / 5), (int)(height / 20)),
text = "Exit",
scale = 0.2f,
fontColor = Color.White,
mainColor = Color.Gray,
fontName = "Fonts\\Font"
};
exitButton.LeftButtonPressed += () =>
{
AppManager.Instance.Exit();
};
Elements.Add(exitButton);
} }
public override void Update(GameTime gameTime) public override void Update(GameTime gameTime)
{ {
base.Update(gameTime);
} }
} }

View file

@ -8,8 +8,10 @@ using DangerousD.GameCore.Graphics;
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Input;
using ZoFo.GameCore.GameManagers.ItemManager;
using ZoFo.GameCore.GUI; using ZoFo.GameCore.GUI;
using static System.Collections.Specialized.BitVector32; using static System.Collections.Specialized.BitVector32;
using MonogameLibrary.UI.Base;
namespace ZoFo.GameCore.GameManagers namespace ZoFo.GameCore.GameManagers
{ {
@ -18,18 +20,22 @@ namespace ZoFo.GameCore.GameManagers
{ {
private GraphicsDeviceManager _graphics; private GraphicsDeviceManager _graphics;
private SpriteBatch _spriteBatch; private SpriteBatch _spriteBatch;
public static AppManager Instance { get; private set; } public static AppManager Instance { get; private set; }
public GameState gamestate; public GameState gamestate;
public AbstractGUI currentGUI; public AbstractGUI currentGUI;
//public Client client; public DebugHUD debugHud;
//public Server server; public Point CurentScreenResolution = new Point(1920, 1080);
public Client client;
public Server server;
#region Managers #region Managers
public InputManager InputManager; public InputManager InputManager;
public ItemManager.ItemManager ItemManager;
public AnimationBuilder animationBuilder{get;set; } public AnimationBuilder animationBuilder{get;set; }
@ -38,20 +44,28 @@ namespace ZoFo.GameCore.GameManagers
public AppManager() public AppManager()
{ {
_graphics = new GraphicsDeviceManager(this); _graphics = new GraphicsDeviceManager(this);
SetResolution(CurentScreenResolution.X, CurentScreenResolution.Y);
FulscrreenSwitch();
Content.RootDirectory = "Content"; Content.RootDirectory = "Content";
IsMouseVisible = true; IsMouseVisible = true;
Instance = this; Instance = this;
InputManager = new InputManager(); InputManager = new InputManager();
currentGUI = new MainMenuGUI();
debugHud = new DebugHUD();
} }
protected override void Initialize() protected override void Initialize()
{ {
currentGUI.Initialize();
debugHud.Initialize();
base.Initialize(); base.Initialize();
@ -60,7 +74,8 @@ namespace ZoFo.GameCore.GameManagers
protected override void LoadContent() protected override void LoadContent()
{ {
_spriteBatch = new SpriteBatch(GraphicsDevice); _spriteBatch = new SpriteBatch(GraphicsDevice);
debugHud.LoadContent();
currentGUI.LoadContent();
@ -71,19 +86,21 @@ namespace ZoFo.GameCore.GameManagers
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed ||
Keyboard.GetState().IsKeyDown(Keys.Escape)) Keyboard.GetState().IsKeyDown(Keys.Escape))
Exit(); Exit();
debugHud.Set("key", "value");
InputManager.Update(); InputManager.Update();
//currentGUI.Update(); currentGUI.Update(gameTime);
switch (gamestate) switch (gamestate)
{ {
case GameState.NotPlaying: case GameState.NotPlaying:
break; break;
case GameState.HostPlaying: case GameState.HostPlaying:
//server.Update(GameTime gameTime); server.Update(gameTime);
//client.Update(GameTime gameTime); client.Update(gameTime);
break; break;
case GameState.ClientPlaying: case GameState.ClientPlaying:
//server.Update(GameTime gameTime); server.Update(gameTime);
break; break;
default: default:
break; break;
@ -96,13 +113,15 @@ namespace ZoFo.GameCore.GameManagers
{ {
GraphicsDevice.Clear(Color.CornflowerBlue); GraphicsDevice.Clear(Color.CornflowerBlue);
//currentGUI.Draw(_spriteBatch); debugHud.Draw(_spriteBatch);
currentGUI.Draw(_spriteBatch);
switch (gamestate) switch (gamestate)
{ {
case GameState.ClientPlaying: case GameState.ClientPlaying:
case GameState.HostPlaying: case GameState.HostPlaying:
//client.Draw(_spriteBatch); client.Draw(_spriteBatch);
break; break;
case GameState.NotPlaying: case GameState.NotPlaying:
default: default:
@ -118,13 +137,22 @@ namespace ZoFo.GameCore.GameManagers
public void SetGUI(AbstractGUI gui) public void SetGUI(AbstractGUI gui)
{ {
currentGUI = gui; currentGUI = gui;
//TODO
} }
public void GameEnded(Dictionary<string, int> lootIGot) public void GameEnded(Dictionary<string, int> lootIGot)
{ {
//TODO //TODO
} }
public void SetResolution(int x, int y)
{
_graphics.PreferredBackBufferWidth = x;
_graphics.PreferredBackBufferHeight = y;
}
public void FulscrreenSwitch()
{
_graphics.IsFullScreen = !_graphics.IsFullScreen;
}
} }
} }

View file

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ZoFo.GameCore.GameManagers.ItemManager
{
class EquippableItemInfo : ItemInfo
{
bool IsEquiped; //экипирован ли предмет
public EquippableItemInfo(string tag) : base(tag)
{
}
}
}

View file

@ -15,10 +15,23 @@ namespace ZoFo.GameCore.GameManagers.ItemManager
Texture2D itemTexture; Texture2D itemTexture;
bool isCraftable; bool isCraftable;
Dictionary<string, int> resourcesNeededToCraft; Dictionary<string, int> resourcesNeededToCraft;
public ItemInfo (string tag)
{
this.tag = tag;
}
public ItemInfo(string tag,string textureName,bool isCraftable, Dictionary<string, int> resourcesNeededToCraft)
{
this.tag = tag;
this.textureName = textureName;
this.isCraftable = isCraftable;
this.resourcesNeededToCraft = resourcesNeededToCraft;
}
//методы //методы
private void LoadTexture() public void LoadTexture()
{ {
//я что-то хз как это //я что-то хз как это
itemTexture=AppManager.Instance.Content.Load<Texture2D>(textureName);
} }
} }
} }

View file

@ -6,7 +6,7 @@ using System.Threading.Tasks;
namespace ZoFo.GameCore.GameManagers.ItemManager namespace ZoFo.GameCore.GameManagers.ItemManager
{ {
class ItemManager public class ItemManager
{ {
//поля //поля
Dictionary<string, ItemInfo> tagItemPairs; Dictionary<string, ItemInfo> tagItemPairs;
@ -15,9 +15,18 @@ namespace ZoFo.GameCore.GameManagers.ItemManager
{ {
return tagItemPairs.GetValueOrDefault(tag); return tagItemPairs.GetValueOrDefault(tag);
} }
void LoadItemTexture() void LoadItemTextures()
{ {
foreach (var item in tagItemPairs)
{
item.Value.LoadTexture();
}
}
void Initialize()
{
tagItemPairs.Add("wood", new ItemInfo("wood","wood",false,null));
tagItemPairs.Add("rock", new ItemInfo("rock", "rock", false, null));
tagItemPairs.Add("steel", new ItemInfo("steel", "steel", false, null));
} }
} }

View file

@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ZoFo.GameCore.GameManagers.ItemManager
{
/// <summary>
/// Класс хранит информацю о количестве ресурсов у игрока
/// </summary>
internal class PlayerData
{
Dictionary<string, int> items;
/// <summary>
/// Принимает тэг и крафтит этот объект
/// </summary>
/// <param name="itemTag"></param>
public void CraftItem(string itemTag)
{
//TODO
}
}
}

View file

@ -6,9 +6,13 @@ using System.Threading.Tasks;
namespace ZoFo.GameCore.GameManagers.ItemManager namespace ZoFo.GameCore.GameManagers.ItemManager
{ {
class WeaponItemInfo:ItemInfo class WeaponItemInfo: EquippableItemInfo
{ {
//поля //поля
float damage; float damage;
public WeaponItemInfo(string tag) : base(tag)
{
}
} }
} }

View file

@ -1,55 +1,85 @@
using System; using System;
using System.Collections.Generic;
using System.Data.SqlTypes; using System.Data.SqlTypes;
using System.Net; using System.Net;
using System.Net.Sockets; using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates; using System.Security.Cryptography.X509Certificates;
using System.Text; using System.Text;
using System.Threading; using System.Threading;
using System.Threading.Tasks;
using ZoFo.GameCore.GameManagers.NetworkManager.Updates;
namespace ZoFo.GameCore.GameManagers.NetworkManager namespace ZoFo.GameCore.GameManagers.NetworkManager
{ {
public class ClientNetworkManager public class ClientNetworkManager
{ {
private IPAddress iPAddress = IPAddress.Any;
private int port = 7632; private int port = 7632;
private EndPoint endPoint; private EndPoint endPoint;
private Socket socket; private Socket socket;
delegate void OnDataSent(string Data); List<IUpdateData> updates = new List<IUpdateData>();
event OnDataSent GetDataSent; // event public delegate void OnDataSent(string Data);
public event OnDataSent GetDataSent; // event
public void Init() //create endPoint, socket public void Init() //create endPoint, socket
{ {
endPoint = new IPEndPoint(iPAddress, port);
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
} }
public void SendData() public void SendData()
{ {
while(socket.Connected)
{
byte[] bytes = Encoding.UTF8.GetBytes(updates.ToString());
socket.Send(bytes);
}
} }
public void JoinRoom() // multyplayer public void StopConnection()
{
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
/// <summary>
/// приложение пытается подключиться к комнате
/// </summary>
/// <param name="ip"></param>
/// <param name="port"></param>
public void JoinRoom(string ip) // multyplayer
{ {
endPoint = new IPEndPoint(IPAddress.Parse(ip), port);
socket.Connect(endPoint);
SendData(); SendData();
StartListening(); Thread listen = new Thread(StartListening);
listen.Start();
} }
/// <summary>
/// создается
/// </summary>
public void JoinYourself() // single player public void JoinYourself() // single player
{ {
endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), port);
socket.Connect(endPoint);
SendData(); SendData();
StartListening(); Thread listen = new Thread(StartListening);
listen.Start();
} }
//поток 2 //поток 2
public void StartListening() public void StartListening()
{ {
socket.Connect(endPoint); while(socket.Connected)
{
byte[] bytes = new byte[2048]; byte[] bytes = new byte[2048];
var countAnsw = socket.Receive(bytes);
var countAnsw = socket.Receive(bytes); string update = Encoding.UTF8.GetString(bytes, 0, countAnsw); // обновление отосланные сервером
GetDataSent(update);
string updates = Encoding.UTF8.GetString(bytes, 0, countAnsw); // обновления отосланные сервером }
} }
} }
} }

View file

@ -1,4 +1,5 @@
using Microsoft.Xna.Framework.Graphics.PackedVector; using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Graphics.PackedVector;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@ -21,44 +22,79 @@ namespace ZoFo.GameCore.GameManagers.NetworkManager
private Socket socket; private Socket socket;
private List<Socket> clients; private List<Socket> clients;
private List<IUpdateData> updates; private List<IUpdateData> updates;
delegate void OnDataSend(string data); // public delegate void OnDataSend(string data);
public event OnDataSend GetDataSend; // event
Dictionary<Socket, Thread> managerThread;
public void Init() //create Socket public void Init() //create Socket
{ {
endPoint = new IPEndPoint(ip, port); endPoint = new IPEndPoint(ip, port);
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
managerThread = new Dictionary<Socket, Thread>();
} }
public void SendData() //отправляет клиенту Data
public void SendData()
{ {
string data = JsonSerializer.Serialize(updates);
var databytes = Encoding.UTF8.GetBytes(data);
foreach (var item in clients)
{
item.SendAsync(databytes);
}
}
public void AddData(IUpdateData data)//добавляет в лист updates новую data
{
updates.Add(data);
} }
public void AddData(IUpdateData data) { }
public void CloseConnection()
{
foreach (var item in clients)
{
item.Shutdown(SocketShutdown.Both);
item.Close();
}
foreach (var item in managerThread)
{
foreach (var socket in clients)
{
managerThread[socket].Interrupt();
}
}
managerThread.Clear();
clients.Clear();
}
//Поток 2 //Поток 2
public void StartWaitingForPlayers()//Слушает игроков, которые хотят подключиться
public void StartWaitingForPlayers(object players)//Слушает игроков, которые хотят подключиться
{ {
int playNumber = (int)players;
socket.Bind(endPoint); socket.Bind(endPoint);
socket.Listen(10); socket.Listen(playNumber);
for (int i = 0; i < 10; i++) for (int i = 0; i < playNumber; i++)
{ {
Socket client = socket.Accept(); Socket client = socket.Accept();
Thread thread = new Thread(StartListening);
thread.Start(client);
managerThread.Add(client, thread);
clients.Add(client); //добавляем клиентов в лист clients.Add(client); //добавляем клиентов в лист
} }
StartListening();
} }
public void StartListening()//начать слушать клиентов в самой игре активируют Ивент private void StartListening(object socket)//начать слушать клиентов в самой игре активируют Ивент
{ {
var buff = new byte[1024]; // obj to Socket
foreach (var client in clients) Socket client = (Socket)socket;
while (client.Connected)
{ {
var buff = new byte[1024];
var answ = client.Receive(buff); var answ = client.Receive(buff);
string response = Encoding.UTF8.GetString(buff, 0, answ); string response = Encoding.UTF8.GetString(buff, 0, answ);
// List<IUpdateData> updateDatas = GetDataSend(response);
} }
Thread.Sleep(-1);
} }
} }
} }

View file

@ -1,8 +1,13 @@
using System; using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Text.Json;
using System.Threading.Tasks; using System.Threading.Tasks;
using ZoFo.GameCore.GameManagers.NetworkManager;
using ZoFo.GameCore.GameManagers.NetworkManager.Updates;
using ZoFo.GameCore.GameManagers.NetworkManager.Updates.ServerToClient;
using ZoFo.GameCore.GameObjects; using ZoFo.GameCore.GameObjects;
namespace ZoFo.GameCore namespace ZoFo.GameCore
@ -10,13 +15,35 @@ namespace ZoFo.GameCore
public class Server public class Server
{ {
private List<GameObject> gameObjects; private List<GameObject> gameObjects;
// private List<> entity; //entity private ServerNetworkManager networkManager;
// private List<> entity; //entity
public Server()
{
networkManager = new ServerNetworkManager();
networkManager.GetDataSend += OnDataSend;
}
public void OnDataSend(string data) { } public void OnDataSend(string data)
public void CreateRoom() { } {
public void StartGame() { } List<IUpdateData> updateDatas = JsonSerializer.Deserialize<List<IUpdateData>>(data);
public void EndGame() { } //ТУТ Switch case будет честное слово
}
public void CreateRoom(int players) {
networkManager.StartWaitingForPlayers(players);
}
// public void StartGame() { } принудительный запуск
public void EndGame() {
UpdateGameEnded gameEnded = new UpdateGameEnded();
networkManager.AddData(gameEnded);
}
internal void Update(GameTime gameTime)
{
}
public void RegisterEntity(GameObject gameObject)
{
gameObjects.Add(gameObject);
}
} }
} }

View file

@ -26,6 +26,9 @@
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\MonogameLibrary\MonogameLibrary.csproj" /> <ProjectReference Include="..\MonogameLibrary\MonogameLibrary.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Folder Include="Content\Textures\GUI\" />
</ItemGroup>
<Target Name="RestoreDotnetTools" BeforeTargets="Restore"> <Target Name="RestoreDotnetTools" BeforeTargets="Restore">
<Message Text="Restoring dotnet tools" Importance="High" /> <Message Text="Restoring dotnet tools" Importance="High" />
<Exec Command="dotnet tool restore" /> <Exec Command="dotnet tool restore" />