Ejemplo n.º 1
0
        public void GetActiveGameWithWithoutGames()
        {
            DbConnection connection = DbConnectionFactory.CreateTransient();

            var scopeMock = new Mock <ILifetimeScope>();

            scopeMock.SetupResolve <ILifetimeScope, IGwintContext>(new GwintContext(connection));
            var userConnectionMapMock = new Mock <IUserConnectionMap>();

            userConnectionMapMock.SetupMapping();
            scopeMock.SetupResolve <ILifetimeScope, IUserConnectionMap>(userConnectionMapMock.Object);
            var rootScopeMock = new Mock <ILifetimeScope>();

            rootScopeMock.Setup(s => s.BeginLifetimeScope()).Returns(scopeMock.Object);
            var clientsMock = new Mock <IHubCallerConnectionContext <dynamic> >();

            clientsMock.SetupClients();

            var     userName             = "******";
            var     userId               = "1";
            var     connectionID         = "13245";
            var     hubCallerContextMock = CreateHubCallerContextMock(userName, userId, connectionID);
            GameHub hub = new GameHub(rootScopeMock.Object)
            {
                Context = hubCallerContextMock.Object,
                Clients = clientsMock.Object
            };

            var result = hub.GetActiveGame();

            Assert.NotNull(result.Error);
            Assert.Null(result.Data);
        }
Ejemplo n.º 2
0
        public IActionResult PauseGame(string gameName)
        {
            var gamehub = new GameHub(_hubContext, _gameService, _questionService);

            gamehub.StopGameTimer(gameName);
            return(Ok());
        }
Ejemplo n.º 3
0
        public async Task SendMovePlayer_GivenParameters_ExpectSomething()
        {
            //Arrange
            var state = new State(new[] {
                "...|.x.|...", "...|...|...", "...|...|...",
                "...|...|...", "...|...|...", "...|...|...",
                "...|...|...", "...|...|...", "...|...|..."
            });
            var mockDatabase = Substitute.For <IDatabaseRepository>();

            mockDatabase.RecordMoveAsync(Arg.Any <string>(), Arg.Any <(int, int)>(), Arg.Any <Field>()).Returns(Task.CompletedTask);
            mockDatabase.GetStateAsync(Arg.Any <string>()).Returns(Task.FromResult(state));
            var clients = Substitute.For <IHubCallerConnectionContext <object> >();
            var uiMock  = Substitute.For <IMockClient>();

            uiMock.When(x => x.broadcastState(Arg.Any <State>())).Do(x => { });
            clients.Group(Arg.Any <string>()).Returns(uiMock);
            var hub = new GameHub(mockDatabase)
            {
                Clients = clients
            };

            //Act
            await hub.SendMovePlayer("Ticket", 0, 4, 'x');

            //Assert
            await mockDatabase.Received(1).RecordMoveAsync("Ticket", (0, 4), Field.X);

            await mockDatabase.Received(1).GetStateAsync("Ticket");

            uiMock.Received(1).broadcastState(state);
        }
Ejemplo n.º 4
0
        public void JoinGame()
        {
            DbConnection connection = DbConnectionFactory.CreateTransient();

            using (var gwintContext = new GwintContext(connection))
            {
                gwintContext.Cards.AddRange(TestCardProvider.GetDefaultCards());
                gwintContext.Users.Add(new User
                {
                    Id = 1
                });
                var user2 = new User
                {
                    Id = 2
                };
                gwintContext.Users.Add(user2);
                gwintContext.Games.Add(new Game
                {
                    Id      = 1,
                    State   = new LobbyState(),
                    Players = new List <Player>
                    {
                        new Player
                        {
                            User = user2
                        }
                    }
                });
                gwintContext.SaveChanges();
            }
            var scopeMock = new Mock <ILifetimeScope>();

            scopeMock.SetupResolve <ILifetimeScope, IGwintContext>(new GwintContext(connection));
            var userConnectionMapMock = new Mock <IUserConnectionMap>();

            userConnectionMapMock.SetupMapping();
            scopeMock.SetupResolve <ILifetimeScope, IUserConnectionMap>(userConnectionMapMock.Object);
            var rootScopeMock = new Mock <ILifetimeScope>();

            rootScopeMock.Setup(s => s.BeginLifetimeScope()).Returns(scopeMock.Object);
            var clientsMock = new Mock <IHubCallerConnectionContext <dynamic> >();

            clientsMock.SetupClients();

            int     gameId               = 1;
            var     userName             = "******";
            var     userId               = "1";
            var     connectionID         = "13245";
            var     hubCallerContextMock = CreateHubCallerContextMock(userName, userId, connectionID);
            GameHub hub = new GameHub(rootScopeMock.Object)
            {
                Context = hubCallerContextMock.Object,
                Clients = clientsMock.Object
            };

            var result = hub.JoinGame(gameId);

            Assert.Null(result.Error);
            Assert.NotNull(result.Data);
        }
