-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathTestMultiplayerClient.cs
More file actions
90 lines (73 loc) · 2.63 KB
/
TestMultiplayerClient.cs
File metadata and controls
90 lines (73 loc) · 2.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
using System;
using System.Collections.Generic;
using MultiplayerMod.ModRuntime;
using MultiplayerMod.Multiplayer.Commands;
using MultiplayerMod.Network;
namespace MultiplayerMod.Test.Environment.Network;
public class TestMultiplayerClient : IMultiplayerClient {
public event Action<MultiplayerClientState>? StateChanged;
public event Action<IMultiplayerCommand>? CommandReceived;
private readonly TestRuntime runtime;
private TestMultiplayerServer server = null!;
private readonly Queue<System.Action> pendingActions = new();
public IMultiplayerClientId Id { get; }
public MultiplayerClientState State { get; private set; } = MultiplayerClientState.Disconnected;
public bool EnablePendingActions { get; set; }
public TestMultiplayerClient(TestMultiplayerClientId id, TestRuntime runtime) {
this.runtime = runtime;
Id = id;
id.Client = this;
}
public void Connect(IMultiplayerEndpoint endpoint) {
server = ((TestMultiplayerEndpoint) endpoint).Server;
EnqueuePendingAction(() => SetState(MultiplayerClientState.Connecting));
EnqueuePendingAction(
() => {
// State must show the client is connected, but the state change event must be postponed
State = MultiplayerClientState.Connected;
server.Accept(Id);
}
);
EnqueuePendingAction(() => StateChanged?.Invoke(State));
}
public void Disconnect() {
EnqueuePendingAction(
() => {
server.Drop(Id);
SetState(MultiplayerClientState.Disconnected);
}
);
}
public bool RunPendingAction() {
if (pendingActions.Count <= 0)
return false;
pendingActions.Dequeue().Invoke();
return true;
}
private void EnqueuePendingAction(System.Action action) {
if (EnablePendingActions) {
pendingActions.Enqueue(action);
return;
}
action();
}
public void Send(IMultiplayerCommand command, MultiplayerCommandOptions options = MultiplayerCommandOptions.None) {
server.Receive(this, CommandTools.Copy(command), options);
}
public void SetState(MultiplayerClientState state) {
State = state;
StateChanged?.Invoke(state);
}
public void Receive(IMultiplayerCommand command) {
var oldRuntime = (TestRuntime) Runtime.Instance;
try {
runtime.Activate();
CommandReceived?.Invoke(CommandTools.Copy(command));
} finally {
oldRuntime.Activate();
}
}
public void Tick()
{
}
}