public IHttpActionResult Create()
        {
            var currentUserId = this.userIdProvider.GetUserId();

            //// Check whether the player has already created a game which is waiting someone else to enter
            //var game =
            //    this.data.Games
            //        .All()
            //        .FirstOrDefault(g => g.State == GameState.WaitingForSecondPlayer && g.FirstPlayerId == currentUserId);

            //if (game != null)
            //{
            //    return this.Ok(game.Id);
            //}

            var game = new Game
            {
                FirstPlayerId = currentUserId,
            };

            this.data.Games.Add(game);
            this.data.SaveChanges();

            return this.Ok(game.Id);
        }
Esempio n. 2
0
        public void MakeGuess_WhenLastMoveAndNoWinner_ShouldReturnStateGameOver()
        {
            User user=new User()
            {
                SessionKey="10043IOvy7N9Bn9BDAk2mtT7ZcYKtZbBpdp00ZoIpJikyIJtef",
                Id=1
            };
            Game updatedGame = new Game();
            List<Guess> guesses = new List<Guess>();
            guesses.Add(new Guess() { Position = 1, User=user });
            mock.Setup(g => g.Games.GetById(It.IsAny<int>())).Returns(
              new Game()
            {
                MovesLeft=1,
                Guesses = guesses,
                GameStatus = "InProgress",
                UserInTurn = 1,
                RedUserId = 1
            });
            mock.Setup(g => g.Users.GetAll()).Returns(new User[]{ user }.AsQueryable());

            mock.Setup(u => u.Games.Update(It.IsAny<Game>())).Callback((Game game) => updatedGame = game);
            GuessModel guessModel = new GuessModel("10043IOvy7N9Bn9BDAk2mtT7ZcYKtZbBpdp00ZoIpJikyIJtef", 1, 2);
            guessService.MakeGuess(guessModel, out gameState);

            Assert.IsTrue(gameState.gameOver);
            Assert.IsNull(gameState.Winner);
            Assert.AreEqual(updatedGame.GameStatus, "Finished");
        }
        public ActionResult JoinOrCreate()
        {
            Game game;
            if (_persistence.Exists(Request.Form["GameName"]))
            {
                game = _persistence.Get(Request.Form["GameName"]);
                game.Player2 = new Player
                    {
                        Name = Request.Form["PlayerName"],
                        Symbol = Symbols.O
                    };
                Session["MyPlayer"] = game.Player2;
            }
            else
            {
                game = new Game
                    {
                        Name = Request.Form["GameName"],
                        Player1 = new Player
                            {
                                Name = Request.Form["PlayerName"],
                                Symbol = Symbols.X
                            },
                        Board = Game.CreateDashboard()
                    };
                Session["MyPlayer"] = game.Player1;
            }
            _persistence.Save(game);
            Session["Game"] = game.Name;

            return RedirectToAction("Dashboard");
        }
Esempio n. 4
0
        public void CreateGame_WhenCreateGameModelIsValid_ShouldAddGameToRepository()
        {
            Game newGame = new Game();
            CreateGameModel createGameModel = new CreateGameModel()
            {
                SessionKey = "100431CZhiZTwwJAh8VTo559HfIyYf8lXyq74Bi2UkBP64ZoLL",
                Password = null,
                Title = "Title",
            };

            mock.Setup(g => g.Users.GetAll()).Returns(new User[]
            {
                new User
                {
                    SessionKey = "100431CZhiZTwwJAh8VTo559HfIyYf8lXyq74Bi2UkBP64ZoLL",
                    Nickname = "Kalinskia",
                    Username = "******",
                },
            }.AsQueryable());
            mock.Setup(u => u.Games.Add(It.IsAny<Game>())).Callback((Game game) => newGame = game);
            GameService gameservice = new GameService(mock.Object);
            gameservice.CreateGame(createGameModel);
            Assert.AreEqual("Title", newGame.Title);
            Assert.IsNull(newGame.Password);
            Assert.AreEqual("Title", newGame.Title);
            Assert.AreEqual("100431CZhiZTwwJAh8VTo559HfIyYf8lXyq74Bi2UkBP64ZoLL", newGame.RedUser.SessionKey);
            Assert.AreEqual("Kalinskia", newGame.RedUser.Nickname);
            Assert.AreEqual("Kalin", newGame.RedUser.Username);
            Assert.AreEqual(9, newGame.MovesLeft);
            Assert.AreEqual("Open", newGame.GameStatus);
            Assert.IsNull(newGame.UserInTurn);
            Assert.IsNull(newGame.Winner);
            Assert.IsNull(newGame.BlueUser);
        }