Ejemplo n.º 5
0
    // End of declaration

    /// <summary>
    /// Connect to the SignalR server
    /// </summary>
    public void Connect()
    {
        signalRClient = this;
        connectVars   = GameObject.Find("ConnectVars").GetComponent <ConnectVars>();

        // Initialize the connection
        gameHub           = new GameHub(ref signalRClient, ref connectVars);
        signalRConnection = new Connection(uri, gameHub);
        signalRConnection.Open();

        signalRConnection.OnConnected += (conn) =>
        {
            Debug.Log("Connect Successfully!");
            connectVars.SetTextStatus("You connected successfully!\nTap START! to find an opponent...");

            // Disable buttonConnect, buttonRetry and Enable buttonStart
            connectVars.ButtonConnectSetActive(false);
            connectVars.ButtonRetrySetActive(false);
            connectVars.ButtonStartSetActive(true);
        };
        signalRConnection.OnError += (conn, err) =>
        {
            Debug.Log(err);
            connectVars.SetTextStatus("Can't connect to the server :(");
        };
    }
Ejemplo n.º 6
0
        public void OnDisconnectGracefully()
        {
            var scopeMock             = new Mock <ILifetimeScope>();
            var userConnectionMapMock = new Mock <IUserConnectionMap>();

            userConnectionMapMock.SetupMapping();
            scopeMock.SetupResolve <ILifetimeScope, IUserConnectionMap>(userConnectionMapMock.Object);
            var rootScopeMock = new Mock <ILifetimeScope>();

            rootScopeMock.Setup(s => s.BeginLifetimeScope()).Returns(scopeMock.Object);
            var clientsMock = new Mock <IHubCallerConnectionContext <dynamic> >();

            clientsMock.SetupClients();

            var userName             = "******";
            var userId               = "1";
            var connectionID         = "13245";
            var hubCallerContextMock = CreateHubCallerContextMock(userName, userId, connectionID);

            GameHub hub = new GameHub(rootScopeMock.Object)
            {
                Context = hubCallerContextMock.Object,
                Clients = clientsMock.Object
            };

            hub.OnDisconnected(true);
        }
Ejemplo n.º 7
0
        protected void SendAlert(string message, List <string> userNames = null, List <Tuple <string, string> > userNameAndMessages = null)
        {
            Task.Run(async() =>
            {
                using (var scope = Services.CreateScope())
                {
                    var hubContext =
                        scope.ServiceProvider
                        .GetRequiredService <IHubContext <H, T> >();
                    GameAlert alert = new GameAlert(message, this.GameType);

                    if (userNames != null && userNames.Any() && !string.IsNullOrEmpty(message))
                    {
                        await hubContext.Clients.Users(userNames).ReceiveNotification(alert);
                    }
                    if (userNameAndMessages != null && userNameAndMessages.Any())
                    {
                        foreach (var userNameToMessage in userNameAndMessages)
                        {
                            await hubContext.Clients.User(userNameToMessage.Item1).ReceiveNotification(new GameAlert(userNameToMessage.Item2, this.GameType));
                        }
                    }
                    if ((userNames == null || !userNames.Any()) && !string.IsNullOrEmpty(message))
                    {
                        await hubContext.Clients.Group(GameHub.GetChannelGroupIdentifier(this.Id)).ReceiveNotification(alert);
                    }
                }
            });
        }
        public IHttpActionResult PostJoinGame(JoinPlayer player)
        {
            String     result = "";
            JoinPlayer jp     = new JoinPlayer();

            jp.PlayerName = player.PlayerName;
            jp.GameCode   = player.GameCode;
            GameHub.JoinGame(jp);

            try
            {
                if (this.ModelState.IsValid)
                {
                    DataAccess access = new DataAccess();
                    access.JoinGame(player);

                    result = "You have successfully joint the game(" + player.GameCode + ")";
                }
            }
            catch (Exception e)
            {
                result = "Joining game has error";
            }

            return(CreatedAtRoute("DefaultApi", new { id = 1 }, result));
        }
