示例#1
0
 // Event handler when moving to a different lane is complete
 public void OnHorizontalMoveComplete()
 {
     horizontalMoveStatus = HorizontalMovement.None;
     currentLane          = targetLane;
     horizVelocity        = 0;
     transform.position   = new Vector3(targetXPos, transform.position.y, transform.position.z);
 }
示例#2
0
 void Start()
 {
     hm     = GetComponent <HorizontalMovement>();
     dash   = GetComponent <Dash>();
     jump   = GetComponent <Jump>();
     gi     = GetComponent <GravityInversion>();
     health = GetComponent <Health>();
 }
示例#3
0
 // Start is called before the first frame update
 void Start()
 {
     horScript      = player.GetComponent <HorizontalMovement>();
     touchingMoving = horScript.touchingMoving;
     movingPush     = horScript.movingPush;
     width          = GetComponent <BoxCollider2D>().bounds.size.x;
     height         = GetComponent <BoxCollider2D>().bounds.size.y;
 }
示例#4
0
 public void SetPlayerDirection(HorizontalMovement direction)
 {
     if (direction != HorizontalMovement.None && direction != _currentDirection)
     {
         _currentDirection = direction;
         Visual.Scale      = new Vector2((int)direction, 1);
     }
 }
        public IChessGame Create()
        {
            var piecesFactory   = new PiecesFactory();
            var movementHistory = new MovementHistory();
            var piecePromoter   = new PiecePromoter(movementHistory);
            var castlingMover   = new CastlingMover(movementHistory);
            var enPassantMover  = new EnPassantMover(movementHistory);
            var pieceMover      = new PieceMover(movementHistory, piecePromoter,
                                                 castlingMover, enPassantMover);
            var chessBoard = new ChessBoard(piecesFactory, pieceMover);

            List <IMovement> movements = new();
            var pawnMovement           = new PawnMovement(chessBoard);
            var enPassantMovement      = new EnPassantMovement(chessBoard);
            var kingMovement           = new KingMovement(chessBoard);
            var horizontalMovement     = new HorizontalMovement(chessBoard);
            var verticalMovement       = new VerticalMovement(chessBoard);
            var pdiagonalMovement      = new PositiveDiagonalMovement(chessBoard);
            var ndiagonalMovement      = new NegativeDiagonalMovement(chessBoard);
            var knightMovement         = new KnightMovement(chessBoard);

            movements.Add(pawnMovement);
            movements.Add(enPassantMovement);
            movements.Add(kingMovement);
            movements.Add(horizontalMovement);
            movements.Add(verticalMovement);
            movements.Add(pdiagonalMovement);
            movements.Add(ndiagonalMovement);
            movements.Add(knightMovement);
            var movementComposite = new MovementComposite(movements);

            List <IMovement> movementsWithCastling = new();
            var queensideCastlingMovement          =
                new QueensideCastlingMovement(chessBoard, movementComposite);
            var kingsideCastlingMovement =
                new KingsideCastlingMovement(chessBoard, movementComposite);

            movementsWithCastling.Add(movementComposite);
            movementsWithCastling.Add(queensideCastlingMovement);
            movementsWithCastling.Add(kingsideCastlingMovement);
            var movementCompositeWithCastling = new MovementComposite(movementsWithCastling);

            var promotionDetector = new PromotionDetector(chessBoard);

            var checkDetector = new CheckDetector(chessBoard, movementCompositeWithCastling);

            var legalMovement = new LegalMovement(chessBoard,
                                                  movementCompositeWithCastling, checkDetector);

            var moveValidator = new MoveValidator(chessBoard,
                                                  legalMovement, promotionDetector);

            var gameFinishedDetector = new GameFinishedDetector(checkDetector,
                                                                legalMovement);

            return(new ChessGame(chessBoard, moveValidator,
                                 promotionDetector, gameFinishedDetector, legalMovement));
        }
        private void Awake()
        {
            abilityManager     = GetComponent <AbilityManager>();
            horizontalMovement = GetComponent <HorizontalMovement>();
            jump = GetComponent <Jump>();
            dash = GetComponent <Dash>();

            RegisterInputHandlers();
        }