Esempio n. 5
0
 private bool CheckGameOver(Game game)
 {
     if (game.MovesLeft <= 0)
     {
         return true;
     }
     return false;
 }
 public GameInfoDataModel(Game game)
 {
     this.Id = game.Id;
     this.Board = game.Board;
     this.FirstPlayerName = game.FirstPlayer != null ? game.FirstPlayer.Email : "";
     this.SecondPlayerName = game.SecondPlayer != null ? game.SecondPlayer.Email : "";
     this.State = game.State.ToString();
 }
 public void Save(Game game)
 {
     if (!Directory.Exists("TicTacToes"))
     {
         Directory.CreateDirectory("TicTacToes");
     }
     var writer = new StreamWriter(GetFileName(game.Name));
     _serializer.Serialize(writer, game);
     writer.Close();
 }
Esempio n. 8
0
 public static void ValidateUserInGame(Game game,User user)
 {
     if(game==null||user==null)
     {
         throw new ArgumentNullException("Game or user is null");
     }
     if (game.RedUserId != user.Id && game.BlueUserId != user.Id)
     {
         throw new ServerErrorException("User not in game", "INV_GAME_USR");
     }
 }
        public IHttpActionResult Create()
        {
            var currentUserId = this.userIdProvider.GetUserId();

            var newGame = new Game { FirstPlayerId = currentUserId, };

            this.data.Games.Add(newGame);
            this.data.SaveChanges();

            return this.Ok(newGame.Id);
        }
Esempio n. 10
0
        public IHttpActionResult Create(CreateGameDataModel gameModel)
        {
            var currentUserId = this.userInfoProvider.GetUserId();

            var newGame = new Game
            {
                Name = gameModel.Name,
                FirstPlayerId = currentUserId,
                DateCreated = DateTime.Now
            };

            this.Data.Games.Add(newGame);
            this.Data.SaveChanges();

            return this.Ok(newGame.GameId);
        }
        public IHttpActionResult Create()
        {
            var userId = User.Identity.GetUserId();
            var game = new Game { FirstPlayerId = userId };
            this.data.Games.Add(game);
            this.data.SaveChanges();

            var gameDataModel =
                this.data.Games.All()
                    .Where(x => x.Id == game.Id)
                    .Project()
                    .To<GameInfoDataModel>()
                    .FirstOrDefault();

            return this.Ok(gameDataModel);
        }
Esempio n. 12
0
 public void MakeGuess_WhenGameStatusIsNotInProgress_ShouldThrowException()
 {
     Game game = new Game()
     {
         GameStatus = "Full",
     };
      mock.Setup(g => g.Users.GetAll()).Returns(new User[]
     {new User()
     {
         SessionKey="10043IOvy7N9Bn9BDAk2mtT7ZcYKtZbBpdp00ZoIpJikyIJtef",
         Id=1
     }}.AsQueryable());
      GuessModel guessModel = new GuessModel("10043IOvy7N9Bn9BDAk2mtT7ZcYKtZbBpdp00ZoIpJikyIJtef", 1, 1);
      mock.Setup(g => g.Games.GetById(It.IsAny<int>())).Returns(game);
      guessService.MakeGuess(guessModel, out gameState);
 }