Ejemplo n.º 9
0
        public async Task <IActionResult> Answer(Guid id, int index, [FromBody] AnswerModel answer)
        {
            try
            {
                var game = await _store.GetGame(id);

                if (game.IsComplete)
                {
                    return(BadRequest("This game has ended"));
                }

                if (index > game.Questions.Count - 1)
                {
                    return(NotFound());
                }

                var question = game.Questions[index];
                if (question.HasAnswer)
                {
                    return(BadRequest("Question already answered"));
                }

                question.Answer = answer.Answer;
                await _store.UpdateGame(game);

                var response = game.ToResponseModel();
                await GameHub.SendUpdate(_clients, id, response);

                return(Ok(response));
            }
            catch (NotFoundException)
            {
                return(NotFound());
            }
        }
Ejemplo n.º 10
0
 public GameController(IGameDataService gameDataService, IPlayerRepository playerRepository, GameHub gameHub, IGameService gameService)
 {
     this._gameDataService  = gameDataService;
     this._playerRepository = playerRepository;
     this._gameHub          = gameHub;
     this._gameService      = gameService;
 }
Ejemplo n.º 11
0
        public async Task <IActionResult> Guess(Guid id, [FromBody] GuessModel guess)
        {
            try
            {
                var game = await _store.GetGame(id);

                if (game.IsComplete)
                {
                    return(BadRequest("This game has ended"));
                }

                game.Guesses.Add(guess.Guess);
                if (game.GuessMatches(guess.Guess))
                {
                    game.Won = true;
                }
                else if (game.GuessesCountAsQuestions && game.QuestionsTaken >= game.TotalQuestions)
                {
                    game.Lost = true;
                }
                await _store.UpdateGame(game);

                var response = game.ToResponseModel();
                await GameHub.SendUpdate(_clients, id, response);

                return(Ok(response));
            }
            catch (NotFoundException)
            {
                return(NotFound());
            }
        }
Ejemplo n.º 12
0
        public void SpawnBoosts()
        {
            Obstacle obs = new Powerup(0, 0, 0, 0, 0);

            if (rnd.Next(2) == 0)
            {
                return;
            }

            int powerUpType = rnd.Next(3);

            ObstacleFactory.boostPrototypes.TryGetValue((Powerup.PowerUpType)powerUpType, out obs);
            Obstacle pwrUp = obs.Clone();

            pwrUp.SetPosition(new System.Drawing.Point(rnd.Next(720), rnd.Next(280)));
            ((Powerup)pwrUp).SetTime(rnd.Next(3, 8));
            foreach (Game game in Program.Games)
            {
                foreach (Player player in game.Players)
                {
                    hubContext.Clients.Clients(GameHub.GetConnectionId(player.id.ToString())).SendAsync("Boost",
                                                                                                        ((Powerup)pwrUp).id,
                                                                                                        ((Powerup)pwrUp).type,
                                                                                                        ((Powerup)pwrUp).value,
                                                                                                        ((Powerup)pwrUp).x,
                                                                                                        ((Powerup)pwrUp).y,
                                                                                                        ((Powerup)pwrUp).time
                                                                                                        );
                }
            }
        }