示例#7
0
 void Update()
 {
     ApostleCollisionHandler.StartCollisions(HorizontalMovement.HorizontalMovementState,
                                             ApostleStatusVariables.facingDirection);
     HorizontalMovement.StartMovement();
     HorizontalMovement.PressMovementHandler();
     VerticalMovement.StartMovement();
     VerticalMovement.PressMovementHandler();
 }
 private void Start()
 {
     horizontalMovement = GetComponent <HorizontalMovement>();
     if (changeDirOnHorizontalCollision)
     {
         physics.Collisions.Left.RegisterCallback(OnHorizontalCollision);
         physics.Collisions.Right.RegisterCallback(OnHorizontalCollision);
     }
 }
示例#9
0
 // Move the player to the right lane
 public void MoveRight()
 {
     if ((currentLane < numLanes) && horizontalMoveStatus != HorizontalMovement.Right)
     {
         horizontalMoveStatus = HorizontalMovement.Right;
         horizVelocity        = horizSpeed;
         targetLane           = targetLane + 1;
         targetXPos           = gameController.GetLaneCenterXPos(targetLane);
     }
 }
    // Start is called before the first frame update
    void Start()
    {
        _horizontalMovement = GetComponent <HorizontalMovement>();

        leftScale = transform.localScale.x;
        if (OriginalDirection == Direction.RIGHT)
        {
            leftScale *= -1;
        }
    }
示例#11
0
 private void Awake()
 {
     comboManager       = GetComponentInParent <ComboManager>();
     audioSource        = GetComponent <AudioSource>();
     gameOver           = GetComponent <GameOver>();
     death              = GetComponentInParent <Death>();
     horizontalMovement = GetComponent <HorizontalMovement>();
     stateManager       = GetComponentInParent <PlayerStateManager>();
     playerGravity      = GetComponent <PlayerGravity>();
 }
示例#12
0
 // Move the player to the left lane
 public void MoveLeft()
 {
     if ((currentLane > 1) && horizontalMoveStatus != HorizontalMovement.Left)
     {
         horizontalMoveStatus = HorizontalMovement.Left;
         horizVelocity        = -horizSpeed;
         targetLane           = targetLane - 1;
         targetXPos           = gameController.GetLaneCenterXPos(targetLane);
     }
 }
示例#13
0
 protected override void Initialize()
 {
     physics.Collisions.Bottom.RegisterCallback(OnGroundedChange);
     wallStick          = GetComponent <WallStick>();
     dash               = GetComponent <Dash>();
     horizontalMovement = GetComponent <HorizontalMovement>();
     faceable           = GetComponent <IFaceable>();
     if (wallStick != null)
     {
         wallStick.OnStart(OnWallStickStart);
     }
 }
示例#14
0
        private void InitializeInputs()
        {
            Inputs.Player.Jump.performed       += _ => PlayerInputs.JumpInput = true;
            Inputs.Player.CancelJump.performed += _ => PlayerInputs.JumpInput = false;

            Inputs.Player.Dash.performed += _ => PlayerInputs.DashInput = true;
            Inputs.Player.Dash.canceled  += _ => PlayerInputs.DashInput = false;

            Inputs.Player.CancelJump.performed += (ctx) =>
            {
                PlayerInputs.CanWallJump     = true;
                PlayerInputs.JumpInputBuffer = 0;
            };

            HorizontalMovement.Subscribe(HorizontalState.WallSticked, OnStateEnter, () => PlayerInputs.WallStickBuffer = 0);
            HorizontalMovement.Subscribe(HorizontalState.WallSticked, OnUpdate, () =>
            {
                var wallDirection = Collisions.Left ? -1 : 1;

                // Sticks the player to wall for a short amount of time allowing him to perform easier wall jump
                var isLeavingWall            = PlayerInputs.RunInput != 0 && Mathf.Sign(PlayerInputs.RunInput) != wallDirection;
                PlayerInputs.WallStickBuffer = isLeavingWall ? PlayerInputs.WallStickBuffer + Time.deltaTime : 0;
            });

            VerticalMovement.Subscribe(VerticalState.Grounded, OnStateEnter, () =>
            {
                PlayerInputs.CanWallJump = false;
                PlayerInputs.CanDash     = true;
            });
            VerticalMovement.Subscribe(VerticalState.Falling, OnUpdate, () => PlayerInputs.FallBuffer   += Time.deltaTime);
            VerticalMovement.Subscribe(VerticalState.Falling, OnStateExit, () => PlayerInputs.FallBuffer = 0);

            Dash.Subscribe(DashState.Rest, OnStateEnter, () =>
            {
                HorizontalMovement.IsLocked = false;
                VerticalMovement.IsLocked   = false;
            });
            Dash.Subscribe(DashState.Rest, OnStateExit, () => PlayerInputs.CanDash = false);
            Dash.Subscribe(DashState.Casting, OnStateEnter, () =>
            {
                HorizontalMovement.IsLocked = true;
                VerticalMovement.IsLocked   = true;
            });
            Dash.Subscribe(DashState.Casting, OnUpdate, () => PlayerInputs.DashDirection = Inputs.Player.DashDirection.ReadValue <Vector2>());
            Dash.Subscribe(DashState.Recovering, OnStateEnter, () =>
            {
                VerticalMovement.IsLocked     = false;
                HorizontalMovement.IsLocked   = false;
                PlayerInputs.IsInDashRecovery = true;
            });
            Dash.Subscribe(DashState.Recovering, OnStateExit, () => PlayerInputs.IsInDashRecovery = false);
        }
