added publisher

This commit is contained in:
MasterGordon 2022-10-28 17:44:16 +02:00
parent f720ac17a9
commit e1a8c9410d
6 changed files with 44 additions and 28 deletions

Binary file not shown.

View File

@ -4,10 +4,10 @@
{
bool isHost = args.Contains("--host");
// bool isHost = true;
// var game = new MultiPlayerGame(isHost);
// game.Run();
var p = new Publisher(isHost ? InteractorKind.Server : InteractorKind.Client);
p.Dump();
Console.WriteLine("Hello World!");
var game = new MultiPlayerGame(isHost);
game.Run();
// var p = new Publisher(isHost ? InteractorKind.Server : InteractorKind.Client);
// p.Dump();
// Console.WriteLine("Hello World!");
}
}

View File

@ -6,6 +6,7 @@ using WatsonTcp;
class Backend : IBackend
{
private WatsonTcpServer server;
private Publisher publisher;
private Queue<ValueType> pendingPackets = new Queue<ValueType>();
public void Process(double dt)
@ -25,35 +26,16 @@ class Backend : IBackend
public void ProcessPacket(ValueType packet)
{
var gameState = Context.Get().GameState;
if (packet is MovePacket movePacket)
{
if (
gameState.PlayerPositions.Find(player => player.name == movePacket.playerName)
is Player player
)
{
player.movement = movePacket.movement * 4;
}
}
if (packet is ConnectPacket connectPacket)
{
Console.WriteLine($"Player {connectPacket.playerName} connected");
gameState.PlayerPositions.Add(
new Player
{
name = connectPacket.playerName,
position = new Vector2(50, 50),
movement = new Vector2(0, 0)
}
);
}
this.publisher.Publish(packet);
this.sendGameState();
}
public void Init()
{
Task.Run(Run);
this.publisher = new Publisher(
Context.Get().IsHost ? InteractorKind.Server : InteractorKind.Client
);
}
public void Run()

View File

@ -63,4 +63,16 @@ class Publisher
}
}
}
public void Publish(ValueType packet)
{
var type = PacketUtils.GetType(packet);
if (subscribers.ContainsKey(type))
{
foreach (var del in subscribers[type])
{
del.DynamicInvoke(packet);
}
}
}
}

View File

@ -0,0 +1,22 @@
class PacketUtils
{
public static string GetType(ValueType packet)
{
var t = packet.GetType();
foreach (var pp in t.GetProperties())
{
Console.WriteLine(pp.Name);
}
var p = t.GetField("type");
if (p == null)
{
throw new Exception("p undef");
}
var v = p.GetValue(packet);
if (v == null)
{
throw new Exception("v undef");
}
return (string)v;
}
}