Ejemplo n.º 13
0
        public void OnConnectedTest()
        {
            var gameHub = new GameHub();

            Dictionary <string, string> dict = new Dictionary <string, string>();

            dict.Add("name", "jan");

            Mock <Microsoft.AspNet.SignalR.Hosting.INameValueCollection> qs = new Mock <Microsoft.AspNet.SignalR.Hosting.INameValueCollection>();

            qs.Setup(x => x.Get(It.IsAny <string>())).Returns("efe");
            qs.Setup(x => x.GetEnumerator()).Returns(dict.GetEnumerator());

            Mock <HubCallerContext> mock = new Mock <HubCallerContext>();

            mock.SetupGet(x => x.QueryString).Returns(qs.Object);

            gameHub.CurrentContext = mock.Object;

            Task s = Task.Run(() => gameHub.OnConnected());

            s.Wait();

            Assert.NotNull(s);
        }
Ejemplo n.º 14
0
        public IActionResult StopEverything()
        {
            var gamehub = new GameHub(_hubContext, _gameService, _questionService);

            gamehub.StopAllTimers();
            _gameService.CleanUp();
            return(Ok());
        }
Ejemplo n.º 15
0
        public async Task StartGame(GameHub hub)
        {
            await hub.Groups.AddToGroupAsync(this.playerA.ConnectionId, this.groupId);

            await hub.Groups.AddToGroupAsync(this.playerB.ConnectionId, this.groupId);

            await hub.Clients.Group(this.groupId).SendAsync("StartGame");
        }
Ejemplo n.º 16
0
 private void  _initGameHub(Db db)
 {
     _gameHub = new GameHub(_gameServiceMock.Object, _roomServiceMock.Object, db)
     {
         Context = _contextMock.Object,
         Groups  = _groupsMock.Object,
         Clients = _clientsMock.Object
     };
 }
Ejemplo n.º 17
0
 /// <summary>
 /// Disposes the disposable resources used by the NinjectFactory instance.
 /// </summary>
 /// <param name="disposing">
 /// If true, the disposable resources of the NinjectFactory instance will be disposed.
 /// </param>
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         if (hub != null)
         {
             hub.Dispose();
             hub = null;
         }
     }
 }
Ejemplo n.º 18
0
        public void BrowseGames()
        {
            DbConnection connection = DbConnectionFactory.CreateTransient();
            var          game       = new Game
            {
                Id       = 1,
                IsActive = true,
                State    = new LobbyState(),
                Players  =
                {
                    new Player()
                }
            };

            using (var gwintContext = new GwintContext(connection))
            {
                gwintContext.Games.Add(game);
                gwintContext.SaveChanges();
            }

            var scopeMock = new Mock <ILifetimeScope>();

            scopeMock.SetupResolve <ILifetimeScope, IGwintContext>(new GwintContext(connection));
            var userConnectionMapMock = new Mock <IUserConnectionMap>();

            userConnectionMapMock.SetupMapping();
            scopeMock.SetupResolve <ILifetimeScope, IUserConnectionMap>(userConnectionMapMock.Object);
            var rootScopeMock = new Mock <ILifetimeScope>();

            rootScopeMock.Setup(s => s.BeginLifetimeScope()).Returns(scopeMock.Object);
            var clientsMock = new Mock <IHubCallerConnectionContext <dynamic> >();

            clientsMock.SetupClients();

            var userName             = "******";
            var userId               = "1";
            var connectionID         = "13245";
            var hubCallerContextMock = CreateHubCallerContextMock(userName, userId, connectionID);

            GameHub hub = new GameHub(rootScopeMock.Object)
            {
                Context = hubCallerContextMock.Object,
                Clients = clientsMock.Object
            };

            var result = hub.BrowseGames();

            Assert.Null(result.Error);
            var gameBrowseDtos = result.Data;

            Assert.NotNull(gameBrowseDtos);
            Assert.Equal(1, gameBrowseDtos.Count);
            Assert.Contains(gameBrowseDtos, g => g.Id == game.Id && g.State == game.State.Name && g.PlayerCount == game.Players.Count);
        }