示例#15
0
 void Update()
 {
     PlayerCollisionHandler.StartCollisions(HorizontalMovement.HorizontalMovementState,
                                            PlayerStatusVariables.facingDirection);
     HorizontalMovement.StartMovement();
     HorizontalMovement.PressMovementHandler();
     VerticalMovement.StartMovement();
     VerticalMovement.PressMovementHandler();
     MiscellaneousMovement.StartMovement();
     MiscellaneousMovement.PressMovementHandler();
     CombatMovement.StartMovement();
     CombatMovement.PressMovementHandler();
 }
示例#16
0
        void RotateGravity(HorizontalMovement direction)
        {
            if (direction == HorizontalMovement.Left)
            {
                _defaultGravityAngle -= 90;
            }
            else if (direction == HorizontalMovement.Right)
            {
                _defaultGravityAngle += 90;
            }

            // normalize between 0 and 360
            _defaultGravityAngle = (_defaultGravityAngle % 360 + 360) % 360;
        }
示例#17
0
    private void Start()
    {
        scooter_rb               = scooter.GetComponent <Rigidbody>();
        rag                      = GetComponentInChildren <Ragdoll>();
        movement                 = GetComponent <Movement>();
        movement_M               = GetComponent <Movement_Mobile>();
        groundCheck              = GetComponentInChildren <GroundCheck>();
        stateManager             = GetComponent <PlayerStateManager>();
        forwardMovement          = GetComponent <ForwardMovement>();
        horizontalMovement       = GetComponent <HorizontalMovement>();
        horizontalMovementMobile = GetComponent <HorizontalMovement_Mobile>();
        jump                     = GetComponent <Jump>();
        jumpMobile               = GetComponent <Jump_Mobile>();

        gameOver = gameOverObject.GetComponent <GameOver>();
    }
示例#18
0
    private static bool AudioIsPlaying; //usada na corotina pra bloquear vários lemming emitindo som ao mesmo tempo

    // Start is called before the first frame update
    void Start()
    {
        rd = GetComponent <Rigidbody2D>();
        //capsule collider?
        coll2d = GetComponent <CapsuleCollider2D>();
        hm     = GetComponent <HorizontalMovement>();
        anim   = GetComponent <Animator>();


        //adds try to jump function to press callback
        //function TryToJump will be called every time "button is pressed", for all platforms
        PlayerInput.OnPress += TryToJump;
        //Debug.Log("Jumps" + PlayerInput.OnPress.GetInvocationList().GetLength(0));

        AudioIsPlaying = false;
    }
示例#19
0
文件: Unit.cs 项目: gjrfytn/MLG360
        private Vector2 PredictPos(Unit unit, float dtime, HorizontalMovement horizontalMovement, bool willJumpOffPlatformOrLadder) //TODO workaround
        {
            float dx;

            switch (horizontalMovement)
            {
            case HorizontalMovement.None:
                dx = 0;
                break;

            case HorizontalMovement.Left:
                dx = -unit._RunSpeed * dtime;
                break;

            case HorizontalMovement.Right:
                dx = unit._RunSpeed * dtime;
                break;

            default: throw new System.ArgumentOutOfRangeException(nameof(horizontalMovement));
            }

            var dy = unit.VerticalDynamic.CalculateDPos(dtime);

            if (dy == 0)
            {
                return(unit.Pos + dx * Vector2.UnitX);
            }

            var pos = unit.Pos + new Vector2(dx, dy);

            var solidTilesAbovePos = _Environment.Tiles
                                     .Where(t => (t.IsWall || t.Type == TileType.JumpPad || (t.Type == TileType.Platform || t.Type == TileType.Ladder) && !willJumpOffPlatformOrLadder) &&
                                            t.Pos.Y < unit.Pos.Y &&
                                            t.Top.Y >= pos.Y &&
                                            t.InXArea(pos))
                                     .ToArray();

            if (solidTilesAbovePos.Any())
            {
                return(new Vector2(unit.Pos.X + dx, solidTilesAbovePos.OrderByDescending(t => t.Top.Y).First().Top.Y));
            }

            // TODO Horizontal prediction.

            return(pos);
        }
