public GameServer(Player player1, Player player2, int?maxGameTurns = null, IReadOnlyList <Card> cardDeck = null)
        {
            Game         = new Game(player1, player2, cardDeck);
            GameClients  = new[] { player1.CreateGameClient(), player2.CreateGameClient() };
            MaxGameTurns = maxGameTurns;

            GameCreated?.Invoke(this, new GameEventArgs(Game, null));
        }
        public Guid CreateNewGame(Guid player1Id, Guid player2Id)
        {
            Guid gameId;
            var  retries = 0;

            do
            {
                if (retries < 3)
                {
                    gameId   = Guid.NewGuid();
                    retries += 1;
                }
                else
                {
                    throw new InvalidOperationException("Could not generate valid Guid within 3 tries");
                }
            } while (GameStore.ContainsKey(gameId));

            var personGenerator = new PersonNameGenerator();
            var names           = personGenerator.GenerateMultipleFirstAndLastNames(2).Select(x => x.Split(' ').First());

            var player1 = new PlayerWrapper
            {
                Player = new Player(names.First()),
                Id     = player1Id
            };

            var player2 = new PlayerWrapper
            {
                Player = new Player(names.Last()),
                Id     = player2Id
            };

            var game = new GameWrapper
            {
                Id      = gameId,
                Game    = new Game(),
                Player1 = player1,
                Player2 = player2
            };

            GameStore.Add(gameId, game);
            PlayerStore.Add(player1.Id, player1);
            PlayerStore.Add(player2.Id, player2);

            GameCreated?.Invoke(this, new GameCreatedEvent(gameId, player1, player2));

            return(gameId);
        }
        private void BtnCreateGame_LeftClick(object sender, EventArgs e)
        {
            string gameName = tbGameName.Text.Replace(";", string.Empty);

            if (string.IsNullOrEmpty(gameName))
            {
                return;
            }

            if (lbTunnelList.SelectedIndex < 0 || lbTunnelList.SelectedIndex >= lbTunnelList.ItemCount)
            {
                return;
            }

            GameCreated?.Invoke(this, new GameCreationEventArgs(gameName,
                                                                int.Parse(ddMaxPlayers.SelectedItem.Text), tbPassword.Text,
                                                                tunnelHandler.Tunnels[lbTunnelList.SelectedIndex]));
        }
 public void OnGameCreated(IGameCreatedEvent evt) => GameCreated?.Invoke(evt);
Esempio n. 5
0
        public async Task OpenAsync(string userName, CancellationToken cancellationToken)
        {
            _cookieContainer   = new CookieContainer();
            _httpClientHandler = new HttpClientHandler {
                CookieContainer = _cookieContainer
            };

            _progressMessageHandler = new ProgressMessageHandler(_httpClientHandler);
            _progressMessageHandler.HttpSendProgress += MessageHandler_HttpSendProgress;

            _client = new HttpClient(_progressMessageHandler)
            {
                Timeout = TimeSpan.FromMinutes(PackageUploadTimelimitInMinutes)
            };
            _client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36");

            var token = await AuthenticateUserAsync(userName, "", cancellationToken);

            _login = userName;

            _connection = new HubConnectionBuilder()
                          .WithUrl($"{ServerAddress}/sionline?token={token}", options =>
            {
                options.AccessTokenProvider = () => Task.FromResult(Convert.ToBase64String(Encoding.UTF8.GetBytes(_login)));
            })
                          .WithAutomaticReconnect()
                          .AddMessagePackProtocol()
                          .Build();

            _connection.Reconnecting += async e =>
            {
                if (Reconnecting != null)
                {
                    await Reconnecting(e);
                }
            };

            _connection.Reconnected += async s =>
            {
                if (Reconnected != null)
                {
                    await Reconnected(s);
                }
            };

            _connection.Closed += OnConnectionClosed;

            _connection.HandshakeTimeout = TimeSpan.FromMinutes(1);

            _connection.On <string, string>("Say", (user, text) => OnUI(() => Receieve?.Invoke(user, text)));
            _connection.On <SI.GameServer.Contract.GameInfo>("GameCreated", (gameInfo) => OnUI(() => GameCreated?.Invoke(ToSICoreGame(gameInfo))));
            _connection.On <int>("GameDeleted", (gameId) => OnUI(() => GameDeleted?.Invoke(gameId)));
            _connection.On <SI.GameServer.Contract.GameInfo>("GameChanged", (gameInfo) => OnUI(() => GameChanged?.Invoke(ToSICoreGame(gameInfo))));
            _connection.On <string>("Joined", (user) => OnUI(() => Joined?.Invoke(user)));
            _connection.On <string>("Leaved", (user) => OnUI(() => Leaved?.Invoke(user)));

            await _connection.StartAsync(cancellationToken);
        }