Ejemplo n.º 19
0
        public async Task <IActionResult> StartGame(string gameName)
        {
            var gamehub = new GameHub(_hubContext, _gameService, _questionService);
            await _hubContext.Clients.Groups(gameName).GameStarted();

            await gamehub.CreateTimers(gameName);

            var question = await _questionService.NextQuestion(gameName, 0);

            await _hubContext.Clients.Groups(gameName).SendQuestion(question);

            gamehub.StartGameTimer(gameName);
            return(Ok());
        }
Ejemplo n.º 20
0
        protected void SendSystemMessage(string message)
        {
            Task.Run(async() =>
            {
                using (var scope = Services.CreateScope())
                {
                    var hubContext =
                        scope.ServiceProvider
                        .GetRequiredService <IHubContext <H, T> >();

                    await hubContext.Clients.Group(GameHub.GetChannelGroupIdentifier(this.Id)).ReceiveSystemMessage(message);
                }
            });
        }
Ejemplo n.º 21
0
 public LeaveRoomCommandHandler(RoomRepository roomRepository,
                                PlayerRepository playerRepository,
                                IUnitOfWork <GameDbContext> unitOfWork,
                                IHttpContextAccessor context,
                                GameDbContext dbContext,
                                GameHub gameHub)
 {
     _roomRepository   = roomRepository;
     _playerRepository = playerRepository;
     _unitOfWork       = unitOfWork;
     _context          = context;
     _dbContext        = dbContext;
     _gameHub          = gameHub;
 }
Ejemplo n.º 22
0
 public HubFunctionalTests()
 {
     mockPlayService      = new Mock <IPlayService>();
     mockClients          = new Mock <IHubCallerClients <IGameHub> >();
     mockClientProxy      = new Mock <IGameHub>();
     mockHubCallerContext = new Mock <HubCallerContext>();
     hub      = new GameHub(mockPlayService.Object);
     messages = new List <Message>();
     mockClients.Setup(clients => clients.All).Returns(mockClientProxy.Object);
     mockClients.Setup(clients => clients.Caller).Returns(mockClientProxy.Object);
     mockClients.Setup(clients => clients.Clients(It.IsAny <List <string> >())).Returns(mockClientProxy.Object);
     mockClientProxy.Setup(m => m.MessageClient(Capture.In(messages)));
     hub.Clients = mockClients.Object;
     hub.Context = mockHubCallerContext.Object;
 }
Ejemplo n.º 23
0
        public override async Task TerminateGame()
        {
            using (var scope = Services.CreateScope())
            {
                var hubContext =
                    scope.ServiceProvider
                    .GetRequiredService <IHubContext <H, T> >();
                await hubContext.Clients.Group(GameHub.GetChannelGroupIdentifier(this.Id)).ReceiveSystemMessage($"Game {this.Id} has ended.");

                foreach (Player p in Players.Values)
                {
                    await hubContext.Groups.RemoveFromGroupAsync(p.SignalRConnectionId, GameHub.GetChannelGroupIdentifier(this.Id));
                }
            }
        }
Ejemplo n.º 24
0
        public void Setup()
        {
            mockBoot = new Mock <IBootstrapper>();

            hub = new GameHub(mockBoot.Object, Mock.Of <IThreadSleeper>());

            var mockContext = new Mock <IHubCallerConnectionContext <dynamic> >();

            hub.Clients = mockContext.Object;

            clients = new Mock <IGameClientContract>();
            mockContext.Setup(x => x.All).Returns(clients.Object);

            clients.Setup(x => x.DisplayError(It.IsAny <string>())).Verifiable();
            clients.Setup(x => x.DisplayResults(It.IsAny <GameBase>())).Verifiable();
        }
