public void Load(MyChessGame game)
        {
            Initialize();
            foreach (var gameMove in game.Moves)
            {
                MakeMove(gameMove.Move);
                if (gameMove.SpecialMove != null)
                {
                    switch (gameMove.SpecialMove)
                    {
                    case MyChessGameSpecialMove.PromotionToRook:
                        ChangePromotion(PieceRank.Rook);
                        break;

                    case MyChessGameSpecialMove.PromotionToKnight:
                        ChangePromotion(PieceRank.Knight);
                        break;

                    case MyChessGameSpecialMove.PromotionToBishop:
                        ChangePromotion(PieceRank.Bishop);
                        break;
                    }
                }
            }
        }
Esempio n. 2
0
        private void MakeMoves(MyChessGame game)
        {
            _chessBoard.Initialize();
            foreach (var gameMove in game.Moves)
            {
                _chessBoard.MakeMove(gameMove.Move);
                if (gameMove.SpecialMove != null)
                {
                    switch (gameMove.SpecialMove)
                    {
                    case MyChessGameSpecialMove.PromotionToRook:
                        _chessBoard.ChangePromotion(PieceRank.Rook);
                        break;

                    case MyChessGameSpecialMove.PromotionToKnight:
                        _chessBoard.ChangePromotion(PieceRank.Knight);
                        break;

                    case MyChessGameSpecialMove.PromotionToBishop:
                        _chessBoard.ChangePromotion(PieceRank.Bishop);
                        break;
                    }
                }
            }
        }
Esempio n. 3
0
        public byte[] Compact(MyChessGame game)
        {
            var json   = JsonSerializer.Serialize(game);
            var buffer = Encoding.UTF8.GetBytes(json);

            using var input      = new MemoryStream(buffer);
            using var output     = new MemoryStream();
            using var compressor = new BrotliStream(output, CompressionMode.Compress);
            input.CopyTo(compressor);
            compressor.Flush();
            return(output.ToArray());
        }
Esempio n. 4
0
        public async Task Create_New_Game()
        {
            // Arrange
            var expectedWhitePlayer = "user123";
            var expectedBlackPlayer = "user456";

            var user = new AuthenticatedUser()
            {
                Name = "abc",
                PreferredUsername  = "******",
                UserIdentifier     = "u1",
                ProviderIdentifier = "p1"
            };

            // Player creating the game
            await _context.UpsertAsync(TableNames.Users, new UserEntity()
            {
                PartitionKey = "u1",
                RowKey       = "p1",
                UserID       = "user123"
            });

            // Opponent
            await _context.UpsertAsync(TableNames.Users, new UserEntity()
            {
                PartitionKey = "u2",
                RowKey       = "p2",
                UserID       = "user456"
            });

            await _context.UpsertAsync(TableNames.UserID2User, new UserID2UserEntity()
            {
                PartitionKey   = "user456",
                RowKey         = "user456",
                UserPrimaryKey = "u2",
                UserRowKey     = "p2"
            });

            var gameToCreate = new MyChessGame();

            gameToCreate.Players.Black.ID = "user456";
            gameToCreate.Moves.Add(new MyChessGameMove());

            // Act
            var actual = await _gamesHandler.CreateGameAsync(user, gameToCreate);

            // Assert
            Assert.Null(actual.Error);
            Assert.NotNull(actual.Game);
            Assert.Equal(expectedWhitePlayer, actual.Game?.Players.White.ID);
            Assert.Equal(expectedBlackPlayer, actual.Game?.Players.Black.ID);
        }
Esempio n. 5
0
        public void Compress_Decompress_Test()
        {
            // Arrange
            var expected = new MyChessGame
            {
                ID = "abc"
            };

            expected.Players.Black.ID = "def";
            var buffer = _compactor.Compact(expected);

            // Act
            var actual = _compactor.Decompress(buffer);

            // Assert
            Assert.Equal(expected.ID, actual.ID);
            Assert.Equal(expected.Players.Black.ID, actual.Players.Black.ID);
        }