示例#20
0
        private void HandleMovements()
        {
            float horizontalVelocity;
            float verticalVelocity;

            float LimitSpeed(float speed)
            {
                return(Mathf.Min(Mathf.Max(speed, -MaxRunSpeed), MaxRunSpeed));
            }

            _inputHorizontalDirection = (HorizontalMovement)Convert.ToInt32(Input.IsActionPressed(Inputs.MoveRight)) -
                                        Convert.ToInt32(Input.IsActionPressed(Inputs.MoveLeft));
            _inputVerticalDirection = (VerticalMovement)Convert.ToInt32(Input.IsActionPressed(Inputs.MoveDown)) -
                                      Convert.ToInt32(Input.IsActionPressed(Inputs.MoveUp));

            if (_inputHorizontalDirection == HorizontalMovement.Left && Velocity.x > -MaxRunSpeed)
            {
                horizontalVelocity = LimitSpeed(Velocity.x - Acceleration);
                SetPlayerDirection(HorizontalMovement.Left);
            }
            else if (_inputHorizontalDirection == HorizontalMovement.Right && Velocity.x < MaxRunSpeed)
            {
                horizontalVelocity = LimitSpeed(Velocity.x + Acceleration);
                SetPlayerDirection(HorizontalMovement.Right);
            }
            else
            {
                horizontalVelocity = Mathf.Abs(Velocity.x) <= 1 ? 0 : Mathf.Lerp(Velocity.x, 0, Inertia);
            }

            if (_inputVerticalDirection == VerticalMovement.Up && Velocity.y > -MaxRunSpeed)
            {
                verticalVelocity = LimitSpeed(Velocity.y - Acceleration);
            }
            else if (_inputVerticalDirection == VerticalMovement.Down && Velocity.y < MaxRunSpeed)
            {
                verticalVelocity = LimitSpeed(Velocity.y + Acceleration);
            }
            else
            {
                verticalVelocity = Mathf.Abs(Velocity.y) <= 1 ? 0 : Mathf.Lerp(Velocity.y, 0, Inertia);
            }

            Velocity = new Vector2(horizontalVelocity, verticalVelocity);
        }
示例#21
0
文件: Unit.cs 项目: gjrfytn/MLG360
 public Unit(int id, int playerId, Vector2 pos, Weapon weapon, Vector2 size, float runSpeed, float jumpSpeed, float jumpTimeLeft, float maxJumpTime, VerticalDynamic verticalDynamic, float health, float maxHealth, HorizontalMovement currentHorizontalMovement, IEnvironment environment, IScoretable scoretable) :
     base(pos, size)
 {
     _Id                        = id;
     PlayerId                   = playerId;
     _Weapon                    = weapon;
     _Size                      = size;
     _RunSpeed                  = runSpeed;
     _JumpSpeed                 = jumpSpeed;
     _JumpTimeLeft              = jumpTimeLeft;
     _MaxJumpTime               = maxJumpTime;
     VerticalDynamic            = verticalDynamic;
     Health                     = health;
     MaxHealth                  = maxHealth;
     _CurrentHorizontalMovement = currentHorizontalMovement;
     _Environment               = environment;
     _Scoretable                = scoretable;
 }
示例#22
0
    // Start is called before the first frame update
    void Start()
    {
        _boxCollider2D      = GetComponent <BoxCollider2D>();
        _horizontalMovement = GetComponent <HorizontalMovement>();
        _rigidbody2D        = GetComponent <Rigidbody2D>();

        // Disables horizontal movement and rigidbody for now
        _horizontalMovement.enabled = false;
        _rigidbody2D.bodyType       = RigidbodyType2D.Static;

        // When fully left, fall
        _horizontalMovement.TurnRightEvent = () =>
        {
            _horizontalMovement.enabled       = false;
            _rigidbody2D.bodyType             = RigidbodyType2D.Dynamic;
            GetComponent <Elevator>().enabled = false;
        };
    }