Esempio n. 13
0
        public void WhenIsXTurnChangeStateToO()
        {
            var userId = "Niki";
            var gameId = Guid.NewGuid();
            var game = new Game
            {
                Id = gameId,
                FirstPlayerId = userId,
                State = GameState.TurnX
            };
            game.Id = gameId;

            var userIdProviderMock = new Mock<IUserIdProvider>();
            userIdProviderMock.Setup(x => x.GetUserId()).
                Returns(userId);

            var repositoryMock = new Mock<IRepository<Game>>();
            repositoryMock.Setup(x => x.All()).Returns(() =>
                new List<Game>()
                {
                    game,
                }
                .AsQueryable());
            repositoryMock.Setup(x => x.Find(It.IsAny<Guid>()))
                .Returns(game);
            var uowData = new Mock<ITicTacToeData>();
            uowData.SetupGet(x => x.Games).Returns(
                repositoryMock.Object);

            var controller = new GamesController(
                    uowData.Object,
                    new GameResultValidator(),
                    userIdProviderMock.Object);

            var result = controller.Play(new PlayRequestDataModel()
                {
                    GameId = gameId.ToString(),
                    Col = 1,
                    Row = 1,
                });

            Assert.AreEqual(GameState.TurnO, game.State);
        }
Esempio n. 14
0
 public void CreateGame(CreateGameModel gameModel)
 {
     //TODO: Validate Title
     if(gameModel==null)
     {
         throw new ArgumentNullException("CreateGameModel is null");
     }
     ValidateGamePassword(gameModel.Password);
     User redUser = GetUserBySessionKey(gameModel.SessionKey);
     Game game = new Game()
     {
         Title = gameModel.Title,
         Password = gameModel.Password,
         RedUser = redUser,
         GameStatus = GameStatusType.Open,
         MovesLeft = 9
     };
     this.Data.Games.Add(game);
     this.Data.SaveChanges();
 }
Esempio n. 15
0
 private void AddToScore(Game game, string playerId, ScoreStatus scoreStatus)
 {
     this.Data.Scores.Add(new Score()
     {
         GameId = game.GameId,
         PlayerId = Guid.Parse(playerId),
         ScoreStatus = scoreStatus
     });
 }
Esempio n. 16
0
        public void ValidateUserInGame_WhenRedUserIsUser_ShouldThrowException()
        {
            User redUser = new User()
            {
                Id = 1,
            };

            Game game = new Game();
            game.RedUserId = 1;
            BaseService.ValidateUserInGame(game, redUser);
        }
Esempio n. 17
0
        public void ValidateUserInGame_WhenRedUserOrBlueUserNotMatchWithUser_ShouldThrowException()
        {
            Game game = new Game()
            {

                RedUserId = 1,
                BlueUserId = 2
            };
            BaseService.ValidateUserInGame(game, new User());
        }
Esempio n. 18
0
 public void MakeGuess_WhenPositionIsOccupied_ShouldThrowException()
 {
     List<Guess> guesses = new List<Guess>();
     guesses.Add(new Guess() { Position = 1 });
     Game game = new Game()
     {
         Guesses=guesses,
         GameStatus = "InProgress",
         UserInTurn = 1,
         RedUserId = 1
     };
     mock.Setup(g => g.Users.GetAll()).Returns(new User[]
     {new User()
     {
         SessionKey="10043IOvy7N9Bn9BDAk2mtT7ZcYKtZbBpdp00ZoIpJikyIJtef",
         Id=1
     }}.AsQueryable());
     GuessModel guessModel = new GuessModel("10043IOvy7N9Bn9BDAk2mtT7ZcYKtZbBpdp00ZoIpJikyIJtef", 1, 1);
     mock.Setup(g => g.Games.GetById(It.IsAny<int>())).Returns(game);
     guessService.MakeGuess(guessModel, out gameState);
 }
Esempio n. 19
0
 private void AddToScore(Game game, string playerId, bool isWin)
 {
     this.Data.Scores.Add(new Score()
     {
         GameId = game.GameId,
         PlayerId = Guid.Parse(playerId),
         IsWin = isWin
     });
 }