Esempio n. 6
0
        public async Task Create_Game_Fails_Due_Invalid_Opponent_Test()
        {
            // Arrange
            var expected      = typeof(ObjectResult);
            var expectedError = "1234";
            var game          = new MyChessGame()
            {
                Name    = "great game",
                State   = "Normal",
                Updated = DateTimeOffset.UtcNow
            };

            game.Players.White.ID = "p1";
            game.Players.Black.ID = "p3";
            game.Moves.Add(new MyChessGameMove()
            {
                Move    = "A2A3",
                Comment = "Cool move",
                Start   = DateTimeOffset.UtcNow.AddMinutes(-1),
                End     = DateTimeOffset.UtcNow
            });

            _gamesHandlerStub.Error = new Models.HandlerError()
            {
                Instance = "some text/1234"
            };

            var identity = new ClaimsIdentity();

            identity.AddClaim(new Claim("http://schemas.microsoft.com/identity/claims/scope", "Games.ReadWrite"));
            _securityValidatorStub.ClaimsPrincipal = new ClaimsPrincipal(identity);

            var req = HttpRequestHelper.Create("POST", body: game, query: new Dictionary <string, Microsoft.Extensions.Primitives.StringValues>());

            // Act
            var actual = await _gamesFunction.Run(req, SignalRHelper.Create(), "abc");

            // Assert
            Assert.IsType(expected, actual);
            var body        = actual as ObjectResult;
            var actualError = body?.Value as ProblemDetails;

            Assert.EndsWith(expectedError, actualError?.Instance);
        }
Esempio n. 7
0
        public async Task Create_Game_Test()
        {
            // Arrange
            var expected       = typeof(CreatedResult);
            var expectedGameID = "abc";
            var game           = new MyChessGame()
            {
                Name    = "great game",
                State   = "Normal",
                Updated = DateTimeOffset.UtcNow
            };

            game.Players.White.ID = "p1";
            game.Players.Black.ID = "p2";
            game.Moves.Add(new MyChessGameMove()
            {
                Move  = "A2A3", Comment = "Cool move",
                Start = DateTimeOffset.UtcNow.AddMinutes(-1),
                End   = DateTimeOffset.UtcNow
            });

            _gamesHandlerStub.SingleGame = new MyChessGame()
            {
                ID = "abc"
            };

            var identity = new ClaimsIdentity();

            identity.AddClaim(new Claim("http://schemas.microsoft.com/identity/claims/scope", "Games.ReadWrite"));
            _securityValidatorStub.ClaimsPrincipal = new ClaimsPrincipal(identity);

            var req = HttpRequestHelper.Create("POST", body: game, query: new Dictionary <string, Microsoft.Extensions.Primitives.StringValues>());

            // Act
            var actual = await _gamesFunction.Run(req, SignalRHelper.Create(), "abc");

            // Assert
            Assert.IsType(expected, actual);
            var body       = actual as CreatedResult;
            var actualGame = body?.Value as MyChessGame;

            Assert.Equal(expectedGameID, actualGame?.ID);
        }
Esempio n. 8
0
        public async Task Create_New_Game_But_No_Opponent_Found()
        {
            // Arrange
            var expected = "2103"; // GameHandlerOpponentNotFound
            var user     = new AuthenticatedUser()
            {
                Name = "abc",
                PreferredUsername  = "******",
                UserIdentifier     = "u",
                ProviderIdentifier = "p"
            };

            var gameToCreate = new MyChessGame();

            // Act
            var actual = await _gamesHandler.CreateGameAsync(user, gameToCreate);

            // Assert
            Assert.Null(actual.Game);
            Assert.NotNull(actual.Error);
            Assert.EndsWith(expected, actual.Error?.Instance);
        }
Esempio n. 9
0
        public async Task Move_Game_To_Archive()
        {
            // Arrange
            var expectedWaitingForYou      = 0;
            var expectedWaitingForOpponent = 0;
            var expectedArchive            = 2;

            var user1 = new AuthenticatedUser()
            {
                Name = "abc",
                PreferredUsername  = "******",
                UserIdentifier     = "u1",
                ProviderIdentifier = "p1"
            };

            // Player creating the game
            await _context.UpsertAsync(TableNames.Users, new UserEntity()
            {
                PartitionKey = "u1",
                RowKey       = "p1",
                UserID       = "user123"
            });

            await _context.UpsertAsync(TableNames.UserID2User, new UserID2UserEntity()
            {
                PartitionKey   = "user123",
                RowKey         = "user123",
                UserPrimaryKey = "u1",
                UserRowKey     = "p1"
            });

            // Opponent
            await _context.UpsertAsync(TableNames.Users, new UserEntity()
            {
                PartitionKey = "u2",
                RowKey       = "p2",
                UserID       = "user456"
            });

            var game = new MyChessGame
            {
                ID = "aaa"
            };

            game.Players.White.ID = "user123";
            game.Players.Black.ID = "user456";
            var moves = new string[]
            {
                "E2E4", // White Pawn
                "A7A6", // Black Pawn
                "F1C4", // White Bishop
                "H7H6", // Black Pawn
                "D1F3", // White Queen
                "A6A5"  // Black Pawn
            };

            foreach (var m in moves)
            {
                game.Moves.Add(new MyChessGameMove()
                {
                    Move = m
                });
            }

            var compactor = new Compactor();
            var data      = compactor.Compact(game);
            await _context.UpsertAsync(TableNames.GamesWaitingForYou, new GameEntity()
            {
                PartitionKey = "user123",
                RowKey       = "aaa",
                Data         = data
            });

            // White Queen
            var finalMove = new MyChessGameMove()
            {
                Move = "F3F7"
            };

            // Act
            var actual = await _gamesHandler.AddMoveAsync(user1, "aaa", finalMove);

            // Assert
            Assert.Null(actual);
            var actualWaitingForYou      = _context.Tables[TableNames.GamesWaitingForYou].Count;
            var actualWaitingForOpponent = _context.Tables[TableNames.GamesWaitingForOpponent].Count;
            var actualWaitingArchive     = _context.Tables[TableNames.GamesArchive].Count;

            Assert.Equal(expectedWaitingForYou, actualWaitingForYou);
            Assert.Equal(expectedWaitingForOpponent, actualWaitingForOpponent);
            Assert.Equal(expectedArchive, actualWaitingArchive);
        }