Ejemplo n.º 25
0
        public void FinishGameAsync(GameHub hub)
        {
            hub.Clients.Client(this.playerA.ConnectionId).SendAsync("FinishGame", this.choiceB);
            hub.Clients.Client(this.playerB.ConnectionId).SendAsync("FinishGame", this.choiceA);

            if (this.choiceA != this.choiceB)
            {
                //Remove group
                hub._pr.games = hub._pr.games.Where(g => g.groupId != this.groupId).ToList();
            }
            else
            {
                //Draw - Restart
                this.choiceA = 0;
                this.choiceB = 0;
            }
        }
Ejemplo n.º 26
0
        public void SetChoice(GameHub hub, Player p, int choice)
        {
            if (p.ConnectionId == this.playerA.ConnectionId && this.choiceA == 0)
            {
                this.choiceA = choice;
            }
            if (p.ConnectionId == this.playerB.ConnectionId && this.choiceB == 0)
            {
                this.choiceB = choice;
            }

            //Early finished game
            if (this.choiceA != 0 && this.choiceB != 0)
            {
                this.FinishGameAsync(hub);
            }
        }
Ejemplo n.º 27
0
        public async Task Announce_GivenUsername_ExpectPlayerBeAdded()
        {
            //Arrange
            var mockDatabase = Substitute.For <IDatabaseRepository>();

            mockDatabase.AddConnectionAsync(Arg.Any <string>(), Arg.Any <string>()).Returns(Task.CompletedTask);
            var context = Substitute.For <HubCallerContext>();

            context.ConnectionId.Returns("1234");
            var hub = new GameHub(mockDatabase)
            {
                Context = context
            };

            //Act
            await hub.AnnounceAsync("Player-1");

            //Assert
            await mockDatabase.Received(1).AddConnectionAsync("Player-1", "1234");
        }
Ejemplo n.º 28
0
        public async Task <IActionResult> Ask(Guid id, [FromBody] AskQuestionModel question)
        {
            try
            {
                var game = await _store.GetGame(id);

                if (game.IsComplete)
                {
                    return(BadRequest("This game has ended"));
                }

                if (game.QuestionsTaken >= game.TotalQuestions)
                {
                    return(BadRequest("No more questions allowed"));
                }

                if (!game.AllowConcurrentQuestions && game.Questions.Count > 0 && !game.Questions.Last().HasAnswer)
                {
                    return(BadRequest("Only one question allowed at a time"));
                }

                var questionModel = new QuestionModel
                {
                    Question = question.Question
                };

                game.Questions.Add(questionModel);
                await _store.UpdateGame(game);

                var response = game.ToResponseModel();
                await GameHub.SendUpdate(_clients, id, response);

                return(Ok(response));
            }
            catch (NotFoundException)
            {
                return(NotFound());
            }
        }
Ejemplo n.º 29
0
 public void UpdateGames()
 {
     foreach (Game game in Program.Games)
     {
         foreach (Obstacle obstacle in game.Obstacles)
         {
             obstacle.Move();
             int width, height;
             obstacle.GetSize(out width, out height);
             foreach (Player player in game.Players)
             {
                 hubContext.Clients.Clients(GameHub.GetConnectionId(player.id.ToString())).SendAsync("Obstacle",
                                                                                                     obstacle.GetType().Name.ToString(),
                                                                                                     obstacle.GetId(),
                                                                                                     obstacle.GetX(),
                                                                                                     obstacle.GetY(),
                                                                                                     width,
                                                                                                     height,
                                                                                                     obstacle.GetColor().applyColor());
             }
         }
     }
 }
Ejemplo n.º 30
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                var players = GameHub.getPlayers();
                if (players.Count > 0)
                {
                    CheckAndRegisterHits(players);
                    ExplosionAnimation(players);

                    try
                    {
                        var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(players);
                        await _hubContext.Clients.All.SendAsync("state", jsonString);

                        await Task.Delay(1000 / 60);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex);
                    }
                }
            }
        }
Ejemplo n.º 31
0
 public GameHubHandler(GameHub hub, IGameContainer games)
 {
     Hub = hub;
     Games = games;
 }