Esempio n. 20
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="game"></param>
 /// <param name="position">The position where to place the marker, should be between 0 and 9</param>
 /// <returns>True if the marker position was not already taken</returns>
 private void PlaceMarker(Game game, User user, int position)
 {
     int count = game.Guesses.Where(g => g.Position == position).Count();
     if (count != 0)
     {
        throw new ServerErrorException("The position is occupied", "INV_POS");
     }
     Guess newGuess = new Guess()
     {
         Position = position,
         User = user,
         Game = game,
     };
     game.Guesses.Add(newGuess);
     game.MovesLeft--;
 }
Esempio n. 21
0
        public void MakeGuess_WhenPlaceThirdRow_ShouldWinning()
        {
            User redUser = new User()
             {
                 SessionKey = "10043IOvy7N9Bn9BDAk2mtT7ZcYKtZbBpdp00ZoIpJikyIJtef",
                 Id = 1
             };
             Game updatedGame = new Game();
             List<Guess> guesses = new List<Guess>();
             guesses.Add(new Guess() { Position = 7, User = redUser });
             guesses.Add(new Guess() { Position = 8, User = redUser });

             mock.Setup(g => g.Games.GetById(It.IsAny<int>())).Returns(
               new Game()
               {
                   MovesLeft = 9,
                   Guesses = guesses,
                   GameStatus = "InProgress",
                   UserInTurn = 1,
                   RedUserId = 1
               });
             mock.Setup(g => g.Users.GetAll()).Returns(new User[] { redUser }.AsQueryable());
             mock.Setup(u => u.Games.Update(It.IsAny<Game>())).Callback((Game game) => updatedGame = game);
             GuessModel guessModel = new GuessModel("10043IOvy7N9Bn9BDAk2mtT7ZcYKtZbBpdp00ZoIpJikyIJtef", 1, 9);
             guessService.MakeGuess(guessModel, out gameState);
             Assert.AreEqual(1, updatedGame.Winner.Id);
             Assert.IsTrue(gameState.gameOver);
        }
Esempio n. 22
0
 public static Game Games(string key, Game game)
 {
     System.Web.HttpContext.Current.Cache["games" + key] = game;
     return game;
 }
Esempio n. 23
0
        public void MakeGuess_WhenPlacedMaerkerAndGameIsNotOver_ShouldUpdateGame()
        {
            User redUser = new User()
            {
                SessionKey = "10043IOvy7N9Bn9BDAk2mtT7ZcYKtZbBpdp00ZoIpJikyIJtef",
                Id = 1
            };
               User blueUser = new User()
            {
                SessionKey = "20043IOvy7N9Bn9BDAk2mtT7ZcYKtZbBpdp00ZoIpJikyIJtef",
                Id = 2
            };
            Game updatedGame = new Game();
            List<Guess> guesses = new List<Guess>();
            guesses.Add(new Guess() { Position = 1, User = blueUser });
            mock.Setup(g => g.Games.GetById(It.IsAny<int>())).Returns(
              new Game()
              {
                  MovesLeft = 8,
                  Guesses = guesses,
                  GameStatus = "InProgress",
                  UserInTurn = 1,
                  RedUser=redUser,
                  RedUserId = 1,
                  BlueUser=blueUser,
                  BlueUserId=2
              });
            mock.Setup(g => g.Users.GetAll()).Returns(new User[] { redUser }.AsQueryable());

            mock.Setup(u => u.Games.Update(It.IsAny<Game>())).Callback((Game game) => updatedGame = game);
            GuessModel guessModel = new GuessModel("10043IOvy7N9Bn9BDAk2mtT7ZcYKtZbBpdp00ZoIpJikyIJtef", 1, 2);
            guessService.MakeGuess(guessModel, out gameState);

            Assert.AreEqual(2, updatedGame.UserInTurn);
            Assert.IsFalse(gameState.gameOver);
            Assert.IsNull(gameState.Winner);
            Assert.AreEqual(updatedGame.GameStatus, "InProgress");
        }