示例#23
0
        private void SetHorizontalMovementAloof()
        {
            // Map raw movement vector into our 2D movement space:
            if (HorizontalMovement.Y > 0.0f) // Positive Y is special because we can move faster in that direction.
            {
                double rawMovementTheta    = Math.Atan2(HorizontalMovement.Y, HorizontalMovement.X);
                float  maxRadius           = (float)(GetMaxFwdMoveLength(rawMovementTheta));
                float  totalMovementLength = HorizontalMovement.Length() * maxRadius;
                // Clamp the movement:
                Controller.HorizontalMotionConstraint.SpeedScale = 0.5f * Math.Min(maxRadius, totalMovementLength);
            }
            else
            {
                // Clamp the movement:
                Controller.HorizontalMotionConstraint.SpeedScale = 0.5f * Math.Min(1.0f, HorizontalMovement.Length());
            }

            Controller.HorizontalMotionConstraint.MovementDirection = BepuConverter.Convert(HorizontalMovement);
        }
示例#24
0
    void Start()
    {
        Initializer initializer = GameObject.FindGameObjectWithTag("Initializer").GetComponent <Initializer>();

        actionController   = initializer.actionController;
        horizontalMovement = initializer.horizontalMovement;

        foreach (Text dateT in dateText)
        {
            dateT.text = DateTime.Now.ToString("dddd") + ", " + DateTime.Now.Day + " " + DateTime.Now.ToString("MMMM");
        }

        float centreOfScreenX   = Screen.width / 2;
        float centreOfScreenY   = Screen.height / 2;
        float defaultSidePosX   = Screen.width * 2f;
        float defaultBottomPosY = -Screen.height;

        posPopupHidden = new Vector2(defaultSidePosX, centreOfScreenY);
        posPageHidden  = new Vector2(centreOfScreenX, defaultBottomPosY);
        posCentre      = new Vector2(centreOfScreenX, centreOfScreenY);

        setPosPopup = posPopupHidden;
        setPosPage  = posPageHidden;

        foreach (GameObject page in allPages)
        {
            //Enable all gameobjects at the start
            if (!page.activeSelf)
            {
                page.SetActive(true);
            }

            page.transform.localPosition = new Vector2(page.transform.localPosition.x, 0f);
        }

        StartCoroutine(HidePagesFirstFrame());
        UpdateProductivity();
        UpdatePriorityCount();
        SaveAllContent();

        SetNotifications();
    }
示例#25
0
 // Use this for initialization
 void Start()
 {
     bodyAnim = GetComponent <Animator> ();
     if (bodyAnim == null)
     {
         Debug.Log("Failed to get Animator component in Robot");
     }
     headAnim = head.GetComponent <Animator> ();
     if (headAnim == null)
     {
         Debug.Log("Failed to get Animator in component Head");
     }
     circleCollider = GetComponent <CircleCollider2D>();
     if (circleCollider == null)
     {
         Debug.Log("Failed to get CircleCollider2D in component Robot");
     }
     movementScript = GetComponent <HorizontalMovement> ();
     if (movementScript == null)
     {
         Debug.Log("Failed to get HorizontalMovement in component Robot");
     }
 }
示例#26
0
    private Vector3 offset;         //Private variable to store the offset distance between the player and camera

    // Use this for initialization
    void Start()
    {
        gameManagement   = GameObject.Find("EndOfLevel").GetComponent <GameManagementScript>();
        horScript        = player.GetComponent <HorizontalMovement>();
        firstEnd         = horScript.firstEnd;
        onInit           = true;
        startDead        = true;
        deathScript      = playBoth.GetComponent <DeathScript>();
        firstStopScript  = firstStop.GetComponent <cameraEnd>();
        secondStopScript = secondStop.GetComponent <cameraEnd>();
        //Calculate and store the offset value by getting the distance between the player's position and camera's position.
        offset = transform.position - player.transform.position;
        cam    = GetComponent <Camera>();
        //the screen position of the two player characters
        playerCam  = cam.WorldToScreenPoint(player.transform.position);
        player2Cam = cam.WorldToScreenPoint(player2.transform.position);
        playerAvg  = (playerCam.x + player2Cam.x) / 2;
        //the screen height
        height             = cam.pixelHeight;
        width              = cam.pixelWidth;
        p1width            = player.GetComponent <BoxCollider2D>().bounds.size.x;
        initCam            = (cam.ScreenToWorldPoint(new Vector3(playerAvg + width / 2, height / 2)));
        initCam           -= new Vector3(p1width * 3 / 4, 0);
        transform.position = initCam;
        camLeft            = new Vector3(0, 0, 0);
        camRight           = new Vector3(0, 0, 0);
        camLeft            = cam.ScreenToWorldPoint(transform.position);
        Vector3 widThing = new Vector3(width, 0, 0);

        widThing       = cam.ScreenToWorldPoint(widThing);
        camRight       = transform.position + widThing;
        curCamEnd      = firstStopScript.cameraHere;
        switchStop     = false;
        freezePlayers  = false;
        switchToSecond = false;
    }
