ConnectSinglePlayer

This commit is contained in:
rawer470 2024-08-16 11:44:50 +03:00
parent 6ee0b4fc73
commit 553677b074
6 changed files with 70 additions and 50 deletions

View file

@ -29,7 +29,7 @@ namespace ZoFo.GameCore
public void JoinRoom(){ } public void JoinRoom(){ }
public void JoinYourself(){ } public void JoinYourself(){ networkManager.JoinYourself(); }
internal void Update(GameTime gameTime) internal void Update(GameTime gameTime)
{ {

View file

@ -2,6 +2,7 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.Linq; using System.Linq;
using System.Threading;
using System.Xml; using System.Xml;
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Content;
@ -20,15 +21,15 @@ public class MainMenuGUI : AbstractGUI
{ {
int width = AppManager.Instance.CurentScreenResolution.X; int width = AppManager.Instance.CurentScreenResolution.X;
int height = AppManager.Instance.CurentScreenResolution.Y; int height = AppManager.Instance.CurentScreenResolution.Y;
menuBackground = new DrawableUIElement(Manager) { rectangle = new Rectangle(0, 0, width, height), mainColor = Color.White, textureName = "Textures\\GUI\\MenuBackground" }; menuBackground = new DrawableUIElement(Manager) { rectangle = new Rectangle(0, 0, width, height), mainColor = Color.White, textureName = "Textures\\GUI\\MenuBackground" };
Elements.Add(menuBackground); Elements.Add(menuBackground);
menuBackground.LoadTexture(AppManager.Instance.Content); 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"}); 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) 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)), rectangle = new Rectangle(width / 2 - (int)(width / 10), height / 3 + height / 20 + height / 40, (int)(width / 5), (int)(height / 20)),
text = "Play", text = "Play",
@ -37,12 +38,18 @@ public class MainMenuGUI : AbstractGUI
mainColor = Color.Gray, mainColor = Color.Gray,
fontName = "Fonts\\Font" fontName = "Fonts\\Font"
}; };
playButton.LeftButtonPressed += () => playButton.LeftButtonPressed += () =>
{ {
Server server = new Server();
Client client = new Client();
server.CreateRoom(1);
client.JoinYourself();
AppManager.Instance.SetServer(server);
AppManager.Instance.SetClient(client);
AppManager.Instance.ChangeState(GameState.HostPlaying);
}; };
Elements.Add(playButton); Elements.Add(playButton);
Button optionButton = new Button(Manager) 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)), rectangle = new Rectangle(width / 2 - (int)(width / 10), height / 3 + (height / 20 + height / 40) * 2, (int)(width / 5), (int)(height / 20)),
text = "Options", text = "Options",
@ -51,12 +58,12 @@ public class MainMenuGUI : AbstractGUI
mainColor = Color.Gray, mainColor = Color.Gray,
fontName = "Fonts\\Font" fontName = "Fonts\\Font"
}; };
optionButton.LeftButtonPressed += () => optionButton.LeftButtonPressed += () =>
{ {
AppManager.Instance.SetGUI(new OptionsGUI()); AppManager.Instance.SetGUI(new OptionsGUI());
}; };
Elements.Add(optionButton); Elements.Add(optionButton);
Button exitButton = new Button(Manager) 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)), rectangle = new Rectangle(width / 2 - (int)(width / 10), height / 3 + (height / 20 + height / 40) * 3, (int)(width / 5), (int)(height / 20)),
text = "Exit", text = "Exit",
@ -65,15 +72,14 @@ public class MainMenuGUI : AbstractGUI
mainColor = Color.Gray, mainColor = Color.Gray,
fontName = "Fonts\\Font" fontName = "Fonts\\Font"
}; };
exitButton.LeftButtonPressed += () => exitButton.LeftButtonPressed += () =>
{ {
AppManager.Instance.Exit(); AppManager.Instance.Exit();
}; };
Elements.Add(exitButton); Elements.Add(exitButton);
}
}
public override void Update(GameTime gameTime) public override void Update(GameTime gameTime)
{ {
base.Update(gameTime); base.Update(gameTime);

View file

@ -20,9 +20,9 @@ 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;
@ -31,13 +31,13 @@ namespace ZoFo.GameCore.GameManagers
public Client client; public Client client;
public Server server; public Server server;
#region Managers #region Managers
public InputManager InputManager; public InputManager InputManager;
public ItemManager.ItemManager ItemManager; public ItemManager.ItemManager ItemManager;
public AnimationBuilder animationBuilder{get;set; } public AnimationBuilder animationBuilder { get; set; }
#endregion #endregion
@ -45,16 +45,16 @@ namespace ZoFo.GameCore.GameManagers
{ {
_graphics = new GraphicsDeviceManager(this); _graphics = new GraphicsDeviceManager(this);
SetResolution(CurentScreenResolution.X, CurentScreenResolution.Y); SetResolution(CurentScreenResolution.X, CurentScreenResolution.Y);
FulscrreenSwitch(); // FulscrreenSwitch();
Content.RootDirectory = "Content"; Content.RootDirectory = "Content";
IsMouseVisible = true; IsMouseVisible = true;
Instance = this; Instance = this;
InputManager = new InputManager(); InputManager = new InputManager();
currentGUI = new MainMenuGUI(); currentGUI = new MainMenuGUI();
debugHud = new DebugHUD(); debugHud = new DebugHUD();
@ -65,7 +65,7 @@ namespace ZoFo.GameCore.GameManagers
{ {
currentGUI.Initialize(); currentGUI.Initialize();
debugHud.Initialize(); debugHud.Initialize();
base.Initialize(); base.Initialize();
@ -86,9 +86,9 @@ 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"); debugHud.Set("key", "value");
InputManager.Update(); InputManager.Update();
currentGUI.Update(gameTime); currentGUI.Update(gameTime);
switch (gamestate) switch (gamestate)
@ -113,7 +113,7 @@ namespace ZoFo.GameCore.GameManagers
{ {
GraphicsDevice.Clear(Color.CornflowerBlue); GraphicsDevice.Clear(Color.CornflowerBlue);
debugHud.Draw(_spriteBatch); debugHud.Draw(_spriteBatch);
currentGUI.Draw(_spriteBatch); currentGUI.Draw(_spriteBatch);
@ -121,7 +121,7 @@ namespace ZoFo.GameCore.GameManagers
{ {
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:
@ -136,7 +136,7 @@ namespace ZoFo.GameCore.GameManagers
} }
public void SetGUI(AbstractGUI gui) public void SetGUI(AbstractGUI gui)
{ {
currentGUI = gui; currentGUI = gui;
currentGUI.Initialize(); currentGUI.Initialize();
currentGUI.LoadContent(); currentGUI.LoadContent();
@ -158,5 +158,8 @@ namespace ZoFo.GameCore.GameManagers
{ {
_graphics.IsFullScreen = !_graphics.IsFullScreen; _graphics.IsFullScreen = !_graphics.IsFullScreen;
} }
public void SetServer(Server server) { this.server = server; }
public void SetClient(Client client) { this.client = client; }
} }
} }

View file

@ -5,6 +5,7 @@ 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.Text.Json;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using ZoFo.GameCore.GameManagers.NetworkManager.Updates; using ZoFo.GameCore.GameManagers.NetworkManager.Updates;
@ -20,6 +21,12 @@ namespace ZoFo.GameCore.GameManagers.NetworkManager
List<IUpdateData> updates = new List<IUpdateData>(); List<IUpdateData> updates = new List<IUpdateData>();
public delegate void OnDataSent(string Data); public delegate void OnDataSent(string Data);
public event OnDataSent GetDataSent; // event public event OnDataSent GetDataSent; // event
public ClientNetworkManager()
{
Init();
}
public void Init() //create endPoint, socket public void Init() //create endPoint, socket
{ {
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
@ -27,11 +34,13 @@ namespace ZoFo.GameCore.GameManagers.NetworkManager
public void SendData() public void SendData()
{ {
while(socket.Connected) byte[] bytes = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(updates)); //нужно сериализовать
{
byte[] bytes = Encoding.UTF8.GetBytes(updates.ToString());
socket.Send(bytes); socket.Send(bytes);
} }
public void AddData(IUpdateData UpdateData)
{
updates.Add(UpdateData);
} }
public void StopConnection() public void StopConnection()
@ -47,10 +56,9 @@ namespace ZoFo.GameCore.GameManagers.NetworkManager
/// <param name="port"></param> /// <param name="port"></param>
public void JoinRoom(string ip) // multyplayer public void JoinRoom(string ip) // multyplayer
{ {
endPoint = new IPEndPoint(IPAddress.Parse(ip), port); endPoint = new IPEndPoint(IPAddress.Parse(ip), port);
socket.Connect(endPoint); socket.Connect(endPoint);
SendData(); SendData();
Thread listen = new Thread(StartListening); Thread listen = new Thread(StartListening);
listen.Start(); listen.Start();
@ -62,9 +70,7 @@ namespace ZoFo.GameCore.GameManagers.NetworkManager
public void JoinYourself() // single player public void JoinYourself() // single player
{ {
endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), port); endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), port);
socket.Connect(endPoint); socket.Connect(endPoint);
SendData(); SendData();
Thread listen = new Thread(StartListening); Thread listen = new Thread(StartListening);
listen.Start(); listen.Start();

View file

@ -16,7 +16,7 @@ namespace ZoFo.GameCore.GameManagers.NetworkManager
{ {
public class ServerNetworkManager public class ServerNetworkManager
{ {
private IPAddress ip = IPAddress.Any; private IPAddress ip =IPAddress.Parse("127.0.0.1"); //IPAddress.Any
private int port = 7632; private int port = 7632;
private IPEndPoint endPoint; private IPEndPoint endPoint;
private Socket socket; private Socket socket;
@ -25,12 +25,18 @@ namespace ZoFo.GameCore.GameManagers.NetworkManager
public delegate void OnDataSend(string data); public delegate void OnDataSend(string data);
public event OnDataSend GetDataSend; // event public event OnDataSend GetDataSend; // event
Dictionary<Socket, Thread> managerThread; Dictionary<Socket, Thread> managerThread;
Thread serverTheread;
public ServerNetworkManager() { Init(); }
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>(); managerThread = new Dictionary<Socket, Thread>();
clients = new List<Socket>();
updates = new List<IUpdateData>();
managerThread = new Dictionary<Socket, Thread>();
} }
/// <summary> /// <summary>
/// отправляет клиенту Data /// отправляет клиенту Data
@ -52,14 +58,7 @@ namespace ZoFo.GameCore.GameManagers.NetworkManager
{ {
updates.Add(data); updates.Add(data);
} }
<<<<<<< Updated upstream
public void CloseConnection() //По сути коне игры и отключение игроков public void CloseConnection() //По сути коне игры и отключение игроков
=======
/// <summary>
///
/// </summary>
public void CloseConnection()
>>>>>>> Stashed changes
{ {
foreach (var item in clients) foreach (var item in clients)
{ {
@ -80,6 +79,12 @@ namespace ZoFo.GameCore.GameManagers.NetworkManager
clients.Clear(); clients.Clear();
} }
public void Start(object players)
{
serverTheread = new Thread(StartWaitingForPlayers);
serverTheread.Start(players);
}
//Потоки Клиентов //Потоки Клиентов
public void StartWaitingForPlayers(object players)//Слушает игроков, которые хотят подключиться public void StartWaitingForPlayers(object players)//Слушает игроков, которые хотят подключиться
{ {

View file

@ -39,7 +39,7 @@ namespace ZoFo.GameCore
} }
public void CreateRoom(int players) //Создает комнату и запускает ожидание подключений public void CreateRoom(int players) //Создает комнату и запускает ожидание подключений
{ {
networkManager.StartWaitingForPlayers(players); networkManager.Start(players);
} }
// public void StartGame() { } принудительный запуск // public void StartGame() { } принудительный запуск