Esempio n. 24
0
        public void RestartGameState_WhenUserInGame_ShouldRestartAndUpdateGameState()
        {
            Game updatedGame = new Game();
            Guess[] guess = new Guess[]
            {
                new Guess() { Id = 1 },
                new Guess() { Id = 2 },
                new Guess() { Id = 3 },
            };
            mock.Setup(g => g.Users.GetAll()).Returns(new User[]
            {
                new User
                {
                    Id = 2,
                    Nickname = "creatorNickname",
                    Username = "******",
                    SessionKey = "10043IOvy7N9Bn9BDAk2mtT7ZcYKtZbBpdp00ZoIpJikyIJtef",
                },
            }.AsQueryable());

            mock.Setup(g => g.Games.GetById(It.IsAny<int>())).Returns(
                new Game()
                {
                    Password = null,
                    GameStatus = "Open",
                    RedUserId = 1,
                    Winner = new User(),
                    BlueUserId = 2,
                    Guesses = guess
                });

            GameService gameSerivce = new GameService(mock.Object);
            mock.Setup(u => u.Games.Update(It.IsAny<Game>())).Callback((Game game) => updatedGame = game);
            mock.Setup(u => u.Guesses.Remove(It.IsAny<Guess[]>()));
            gameSerivce.RestartGameState("10043IOvy7N9Bn9BDAk2mtT7ZcYKtZbBpdp00ZoIpJikyIJtef", 1, "Open");

            Assert.AreEqual("Open", updatedGame.GameStatus);
            Assert.AreEqual(9, updatedGame.MovesLeft);
            Assert.IsNull(updatedGame.Winner);
        }
        private void DoMovement(Game game, Player player)
        {
            var x = int.Parse(Request.Form["X"]);
            var y = int.Parse(Request.Form["Y"]);

            if (game.Board[x][y] == null)
            {
                game.Board[x][y] = player;
                game.CurrentPlayer = game.CurrentPlayer == Symbols.X ? Symbols.O : Symbols.X;
                _persistence.Save(game);
            }
            else
            {
                Session["Info"] = "The other player already took that position :(";
            }
        }
Esempio n. 26
0
        public void LeaveGame_WhenUserIsГuest_ShouldUpdateGameState()
        {
            Game updatedGame = new Game();
            mock.Setup(g => g.Users.GetAll()).Returns(new User[]
            {
                new User
                {
                    Id = 2,
                    Nickname = "creatorNickname",
                    Username = "******",
                    SessionKey = "10043IOvy7N9Bn9BDAk2mtT7ZcYKtZbBpdp00ZoIpJikyIJtef",
                },
            }.AsQueryable());

            mock.Setup(g => g.Games.GetById(It.IsAny<int>())).Returns(
                new Game()
                {
                    Password = null,
                    GameStatus = "Full",
                    RedUserId = 1,
                    Winner = new User(),
                    BlueUserId = 2,
                    BlueUser = new User(),
                });
            mock.Setup(u => u.Games.Update(It.IsAny<Game>())).Callback((Game game) => updatedGame = game);

            GameService gameSerivce = new GameService(mock.Object);
            gameSerivce.LeaveGame(1, "10043IOvy7N9Bn9BDAk2mtT7ZcYKtZbBpdp00ZoIpJikyIJtef");

            Assert.AreEqual("Open", updatedGame.GameStatus);
            Assert.IsNull(updatedGame.BlueUser);
        }
Esempio n. 27
0
        public void LeaveGame_WhenUserIsCreator_ShouldNotUpdateGameState()
        {
            Game updatedGame = new Game();
            mock.Setup(g => g.Users.GetAll()).Returns(new User[]
            {
                new User
                {
                    Id = 1,
                    Nickname = "creatorNickname",
                    Username = "******",
                    SessionKey = "10043IOvy7N9Bn9BDAk2mtT7ZcYKtZbBpdp00ZoIpJikyIJtef",
                },
            }.AsQueryable());

            mock.Setup(g => g.Games.GetById(It.IsAny<int>())).Returns(
                new Game()
                {
                    Password = null,
                    GameStatus = "Full",
                    RedUserId = 1,
                    Winner = new User(),
                    BlueUserId = 2,
                });

            GameService gameSerivce = new GameService(mock.Object);
            gameSerivce.LeaveGame(1, "10043IOvy7N9Bn9BDAk2mtT7ZcYKtZbBpdp00ZoIpJikyIJtef");

            mock.Verify(u => u.Games.Update(It.IsAny<Game>()), Times.Never());
        }