示例#27
0
        public void QueenCanCaptureEnemiesButCantJumpThroughThem()
        {
            //BQ - black queen
            //PM - possible move
            //EP - enemy piece
            //7
            //6
            //5          EP PM PM BQ PM
            //4
            //3
            //2
            //1
            //0
            //  0  1  2  3  4  5  6  7
            var boardMock = new Mock <IChessBoard>(MockBehavior.Strict);
            var queenMock = new Mock <IReadOnlyChessPiece>(MockBehavior.Strict);

            var queenPosition = new Position(6, 5);
            var enemyPosition = new Position(3, 5);

            var availableFinishPosition1 = new Position(4, 5);
            var availableFinishPosition2 = new Position(5, 5);
            var availableFinishPosition3 = new Position(7, 5);

            var availableFinishPositions = new List <Position>()
            {
                availableFinishPosition1, availableFinishPosition2,
                availableFinishPosition3
            };

            queenMock
            .SetupGet(p => p.Color)
            .Returns(ChessColor.Black);
            queenMock
            .SetupGet(p => p.PieceType)
            .Returns(ChessPieceType.Queen);
            queenMock
            .SetupGet(p => p.Position)
            .Returns(queenPosition);
            queenMock
            .SetupGet(p => p.HasMoved)
            .Returns(true);

            boardMock
            .Setup(b => b.IsPositionTaken(enemyPosition))
            .Returns(true);
            boardMock
            .Setup(b => b.IsPositionTaken(It.IsIn <Position>(availableFinishPositions)))
            .Returns(false);
            boardMock
            .Setup(b => b.IsEnemyOnPosition(enemyPosition, ChessColor.White))
            .Returns(true);
            boardMock
            .Setup(b => b.IsEnemyOnPosition(It.IsIn <Position>(availableFinishPositions),
                                            ChessColor.White))
            .Returns(false);

            var movement       = new HorizontalMovement(boardMock.Object);
            var availableMoves = movement.GetAvailableMoves(queenMock.Object);

            Assert.AreEqual(4, availableMoves.Count());
            Assert.IsTrue(availableMoves.All(m => m.StartingPosition == queenPosition));

            var finishedPositions = availableMoves
                                    .Select(m => m.FinishedPosition)
                                    .ToList();

            Assert.Contains(availableFinishPosition1, finishedPositions);
            Assert.Contains(availableFinishPosition2, finishedPositions);
            Assert.Contains(availableFinishPosition3, finishedPositions);
            Assert.Contains(enemyPosition, finishedPositions);
        }
示例#28
0
        public void QueenCantJumpThroughFriendlyPieces()
        {
            //WQ - white queen
            //PM - possible move
            //WP - white piece
            //7
            //6
            //5
            //4
            //3    WP PM WQ WP
            //2
            //1
            //0
            //  0  1  2  3  4  5  6  7
            var boardMock = new Mock <IChessBoard>(MockBehavior.Strict);
            var queenMock = new Mock <IReadOnlyChessPiece>(MockBehavior.Strict);

            var queenPosition = new Position(3, 3);
            var pawn1Position = new Position(1, 3);
            var pawn2Position = new Position(4, 3);

            var availableFinishPosition = new Position(2, 3);

            queenMock
            .SetupGet(p => p.Color)
            .Returns(ChessColor.White);
            queenMock
            .SetupGet(p => p.PieceType)
            .Returns(ChessPieceType.Queen);
            queenMock
            .SetupGet(p => p.Position)
            .Returns(queenPosition);
            queenMock
            .SetupGet(p => p.HasMoved)
            .Returns(true);

            boardMock
            .Setup(b => b.IsPositionTaken(pawn1Position))
            .Returns(true);
            boardMock
            .Setup(b => b.IsPositionTaken(pawn2Position))
            .Returns(true);
            boardMock
            .Setup(b => b.IsPositionTaken(availableFinishPosition))
            .Returns(false);
            boardMock
            .Setup(b => b.IsEnemyOnPosition(It.IsAny <Position>(), ChessColor.Black))
            .Returns(false);

            var movement       = new HorizontalMovement(boardMock.Object);
            var availableMoves = movement.GetAvailableMoves(queenMock.Object);

            Assert.AreEqual(1, availableMoves.Count());
            Assert.IsTrue(availableMoves.All(m => m.StartingPosition == queenPosition));

            var finishedPositions = availableMoves
                                    .Select(m => m.FinishedPosition)
                                    .ToList();

            Assert.Contains(availableFinishPosition, finishedPositions);
        }