Esempio n. 6
0
        /// <summary>
        /// Processes received packets.
        /// </summary>
        /// <param name="packet">Received packet.</param>
        void ProcessPacket(NetworkPacket packet)
        {
            // Decrypt data
            var data = packet.Data;

            if (data != null && data.Length > 0 && packet.PacketType != NetworkPacketType.PublicKey)
            {
                if (packet.PacketType != NetworkPacketType.ServerInfo)
                {
                    data = _decrypter.Decrypt(packet.Data);
                }
                if (data == null)
                {
                    Log.WriteLine(LogPriority.Error, "NetworkGameClient: Error! Could not decrypt message from server");
                    return;
                }
            }
            switch (packet.PacketType)
            {
            case NetworkPacketType.PublicKey:
                try
                {
                    var serverPubKey = Encoding.ASCII.GetString(packet.Data);
                    _encrypter = new CryptoHelper(serverPubKey);
                }
                catch (Exception ex)
                {
                    _encrypter = null;
                    Log.WriteLine(LogPriority.Error, "NetworkGameClient: Received key is invalid! " + ex.Message);
                }
#pragma warning disable RECS0022 // A catch clause that catches System.Exception and has an empty body
#pragma warning disable CC0004   // Catch block cannot be empty
                finally { try { _encrypterWaiter?.Cancel(); } catch { /* Ignore*/ } }
#pragma warning restore CC0004   // Catch block cannot be empty
#pragma warning restore RECS0022 // A catch clause that catches System.Exception and has an empty body
                break;

            case NetworkPacketType.ListGames:
                try
                {
                    var glistString = Encoding.ASCII.GetString(data);
                    var glist       = JsonConvert.DeserializeObject <List <GameInfo> >(glistString);
                    Log.WriteLine(LogPriority.Verbose, "NetworkGameClient: Received list of games on server. Game count: " + glist.Count);
                    GameListReceived?.Invoke(this, new GameListEventArgs(glist));
                }
                catch (Exception e)
                {
                    Log.WriteLine(LogPriority.Error, "NetworkGameClient: Received list of games from server could not be read. " + e.Message);
                }
                break;

            case NetworkPacketType.ClientLogin:
                try
                {
                    if (data.Length > 0 && data[0] == 0)
                    {
                        IsLoggedIn = true;
                        Log.WriteLine(LogPriority.Information, "NetworkGameClient: Login to server successful!");
                    }
                    else
                    {
                        IsLoggedIn = false;
                        var error = "NetworkGameClient: Login to server failed! ";
                        if (data[0] == 1)
                        {
                            error += "Invalid user name";
                        }
                        else if (data[0] == 2)
                        {
                            error += "Invalid password";
                        }
                        else if (data[0] == 3)
                        {
                            error += "Database error";
                        }
                        else
                        {
                            error += "Unknown error";
                        }
                    }
                    LoggedIn?.Invoke(this, new LoggedInEventArgs(IsLoggedIn == true));
                }
                catch (Exception e)
                {
                    Log.WriteLine(LogPriority.Error, "NetworkGameClient: Received login confirmation could not be read." + e.Message);
                }
                break;

            case NetworkPacketType.CreateGame:
                try
                {
                    // Check if an UID was assigned
                    var ginfo = JsonConvert.DeserializeObject <GameInfo>(Encoding.ASCII.GetString(data));
                    if (ginfo != null)
                    {
                        if (ginfo.UID != 0)
                        {
                            GameCreated?.Invoke(this, new GameCreatedEventArgs(ginfo));
                        }
                    }
                    else
                    {
                        Log.WriteLine(LogPriority.Error, "NetworkGameClient: Received CreateGame confirmation could not be read.");
                    }
                }
                catch (Exception e)
                {
                    Log.WriteLine(LogPriority.Error, "NetworkGameClient: Received CreateGame confirmation could not be read." + e.Message);
                }
                break;

            case NetworkPacketType.JoinGame:
                try
                {
                    var jMsg = JsonConvert.DeserializeObject <JoinMessage>(Encoding.ASCII.GetString(data));
                    if (jMsg != null)
                    {
                        GameJoinRequested?.Invoke(this, new GameJoinRequestedEventArgs(jMsg));

                        // If joining and other side declined then set IsJoined to false
                        if (jMsg.Request == JoinRequestType.Decline)
                        {
                            IsJoined = false;
                        }
                    }
                }
                catch (Exception e)
                {
                    Log.WriteLine(LogPriority.Error, "NetworkGameClient: Received JoinGame confirmation could not be read." + e.Message);
                }
                break;

            case NetworkPacketType.ServerInfo:
                try
                {
                    // Server data is always unencrypted
                    var jMsg = JsonConvert.DeserializeObject <ServerInfo>(Encoding.ASCII.GetString(packet.Data));
                    if (jMsg != null)
                    {
                        ServerRequiresLogin = jMsg.RequiresLogin;
                        ServerInfoReceived?.Invoke(this, new ServerInfoEventArgs(jMsg));
                    }
                }
                catch (Exception e)
                {
                    Log.WriteLine(LogPriority.Error, "NetworkGameClient: Received ServerInfo could not be read." + e.Message);
                }
                break;

            case NetworkPacketType.ExitGame:
                try
                {
                    var eMsg = JsonConvert.DeserializeObject <ExitGame>(Encoding.ASCII.GetString(data));
                    if (eMsg != null)
                    {
                        if (eMsg.UID == UID)
                        {
                            IsJoined = false;
                            UID      = 0;
                            GameExitReceived?.Invoke(this, EventArgs.Empty);
                        }
                    }
                }
                catch (Exception e)
                {
                    Log.WriteLine(LogPriority.Error, "NetworkGameClient: Received ExitGame message could not be read." + e.Message);
                }
                break;

            case NetworkPacketType.GameSync:
                try
                {
                    var eMsg = JsonConvert.DeserializeObject <GameSync>(Encoding.ASCII.GetString(data));
                    if (eMsg != null && eMsg.UID == UID)
                    {
                        GameSyncReceived?.Invoke(this, new GameSyncEventArgs(eMsg));
                    }
                }
                catch (Exception e)
                {
                    Log.WriteLine(LogPriority.Error, "NetworkGameClient: Received GameSync message could not be read." + e.Message);
                }
                break;

            case NetworkPacketType.GameCommand:
                try
                {
                    var eMsg = JsonConvert.DeserializeObject <GameCommand>(Encoding.ASCII.GetString(data));
                    if (eMsg != null)
                    {
                        GameCommandReceived?.Invoke(this, new GameCommandEventArgs(eMsg));
                    }
                }
                catch (Exception e)
                {
                    Log.WriteLine(LogPriority.Error, "NetworkGameClient: Received GameSync message could not be read." + e.Message);
                }
                break;

            default:
                Log.WriteLine(LogPriority.Error, "NetworkGameClient: Packet type " + packet.PacketType + " not recognized!");
                break;
            }
        }
Esempio n. 7
0
 internal virtual void OnCreateGame(GameCreatedEventArgs args) => GameCreated?.Invoke(args);
Esempio n. 8
0
 private void _OnCreated(IGameWorker worker, string gameModeName, string placementName) =>
 GameCreated?.Invoke(this, new GameCreatedEnventArgs(worker, gameModeName, placementName));