public async Task <ConnectionToGameResult> ConnectToGame(Player player, ImmutableArray <Ship> ships, string connectionCode) { var completionSource = new TaskCompletionSource <ConnectionToGameResult>(); IDisposable subscription = null; subscription = _socket.MessageReceived.Subscribe(msg => { subscription.Dispose(); var connectionToGameResult = _serializer.Deserialize <ConnectionToGameResult>(msg.Text); completionSource.SetResult(connectionToGameResult); if (!connectionToGameResult.IsConnected) { return; } _reconnectSubscription.Dispose(); GameCreated?.Invoke(this, new(_socket, connectionToGameResult.Go, connectionToGameResult.Enemy)); }); await Connect(); var message = new CreateGameMessage(new(player, ships, connectionCode)); var text = _serializer.Serialize(message); _socket.Send(text); return(await completionSource.Task); }
private void BtnCreateGame_LeftClick(object sender, EventArgs e) { string gameName = tbGameName.Text.Replace(";", string.Empty); if (string.IsNullOrEmpty(gameName)) { return; } if (new ProfanityFilter().IsOffensive(gameName)) { XNAMessageBox.Show(WindowManager, "Offensive game name", "Please enter a less offensive game name."); return; } if (!lbTunnelList.IsValidIndexSelected()) { return; } GameCreated?.Invoke(this, new GameCreationEventArgs(gameName, int.Parse(ddMaxPlayers.SelectedItem.Text), tbPassword.Text, tunnelHandler.Tunnels[lbTunnelList.SelectedIndex])); }
public async Task <ConnectionCode> CreateGame(Player player, ImmutableArray <Ship> ships) { var completionSource = new TaskCompletionSource <ConnectionCode>(); IDisposable subscription = null; subscription = _socket.MessageReceived.Subscribe(msg => { var connectionResult = _serializer.DeserializeDynamic(msg.Text); switch ((string)connectionResult["message_type"]) { case "connection_code": var connectionCode = _serializer.DeserializeObject <ConnectionCode>(connectionResult); completionSource.SetResult(connectionCode); break; case "game_connected": var result = _serializer.DeserializeObject <ConnectionToGameResult>(connectionResult); subscription.Dispose(); _reconnectSubscription.Dispose(); GameCreated?.Invoke(this, new(_socket, result.Go, result.Enemy)); break; default: throw new("Unexpected message type"); } }); await Connect(); var message = new CreateGameMessage(new(player, ships, null)); var text = _serializer.Serialize(message); _socket.Send(text); return(await completionSource.Task); }
private GameAggregate(Guid gameId, string title, string description, int?rating, DateTime?releaseDate) { this.AggregateId = gameId; var creationEvent = new GameCreated(gameId, title, description, rating, releaseDate); this.RaiseEvent(creationEvent); }
public async Task <IActionResult> CreateGameAsync([FromQuery] uint player1Id, [FromQuery] uint player2Id) { if (player1Id == 0 || player2Id == 0 || player1Id == player2Id) { return(BadRequest()); } var isGameStarted = await _gameRepository.IsThereStartedGame(player1Id, player2Id); if (isGameStarted) { return(StatusCode((int)HttpStatusCode.Conflict)); } var game = new Game { Id = Guid.NewGuid().ToString(), Player1Id = player1Id, Player2Id = player2Id }; await _gameRepository.AddGameAsync(game); var response = new GameCreated { GameId = game.Id }; return(Ok(response)); }
public Game Create() { var gameTimeService = new GameTimeService(30); var gameLoop = new GameEventQueueService(gameTimeService); var terrainServiceStore = new SectorGraphDescriptionStore(); var terrainSnapshotBuilder = new TerrainSnapshotCompiler(terrainServiceStore); var terrainService = new TerrainService(terrainServiceStore, terrainSnapshotBuilder); var entityService = new EntityService(); var statsCalculator = new StatsCalculator(); var pathfinderCalculator = new PathfinderCalculator(terrainService, statsCalculator); var movementSystemService = new MovementSystemService(entityService, gameTimeService, statsCalculator, terrainService, pathfinderCalculator); entityService.AddEntitySystem(movementSystemService); var gameLogicFacade = new GameLogicFacade(terrainService, movementSystemService); var gameInstance = new Game { GameTimeService = gameTimeService, GameEventQueueService = gameLoop, TerrainService = terrainService, EntityService = entityService, PathfinderCalculator = pathfinderCalculator, MovementSystemService = movementSystemService, GameLogicFacade = gameLogicFacade }; gameInstance.Initialize(); GameCreated?.Invoke(this, gameInstance); return(gameInstance); }
private void TimerElapsed(object sender, ElapsedEventArgs e) { bool CheckPlayer(long id, out Player player) { searchQuery.Remove(id); if (players.ContainsKey(id)) { player = null; return(false); } player = new Player(id); players.Add(id, player); return(true); } for (var i = 0; i + 2 <= searchQuery.Count; i += 2) { var first = searchQuery[i]; var second = searchQuery[i + 1]; if (CheckPlayer(first, out var firstplayer) && CheckPlayer(second, out var secondplayer)) { firstplayer.Enemy = secondplayer; secondplayer.Enemy = firstplayer; GameCreated?.Invoke(this, new GameEventArgs() { FirstPlayerId = firstplayer.Id, SecondPlayerId = secondplayer.Id }); } } }
public void Handle(GameCreated e) { UsersHub.CurrentContext.Clients.Group(e.Id).gameCreated(new { e = e }); }
private void HandleGameCreated(GameCreated gameCreated) { foreach (var handler in gameCreatedHandlers.ToArray()) { handler(gameCreated); } }
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)); }
// Applied by Reflection when reading events (AggregateBase -> this.AsDynamic().Apply(@event);) // Ensures aggregates get their needed property values (e.g. Id) from events // ReSharper disable once UnusedMember.Local private void Apply(GameCreated e) { Id = e.Id; _innerDetails = new GameDetails { Id = e.Id, ActivatedOn = e.CreatedOn, Version = e.Version }; }
public void Handle(GameCreated @event) { var repository = _container.Resolve <IBonusRepository>(); repository.Games.Add(new Game { Id = @event.Id, ProductId = @event.GameProviderId }); repository.SaveChanges(); }
public IEnumerable <GameFieldCreate> GenerateFields(GameCreated createdGame, IEnumerable <GameTeamCreated> teams, IEnumerable <string> words) { var wordsArray = words.ToArray(); var fieldsToReturn = CreateFields(createdGame, wordsArray); var fieldsToUpdate = fieldsToReturn.ToList(); fieldsToUpdate = UpdateTrapFields(fieldsToUpdate, createdGame.TrapCount); fieldsToUpdate = UpdateTeamFields(fieldsToUpdate, teams); return(fieldsToReturn); }
public async void AGameEventHandlerShouldHandleTheGameCreatedEvent() { var mockReadFac = new Mock <IReadModelFacade>(); var mockReadPer = new Mock <IReadModelPersistence>(); var newGuid = Guid.NewGuid(); var fakeEvent = new GameCreated(newGuid); var sut = new GameEventHandler(mockReadFac.Object, mockReadPer.Object); await sut.Handle(fakeEvent); mockReadPer.Verify(m => m.Put(It.IsAny <GameDetails>()), Times.Once); }
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 async Task CreateGameData(GameCreated game, IEnumerable <GameTeamCreate> teamsToCreate) { await validator.ValidateTeams(teamsToCreate); var teams = await gameTeamRepository.CreateGameTeams(teamsToCreate); var firstTeamId = await gameTeamRepository.GetFirstTeamId(game.Id); await gameStatusRepository.CreateInitialGameStatus(game.Id, firstTeamId); var fieldCount = game.BoardHeight * game.BoardWidth; var words = await randomWordRepository.GetRandomWords(game.LanguageId, fieldCount); var fields = gameFieldsGenerator.GenerateFields(game, teams, words); await validator.ValidateFields(fields); await gameFieldRepository.SaveGameFields(fields); }
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])); }
private IEnumerable <GameFieldCreate> CreateFields(GameCreated createdGame, string[] wordsArray) { var fieldsToReturn = new GameFieldCreate[wordsArray.Count()]; int wordIndex = 0; for (int r = 0; r < createdGame.BoardHeight; r++) { for (int c = 0; c < createdGame.BoardWidth; c++) { var field = CreateField(createdGame.Id, wordsArray[wordIndex], r, c); fieldsToReturn[wordIndex] = field; wordIndex++; } } return(fieldsToReturn); }
public GameState When(GameCreated @event) => new GameState { Status = GameStatus.ReadyToStart };
private void Apply(GameCreated obj) { this.AggregateId = obj.AggregateId; this.GameDetails = new GameDetailsEntity(obj.AggregateId, obj.Title, obj.Description, obj.Rating, obj.ReleaseDate); }
internal virtual void OnCreateGame(GameCreatedEventArgs args) => GameCreated?.Invoke(args);
public void Consume(GameCreated message) { _eventHandlers.Handle(message); }
private void OnGameCreated() { GameCreated.SafeRaise(this, EventArgs.Empty); }
public GameState When(GameCreated gameCreated) { CreatorId = gameCreated.PlayerId; return(this); }
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); }
public void Handle(GameCreated @event) { AddActivityLog(AdminActivityLogCategory.Game, @event); }
public void OnGameCreated(IGameCreatedEvent evt) => GameCreated?.Invoke(evt);
/// <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; } }
public GameState When(GameCreated @event) { Status = GameStatus.ReadyToStart; return(this); }
public void Consume(GameCreated message) { _gameSubscriber.Handle(message); }