示例#29
0
        public void RookCanMoveHorizontally()
        {
            //WR - white rook
            //PM - possible move
            //7
            //6
            //5
            //4
            //3
            //2
            //1 PM WR PM PM PM PM PM PM
            //0
            //  0  1  2  3  4  5  6  7
            var boardMock = new Mock <IChessBoard>(MockBehavior.Strict);
            var rookMock  = new Mock <IReadOnlyChessPiece>(MockBehavior.Strict);

            var rookPosition = new Position(1, 1);

            var availableFinishPosition01 = new Position(0, 1);
            var availableFinishPosition02 = new Position(2, 1);
            var availableFinishPosition03 = new Position(3, 1);
            var availableFinishPosition04 = new Position(4, 1);
            var availableFinishPosition05 = new Position(5, 1);
            var availableFinishPosition06 = new Position(6, 1);
            var availableFinishPosition07 = new Position(7, 1);

            rookMock
            .SetupGet(p => p.Color)
            .Returns(ChessColor.White);
            rookMock
            .SetupGet(p => p.PieceType)
            .Returns(ChessPieceType.Rook);
            rookMock
            .SetupGet(p => p.Position)
            .Returns(rookPosition);
            rookMock
            .SetupGet(p => p.HasMoved)
            .Returns(true);

            boardMock
            .Setup(b => b.IsPositionTaken(It.IsAny <Position>()))
            .Returns(false);
            boardMock
            .Setup(b => b.IsEnemyOnPosition(It.IsAny <Position>(), It.IsAny <ChessColor>()))
            .Returns(false);

            var movement       = new HorizontalMovement(boardMock.Object);
            var availableMoves = movement.GetAvailableMoves(rookMock.Object);

            Assert.AreEqual(7, availableMoves.Count());
            Assert.IsTrue(availableMoves.All(m => m.StartingPosition == rookPosition));

            var finishedPositions = availableMoves
                                    .Select(m => m.FinishedPosition)
                                    .ToList();

            Assert.Contains(availableFinishPosition01, finishedPositions);
            Assert.Contains(availableFinishPosition02, finishedPositions);
            Assert.Contains(availableFinishPosition03, finishedPositions);
            Assert.Contains(availableFinishPosition04, finishedPositions);
            Assert.Contains(availableFinishPosition05, finishedPositions);
            Assert.Contains(availableFinishPosition06, finishedPositions);
            Assert.Contains(availableFinishPosition07, finishedPositions);
        }
示例#30
0
    public List <ItemMovementDetails> MoveHorizontal(HorizontalMovement horizontalMovement)
    {
        ResetWasJustDuplicatedValues();

        var movementDetails = new List <ItemMovementDetails>();

        //the relative column we will compare with
        //if swipe is left, we will compare with the previous one (the -1 position)
        int relativeColumn = horizontalMovement == HorizontalMovement.Left ? -1 : 1;
        //to get the column indexes, to do the loop below
        var columnNumbers = Enumerable.Range(0, Globals.Columns);

        //for left swipe, we will traverse the columns in the order 0,1,2,3
        //for right swipe, we want the reverse order
        if (horizontalMovement == HorizontalMovement.Right)
        {
            columnNumbers = columnNumbers.Reverse();
        }

        for (int row = Globals.Rows - 1; row >= 0; row--)
        {   //we're doing foreach instead of for in order to traverse the columns
            //in the appropriate order
            foreach (int column in columnNumbers)
            {
                //if the item is null, continue checking for non-null items
                if (matrix[row, column] == null)
                {
                    continue;
                }

                //since we arrived here, we have a non-null item
                //first we check if this item has the same value as the previous one
                //previous one's position depends on whether the relativeColumn variable is -1 or 1, depending on the swipe
                ItemMovementDetails imd = AreTheseTwoItemsSame(row, column, row, column + relativeColumn);
                if (imd != null)
                {
                    //items have the same value, so they will be "merged"
                    movementDetails.Add(imd);
                    //continue the loop
                    //the new duplicated item may be moved on a subsequent loop
                    continue;
                }

                //matrix[row,column] is the first not null item
                //move it to the first null item space
                int columnFirstNullItem = -1;

                //again, this is to help on the foreach loop that follows
                //for a left swipe, we want to check the columns 0 to [column-1]
                //for a right swipe, we want to check columns [Globals.Columns-1] to column
                int numberOfItemsToTake = horizontalMovement == HorizontalMovement.Left
                ? column : Globals.Columns - column;

                bool emptyItemFound = false;

                //keeping it for documentation/clarity
                //this for loop would run for a left swipe ;)
                //for (columnFirstNullItem = 0; columnFirstNullItem < column; columnFirstNullItem++)
                foreach (var tempColumnFirstNullItem in columnNumbers.Take(numberOfItemsToTake))
                {
                    //keep a copy of the index on the potential null item position
                    columnFirstNullItem = tempColumnFirstNullItem;
                    if (matrix[row, columnFirstNullItem] == null)
                    {
                        emptyItemFound = true;
                        break;//exit the loop
                    }
                }

                //we did not find an empty/null item, so we cannot move current item
                if (!emptyItemFound)
                {
                    continue;
                }


                ItemMovementDetails newImd =
                    MoveItemToNullPositionAndCheckIfSameWithNextOne
                        (row, row, row, column, columnFirstNullItem, columnFirstNullItem + relativeColumn);

                movementDetails.Add(newImd);
            }
        }
        return(movementDetails);
    }