Esempio n. 28
0
 public void JoinGame_WhenDataIsValid_ShouldUpdateGameState()
 {
     Game updatedGame = new Game();
     JoinGameModel joinGameModel = new JoinGameModel()
     {
         GameId = 1,
         Password = null,
         SessionKey = "10043IOvy7N9Bn9BDAk2mtT7ZcYKtZbBpdp00ZoIpJikyIJtef",
     };
     mock.Setup(g => g.Games.GetById(It.IsAny<int>())).Returns(
         new Game()
         {
             Password = null,
             GameStatus = "Open",
             RedUserId = 1
         });
     mock.Setup(g => g.Users.GetAll()).Returns(new User[]
     {
         new User
         {
             Id = 2,
             Nickname = "creatorNickname",
             Username = "******",
             SessionKey = "10043IOvy7N9Bn9BDAk2mtT7ZcYKtZbBpdp00ZoIpJikyIJtef",
         },
     }.AsQueryable());
     mock.Setup(u => u.Games.Update(It.IsAny<Game>())).Callback((Game game) => updatedGame = game);
     GameService gameService = new GameService(mock.Object);
     gameService.JoinGame(joinGameModel);
     Assert.AreEqual("Full", updatedGame.GameStatus);
     Assert.AreEqual(2, updatedGame.BlueUser.Id);
 }
Esempio n. 29
0
        private void ChangeGameState(GameResult gameResult, Game game)
        {
            switch (gameResult)
            {
                case GameResult.WonByX:
                    {
                        game.State = GameState.WonByX;
                        this.AddToScore(game, game.FirstPlayerId, true);
                        this.AddToScore(game, game.SecondPlayerId, false);

                        this.Data.SaveChanges();
                        break;
                    }
                case GameResult.WonByO:
                    {
                        game.State = GameState.WonByO;
                        this.AddToScore(game, game.FirstPlayerId, false);
                        this.AddToScore(game, game.SecondPlayerId, true);

                        this.Data.SaveChanges();
                        break;
                    }
                case GameResult.Draw:
                    {
                        game.State = GameState.Draw;
                        this.Data.SaveChanges();
                        break;
                    }
            }
        }
Esempio n. 30
0
        public void StartGame_WhenStateIsFullAndUserIsCreator_ShouldUpdateGameState()
        {
            Game updatedGame = new Game();
            mock.Setup(g => g.Users.GetAll()).Returns(new User[]
            {
                new User
                {
                    Id = 1,
                    Nickname = "creatorNickname",
                    Username = "******",
                    SessionKey = "10043IOvy7N9Bn9BDAk2mtT7ZcYKtZbBpdp00ZoIpJikyIJtef",
                },
            }.AsQueryable());

            mock.Setup(g => g.Games.GetById(It.IsAny<int>())).Returns(
                new Game()
                {
                    Password = null,
                    GameStatus = "Full",
                    RedUserId = 1,
                    Winner = new User(),
                    BlueUserId = 2,
                });

            mock.Setup(u => u.Games.Update(It.IsAny<Game>())).Callback((Game game) => updatedGame = game);

            GameService gameSerivce = new GameService(mock.Object);
            gameSerivce.StartGame("10043IOvy7N9Bn9BDAk2mtT7ZcYKtZbBpdp00ZoIpJikyIJtef", 1);

            Assert.AreEqual("InProgress", updatedGame.GameStatus);
            Assert.IsTrue(updatedGame.UserInTurn == 1 || updatedGame.UserInTurn == 2);
        }