Esempio n. 10
0
        public async Task Add_Move_To_Existing_Game()
        {
            // Arrange
            var expectedWaitingForYou      = 1;
            var expectedWaitingForOpponent = 1;

            var user1 = new AuthenticatedUser()
            {
                Name = "abc",
                PreferredUsername  = "******",
                UserIdentifier     = "u1",
                ProviderIdentifier = "p1"
            };

            var user2 = new AuthenticatedUser()
            {
                Name = "def",
                PreferredUsername  = "******",
                UserIdentifier     = "u2",
                ProviderIdentifier = "p2"
            };

            // Player creating the game
            await _context.UpsertAsync(TableNames.Users, new UserEntity()
            {
                PartitionKey = "u1",
                RowKey       = "p1",
                UserID       = "user123"
            });

            // Opponent
            await _context.UpsertAsync(TableNames.Users, new UserEntity()
            {
                PartitionKey = "u2",
                RowKey       = "p2",
                UserID       = "user456"
            });

            await _context.UpsertAsync(TableNames.UserID2User, new UserID2UserEntity()
            {
                PartitionKey   = "user456",
                RowKey         = "user456",
                UserPrimaryKey = "u2",
                UserRowKey     = "p2"
            });

            var gameToCreate = new MyChessGame();

            gameToCreate.Players.Black.ID = "user456";
            gameToCreate.Moves.Add(new MyChessGameMove()
            {
                Move = "A2A3"
            });
            var createResponse = await _gamesHandler.CreateGameAsync(user1, gameToCreate);

            var gameID = createResponse.Game?.ID;
            var move   = new MyChessGameMove()
            {
                Move = "A7A6"
            };

            // Act
            var actual = await _gamesHandler.AddMoveAsync(user2, gameID, move);

            // Assert
            Assert.Null(actual);
            var actualWaitingForYou      = _context.Tables[TableNames.GamesWaitingForYou].Count;
            var actualWaitingForOpponent = _context.Tables[TableNames.GamesWaitingForOpponent].Count;

            Assert.Equal(expectedWaitingForYou, actualWaitingForYou);
            Assert.Equal(expectedWaitingForOpponent, actualWaitingForOpponent);
        }
Esempio n. 11
0
        public async Task <(MyChessGame?Game, HandlerError?Error)> CreateGameAsync(AuthenticatedUser authenticatedUser, MyChessGame game)
        {
            var opponentID = game.Players.Black.ID;
            var opponent   = await GetUserByUserIDAsync(opponentID);

            if (opponent == null)
            {
                return(null, new HandlerError()
                {
                    Instance = LoggingEvents.CreateLinkToProblemDescription(LoggingEvents.GameHandlerOpponentNotFound),
                    Status = (int)HttpStatusCode.NotFound,
                    Title = "User not found",
                    Detail = "For some reason your opponent could not be found"
                });
            }

            var user = await GetOrCreateUserAsync(authenticatedUser);

            game.ID = Guid.NewGuid().ToString("D");
            game.Players.White.ID = user.UserID;
            var data = _compactor.Compact(game);

            // TODO: Validate game data
            var comment = game.Moves[0].Comment;

            await _context.UpsertAsync(TableNames.GamesWaitingForYou, new GameEntity
            {
                PartitionKey = opponentID,
                RowKey       = game.ID,
                Data         = data
            });

            await _context.UpsertAsync(TableNames.GamesWaitingForOpponent, new GameEntity
            {
                PartitionKey = user.UserID,
                RowKey       = game.ID,
                Data         = data
            });

            await _notificationHandler.SendNotificationAsync(opponentID, game.ID, comment);

            return(game, null);
        }