示例#31
0
    public List<ItemMovementDetails> MoveHorizontal(HorizontalMovement horizontalMovement)
    {
        ResetWasJustDuplicatedValues();

        var movementDetails = new List<ItemMovementDetails>();

        //the relative column we will compare with
        //if swipe is left, we will compare with the previous one (the -1 position)
        int relativeColumn = horizontalMovement == HorizontalMovement.Left ? -1 : 1;
        //to get the column indexes, to do the loop below
        var columnNumbers = Enumerable.Range(0, Globals.Columns);

        //for left swipe, we will traverse the columns in the order 0,1,2,3
        //for right swipe, we want the reverse order
        if (horizontalMovement == HorizontalMovement.Right)
        {
            columnNumbers = columnNumbers.Reverse();
        }

        for (int row = Globals.Rows - 1; row >= 0; row--)
        {   //we're doing foreach instead of for in order to traverse the columns
            //in the appropriate order
            foreach (int column in columnNumbers)
            {
                //if the item is null, continue checking for non-null items
                if (matrix[row, column] == null) continue;

                //since we arrived here, we have a non-null item
                //first we check if this item has the same value as the previous one
                //previous one's position depends on whether the relativeColumn variable is -1 or 1, depending on the swipe
                ItemMovementDetails imd = AreTheseTwoItemsSame(row, column, row, column + relativeColumn);
                if (imd != null)
                {
                    //items have the same value, so they will be "merged"
                    movementDetails.Add(imd);
                    //continue the loop
                    //the new duplicated item may be moved on a subsequent loop
                    continue;
                }

                //matrix[row,column] is the first not null item
                //move it to the first null item space
                int columnFirstNullItem = -1;

                //again, this is to help on the foreach loop that follows
                //for a left swipe, we want to check the columns 0 to [column-1]
                //for a right swipe, we want to check columns [Globals.Columns-1] to column
                int numberOfItemsToTake = horizontalMovement == HorizontalMovement.Left
                ? column : Globals.Columns - column;

                bool emptyItemFound = false;

                //keeping it for documentation/clarity
                //this for loop would run for a left swipe ;)
                //for (columnFirstNullItem = 0; columnFirstNullItem < column; columnFirstNullItem++)
                foreach (var tempColumnFirstNullItem in columnNumbers.Take(numberOfItemsToTake))
                {
                    //keep a copy of the index on the potential null item position
                    columnFirstNullItem = tempColumnFirstNullItem;
                    if (matrix[row, columnFirstNullItem] == null)
                    {
                        emptyItemFound = true;
                        break;//exit the loop
                    }
                }

                //we did not find an empty/null item, so we cannot move current item
                if (!emptyItemFound)
                {
                    continue;
                }


                ItemMovementDetails newImd =
                MoveItemToNullPositionAndCheckIfSameWithNextOne
                (row, row, row, column, columnFirstNullItem, columnFirstNullItem + relativeColumn);

                movementDetails.Add(newImd);


            }
        }
        return movementDetails;
    }