示例#1
0
    public Match3Tile SpawnTileAt(Match3BoardPiece boardPiece, BoardCoord boardPos, GameObject tilePrefab)
    {
        // Destroy previous tile from board piece (if present).
        if (boardPiece.EditorTile != null)
        {
            // Remove the first spawn rule entry for this tile if it corresponds to its type.
            SetBoardPieceSpawnRuleForTile(boardPiece, boardPiece.EditorTile, true);
            GameObject.DestroyImmediate(boardPiece.EditorTile.gameObject);
        }

        GameObject newTileGO = PrefabUtility.InstantiatePrefab(tilePrefab) as GameObject;

        PrefabUtility.DisconnectPrefabInstance(newTileGO);

        Match3Tile newTile = newTileGO.GetComponent <Match3Tile>();

        newTile.name                    = string.Format("[{0},{1}] {2}", boardPos.row, boardPos.col, newTile.name);
        newTile.transform.parent        = boardRenderer.transform;
        newTile.transform.localPosition = boardPiece.transform.localPosition - boardRenderer.transform.forward * 2f;
        boardPiece.EditorTile           = newTile;

        // Add the first spawn rule entry for with this tile's type.
        SetBoardPieceSpawnRuleForTile(boardPiece, boardPiece.EditorTile);

        return(newTile);
    }
示例#2
0
    public override List <BoardCoord> CalculateTemplateMoves()
    {
        List <BoardCoord> moves = new List <BoardCoord>();
        int xModifier, yModifier;

        for (int i = 0; i <= 7; i++)
        {
            chessGame.GetMoveDirectionModifiers(this, (MoveDirection)i, out xModifier, out yModifier);
            BoardCoord coord = GetBoardPosition() + new BoardCoord(xModifier, yModifier);

            while (chessGame.board.ContainsCoord(coord))
            {
                if (chessGame.board.GetCoordInfo(coord).occupier != null)
                {
                    BoardCoord grasshopperMove = chessGame.TryGetSpecificMove(this, coord + new BoardCoord(xModifier, yModifier));
                    if (grasshopperMove != BoardCoord.NULL)
                    {
                        moves.Add(grasshopperMove);
                    }
                    break;
                }
                coord.x += xModifier;
                coord.y += yModifier;
            }
        }
        return(moves);
    }
示例#3
0
        /// <summary>
        /// Gets all possible check threats against the piece-to-check. This should vary between game-modes
        /// that involve pieces that don't move directionally.
        /// </summary>
        /// <param name="pieceToCheck">Piece to check (usually the current or opposing royal piece).</param>
        /// <returns>A list of chess pieces that can check the piece-to-check.</returns>
        protected virtual List <ChessPiece> GetAllPossibleCheckThreats(ChessPiece pieceToCheck)
        {
            List <ChessPiece> possibleCheckThreats = new List <ChessPiece>();

            for (int i = (int)MoveDirection.Up; i <= (int)MoveDirection.DownRight; i++)
            {
                int xModifier, yModifier;
                GetMoveDirectionModifiers(pieceToCheck, (MoveDirection)i, out xModifier, out yModifier);
                BoardCoord coord = pieceToCheck.GetBoardPosition() + new BoardCoord(xModifier, yModifier);

                while (board.ContainsCoord(coord))
                {
                    if (IsThreat(pieceToCheck, coord))
                    {
                        possibleCheckThreats.Add(board.GetCoordInfo(coord).occupier);
                    }
                    coord.x += xModifier;
                    coord.y += yModifier;
                }
            }

            foreach (Knight knight in GetPiecesOfType <Knight>())
            {
                if (IsThreat(pieceToCheck, knight.GetBoardPosition()))
                {
                    possibleCheckThreats.Add(knight);
                }
            }

            return(possibleCheckThreats);
        }
示例#4
0
    public Vector2 PositionForBoardCoord(BoardCoord boardCoord)
    {
        Vector2 pos = new Vector2((boardCoord.col * boardSquareSize.width) + (boardSquareSize.width * 0.5f), (boardCoord.row * boardSquareSize.height) + (boardSquareSize.height * 0.5f));

        pos += boardStartOffset;
        return(pos);
    }
示例#5
0
 public override bool MovePiece(ChessPiece mover, BoardCoord destination)
 {
     // Try make the move
     if (MakeMove(mover, destination))
     {
         // Check castling moves
         if (mover is King && mover.MoveCount == 1)
         {
             if (mover.GetBoardPosition() == new BoardCoord(1, WHITE_BACKROW))
             {
                 aSideWhiteRook = (Rook)PerformCastle(aSideWhiteRook, new BoardCoord(2, WHITE_BACKROW));
             }
             else if (mover.GetBoardPosition() == new BoardCoord(2, BLACK_BACKROW))
             {
                 hSideBlackRook = (Rook)PerformCastle(hSideBlackRook, new BoardCoord(1, BLACK_BACKROW));
             }
         }
         else if (mover is Pawn)
         {
             ChessPiece promotedPiece = CheckPawnPromotion((Pawn)mover);
             if (promotedPiece != null)
             {
                 mover = promotedPiece;
             }
         }
         return(true);
     }
     return(false);
 }
示例#6
0
    public ArrayList FillGapsWithNewTiles(LevelData level, GameManager gameManager)
    {
        // This array will hold all the new tiles, split into ordered columns.
        // We use this for animating the drop down after we change the data model here.
        ArrayList columns = new ArrayList();

        for (int col = 0; col < boardSize.numCols; col++)
        {
            ArrayList column = new ArrayList();
            columns.Add(column);

            // Scan from bottom to top looking for any remaining board squares with no tile
            for (int row = 0; row < boardSize.numRows; row++)
            {
                BoardCoord boardCoord = new BoardCoord(col, row);

                if (CanHaveTileAtCoord(boardCoord) && !IsTileAtCoord(boardCoord))
                {
                    // Put in the new tile at this coord
                    Tile newTile = CreateTile(boardCoord, level.GetRandomTileType(), gameManager);
                    tiles[col, row] = newTile;
                    column.Add(newTile);

                    // Set the appearance so it is ready to drop in to place
                    newTile.PrepareForNewDrop();
                    newTile.transform.localPosition = PositionForBoardCoord(new BoardCoord(col, boardSize.numRows + 1));
                }
            }
        }

        return(columns);
    }
示例#7
0
        public override List <BoardCoord> CalculateAvailableMoves(ChessPiece mover)
        {
            BoardCoord[]      templateMoves  = mover.CalculateTemplateMoves().ToArray();
            List <BoardCoord> availableMoves = new List <BoardCoord>(templateMoves.Length);

            for (int i = 0; i < templateMoves.Length; i++)
            {
                if (IsPieceInCheckAfterThisMove(currentRoyalPiece, mover, templateMoves[i]) == false)
                {
                    availableMoves.Add(templateMoves[i]);
                }
            }

            if (mover is King && mover.MoveCount == 0)
            {
                availableMoves.AddRange(TryAddAvailableCastleMoves(mover));
            }
            else if (mover is Pawn)
            {
                BoardCoord enPassantMove = TryAddAvailableEnPassantMove((Pawn)mover);
                if (enPassantMove != BoardCoord.NULL)
                {
                    availableMoves.Add(enPassantMove);
                }
            }

            return(availableMoves);
        }
示例#8
0
        public override bool MovePiece(ChessPiece mover, BoardCoord destination)
        {
            BoardCoord oldPos = mover.GetBoardPosition();

            // Try make the move
            if (MakeMove(mover, destination))
            {
                // Check castling moves
                if (mover is King && mover.MoveCount == 1)
                {
                    TryPerformCastlingRookMoves(mover);
                }
                else if (mover is Pawn)
                {
                    ((Pawn)mover).validEnPassant = (mover.MoveCount == 1 && mover.GetRelativeBoardCoord(0, -1) != oldPos);
                    CheckPawnEnPassantCapture((Pawn)mover);
                    ChessPiece promotedPiece = CheckPawnPromotion((Pawn)mover);
                    if (promotedPiece != null)
                    {
                        mover = promotedPiece;
                    }
                }
                return(true);
            }
            return(false);
        }
示例#9
0
        public static TilePosition BoardCoordToTile(BoardCoord boardCoord)
        {
            var tilePosition = new TilePosition();
            switch (boardCoord.YRank)
            {
                case "8":
                    tilePosition.X = 0;
                    break;
                case "7":
                    tilePosition.X = 1;
                    break;
                case "6":
                    tilePosition.X = 2;
                    break;
                case "5":
                    tilePosition.X = 3;
                    break;
                case "4":
                    tilePosition.X = 4;
                    break;
                case "3":
                    tilePosition.X = 5;
                    break;
                case "2":
                    tilePosition.X = 6;
                    break;
                case "1":
                    tilePosition.X = 7;
                    break;
            }

            tilePosition.Y = PositionCharToInt(boardCoord.XRank);

            return tilePosition;
        }
	bool InputFilter(AbstractTile selectedTile, AbstractTile destinationTile, TileMoveDirection moveDirection) 
	{
		if (pieceToMove == null || pieceToMoveDestination == null) {
			return true;
		}
		
		AbstractTile tileToMove = pieceToMove.Tile;
		AbstractTile tileToMoveDest = pieceToMoveDestination.Tile;
		
		if (destinationTile == null) 
		{
			Match3BoardGameLogic boardLogic = Match3BoardGameLogic.Instance;
			BoardCoord targetBoardPos = selectedTile.BoardPiece.BoardPosition;
			targetBoardPos.OffsetByAndClamp(boardLogic.tilesMoveDirections[(int)moveDirection], boardLogic.boardData.NumRows - 1, boardLogic.boardData.NumColumns - 1);
			destinationTile = boardLogic.boardData[targetBoardPos].Tile;
		}
		
		if (tileToMove == selectedTile && tileToMoveDest == destinationTile ||
			tileToMove == destinationTile && tileToMoveDest == selectedTile)
		{
			disableTutorial = true;
			TileSwitchInput.Instance.InputFilter = null;
			return true;
		}

		return false;
	}
示例#11
0
    /// <summary>
    /// Moves a chess piece from it's current position to the destination.
    /// </summary>
    /// <param name="mover"></param>
    /// <param name="destination"></param>
    /// <returns></returns>
    protected bool MakeMove(ChessPiece mover, BoardCoord destination)
    {
        BoardCoord previousPosition = mover.GetBoardPosition();
        bool       wasThreat        = IsThreat(mover, destination);

        if (mover.MakeMoveTo(destination))
        {
            if (wasThreat)
            {
                mover.CaptureCount++;
            }
            numConsecutiveCapturelessMoves = (wasThreat == false && (mover is Pawn) == false) ? numConsecutiveCapturelessMoves + 1 : 0;
            UpdateSquareOccupiers(previousPosition, mover.GetBoardPosition());
            if (mover.GetTeam() == Team.WHITE)
            {
                lastMovedWhitePiece = mover;
            }
            else
            {
                lastMovedBlackPiece = mover;
            }
            return(true);
        }
        return(false);
    }
示例#12
0
 /// <summary>
 /// Simulates a move being played. NOTE: Must be followed by RevertSimulatedMove.
 /// </summary>
 /// <param name="mover">Piece to move.</param>
 /// <param name="dest">Destination to move to.</param>
 /// <param name="originalOccupier">The occupier at the destination prior to this simulated move.</param>
 /// <param name="originalLastMover">The last moved piece prior to this simulated move.</param>
 protected void SimulateMove(ChessPiece mover, BoardCoord dest, ChessPiece originalOccupier, out ChessPiece originalLastMover)
 {
     originalLastMover = null;
     if (AssertContainsCoord(dest))
     {
         if (mover.GetTeam() == Team.WHITE)
         {
             if (lastMovedWhitePiece != null)
             {
                 originalLastMover = lastMovedWhitePiece;
             }
             lastMovedWhitePiece = mover;
         }
         else
         {
             if (lastMovedBlackPiece != null)
             {
                 originalLastMover = lastMovedBlackPiece;
             }
             lastMovedBlackPiece = mover;
         }
         if (originalOccupier != null)
         {
             originalOccupier.IsAlive = false;
         }
         board.GetCoordInfo(mover.GetBoardPosition()).occupier = null;
         board.GetCoordInfo(dest).occupier = mover;
         mover.SetBoardPosition(dest);
     }
 }
示例#13
0
        protected override BoardCoord TryAddAvailableEnPassantMove(Pawn mover)
        {
            const int LEFT  = -1;
            const int RIGHT = 1;

            if (mover.canEnPassantCapture)
            {
                for (int i = LEFT; i <= RIGHT; i += 2)
                {
                    int        modulusRelativeX = MathExtensions.mod(i, BOARD_WIDTH);
                    BoardCoord coord            = TryGetSpecificMove(mover, mover.GetRelativeBoardCoord(modulusRelativeX, 0), threatOnly: true);
                    if (board.ContainsCoord(coord))
                    {
                        ChessPiece piece = board.GetCoordInfo(coord).occupier;
                        if (piece is Pawn && piece == LastMovedOpposingPiece(mover) && ((Pawn)piece).validEnPassant)
                        {
                            if (IsPieceInCheckAfterThisMove(currentRoyalPiece, mover, mover.GetRelativeBoardCoord(modulusRelativeX, 1)) == false)
                            {
                                return(TryGetSpecificMove(mover, mover.GetRelativeBoardCoord(modulusRelativeX, 1)));
                            }
                        }
                    }
                }
            }
            return(BoardCoord.NULL);
        }
示例#14
0
 public void Move(Vector2 pos)
 {
     BoardTile = Helpers.TileToBoardCoord((int)pos.X, (int)pos.Y);
     Position = Helpers.TileToPixel((int)pos.X, (int)pos.Y);
     TilePosition = new TilePosition() { X = (int)pos.Y, Y = (int)pos.X };
     CollisionRect = new Rectangle((int)Position.X, (int)Position.Y, 132, 132);
 }
示例#15
0
        public override List <BoardCoord> CalculateAvailableMoves(ChessPiece mover)
        {
            BoardCoord[]      templateMoves  = mover.CalculateTemplateMoves().ToArray();
            List <BoardCoord> availableMoves = new List <BoardCoord>(templateMoves.Length);

            for (int i = 0; i < templateMoves.Length; i++)
            {
                if (IsPieceInCheckAfterThisMove(currentRoyalPiece, mover, templateMoves[i]) == false)
                {
                    availableMoves.Add(templateMoves[i]);
                }
            }

            if (mover is Pawn)
            {
                BoardCoord enPassantMove = TryAddAvailableEnPassantMove((Pawn)mover);
                if (enPassantMove != BoardCoord.NULL)
                {
                    availableMoves.Add(enPassantMove);
                }

                if (checkingForCheck == false && CanPromote((Pawn)mover, availableMoves.ToArray()))
                {
                    OnDisplayPromotionUI(true);
                }
            }

            return(availableMoves);
        }
示例#16
0
        public void Move(BoardCoord originCoord, BoardCoord targetCoord, Action onFinish)
        {
            IChessmanController icc;

            if (TryGetChessman(originCoord, out icc))
            {
                IChessmanController targeticc;
                if (TryGetChessman(targetCoord, out targeticc))
                {
                    icc.Move(targetCoord, () =>
                    {
                        targeticc.Destroy();
                        _chessmans.Remove(targeticc);
                        onFinish();
                    });
                }
                else
                {
                    icc.Move(targetCoord, onFinish);
                }
            }
            else
            {
                onFinish();
            }
        }
示例#17
0
    public void OnTileTapped(AbstractTile tile)
    {
        BoardCoord targetCoord = tile.BoardPiece.BoardPosition;

        if (selectedTile == typeof(BombTile))
        {
            GameObject.Destroy(tile.gameObject);
            BombTile newTile = Match3BoardRenderer.Instance.SpawnSpecificTileAt(targetCoord, selectedTile, TileColorType.None) as BombTile;
            newTile.TileColor = RuleEntry.genericColors[Random.Range(0, Match3BoardRenderer.maxNumBoardColors)];
            newTile.UpdateMaterial();
        }
        else if (selectedTile == typeof(DirectionalDestroyTile))
        {
            GameObject.Destroy(tile.gameObject);

            DirectionalDestroyTile newTile = null;
            if (Random.value > 0.5f)
            {
                newTile = Match3BoardRenderer.Instance.SpawnSpecificTileAt(targetCoord, typeof(RowDestroyTile), TileColorType.None) as DirectionalDestroyTile;
            }
            else
            {
                newTile = Match3BoardRenderer.Instance.SpawnSpecificTileAt(targetCoord, typeof(ColumnDestroyTile), TileColorType.None) as DirectionalDestroyTile;
            }

            newTile.TileColor = RuleEntry.genericColors[Random.Range(0, Match3BoardRenderer.maxNumBoardColors)];
            newTile.UpdateMaterial();
        }
        else if (selectedTile == typeof(ColorBombTile))
        {
            GameObject.Destroy(tile.gameObject);

            ColorBombTile newTile = Match3BoardRenderer.Instance.SpawnSpecificTileAt(targetCoord, selectedTile, TileColorType.None) as ColorBombTile;
        }
    }
示例#18
0
    private void CreateBoardObjects(LevelData level, GameManager gameManager)
    {
        boardSquares = new BoardSquare[boardSize.numCols, boardSize.numRows];

        tiles = new Tile[boardSize.numCols, boardSize.numRows];

        for (int row = 0; row < boardSize.numRows; row++)
        {
            for (int col = 0; col < boardSize.numCols; col++)
            {
                BoardCoord boardCoord = new BoardCoord(col, row);

                // Create a board square of right type for this coordinate
                BoardSquareType boardSquareType = (BoardSquareType)level.tiles[col, row];
                if (boardSquareType == BoardSquareType.Blocker && IsCoordEdgeOfBoard(boardCoord))
                {
                    boardSquareType = BoardSquareType.Edge;
                }

                boardSquares[col, row] = CreateBoardSquare(boardCoord, boardSquareType);

                // Create a tile if we should depending on type of board square
                if (CanHaveTileAtCoord(boardCoord))
                {
                    int tileType = level.GetRandomTileType();
                    tiles[col, row] = CreateTile(boardCoord, tileType, gameManager);
                }
            }
        }
    }
示例#19
0
 /// <summary>
 /// Reverts a simulated move. NOTE: Must be preceeded by SimulateMove.
 /// </summary>
 /// <param name="mover">Piece to move.</param>
 /// <param name="dest">Destination to move to.</param>
 /// <param name="originalOccupier">The occupier at the destination prior to this simulated move.</param>
 /// <param name="originalLastMover">The last moved piece prior to this simulated move.</param>
 /// <param name="oldPos">The position of the mover prior to this simulated move.</param>
 protected void RevertSimulatedMove(ChessPiece mover, BoardCoord dest, ChessPiece originalOccupier, ChessPiece originalLastMover, BoardCoord oldPos)
 {
     if (AssertContainsCoord(dest))
     {
         mover.SetBoardPosition(oldPos);
         board.GetCoordInfo(mover.GetBoardPosition()).occupier = mover;
         if (originalOccupier != null)
         {
             originalOccupier.IsAlive          = true;
             board.GetCoordInfo(dest).occupier = originalOccupier;
         }
         else
         {
             board.GetCoordInfo(dest).occupier = null;
         }
         if (mover.GetTeam() == Team.WHITE)
         {
             lastMovedWhitePiece = originalLastMover;
         }
         else
         {
             lastMovedBlackPiece = originalLastMover;
         }
     }
 }
示例#20
0
    // TODO : 손좀 보자
    public BoardCoord GetClickedCoord()
    {
        float      mousePositionX = float.MaxValue;
        float      mousePositionZ = float.MaxValue;
        BoardCoord clickedCoord   = new BoardCoord(-1, -1);

        //if (!Camera.main) ;
        if (Camera.main)
        {
            RaycastHit hit;
            float      raycastDistance = 1000.0f;

            if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition),
                                out hit, raycastDistance, LayerMask.GetMask("ChessBoard")))
            {
                mousePositionX = hit.point.x - transform.position.x;
                mousePositionZ = hit.point.z - transform.position.z;
            }
            else
            {
                return(clickedCoord);
            }

            if (!((float)BoardEdge.LEFT <= mousePositionX && mousePositionX <= (float)BoardEdge.RIGHT &&
                  (float)BoardEdge.Bottom <= mousePositionZ && mousePositionZ <= (float)BoardEdge.Top))
            {
                return(clickedCoord);
            }

            return(new BoardCoord(mousePositionX, mousePositionZ));
        }
        return(clickedCoord);
    }
示例#21
0
    /// <summary>
    /// Преобразовать позицию на доске в позицию на экране
    /// </summary>
    /// <param name="coord">позиция на доске</param>
    /// <returns></returns>
    public Vector3 BoardCoordToTransformPosition(BoardCoord coord)
    {
        float x = rectTransform.position.x + coord.column * CurrentCellSize + CurrentCellSize / 2;
        float y = rectTransform.position.y + coord.row * CurrentCellSize + CurrentCellSize / 2;

        return(new Vector3(x, y, 0));
    }
示例#22
0
    public static int Distance(BoardCoord origin, BoardCoord target)
    {
        BoardCoord displacement    = target - origin;
        int        squaredDistance = displacement.col * displacement.col + displacement.row * displacement.row;

        int shift = 2;
        int shiftedSquaredDinstance = squaredDistance >> shift;

        while (shiftedSquaredDinstance != 0 && shiftedSquaredDinstance != squaredDistance)
        {
            ++shift;
            ++shift;
            shiftedSquaredDinstance = squaredDistance >> shift;
        }
        --shift;
        --shift;

        int distance = 0;

        while (shift >= 0)
        {
            distance = distance << 1;
            int candidateDistance = distance + 1;
            if (candidateDistance * candidateDistance <= (squaredDistance >> shift))
            {
                distance = candidateDistance;
            }
            shift = shift - 2;
        }

        return(distance);
    }
示例#23
0
    /// <summary>
    /// Parses the name of the coordinate from the name of a board piece which must use a valid format like: [3,4] BoardPiece.
    /// </summary>
    /// <returns>
    /// The parsed BoardCoord from the given board piece name.
    /// </returns>
    /// <param name='strName'>
    /// Board piece game object name.
    /// </param>
    public static BoardCoord ParseCoordFromString(string strName)
    {
        BoardCoord result = new BoardCoord(-1, -1);

        //TODO: this can be optimized with a regex expression (no time to implement this now)

        // Extract the board piece name from the gameobject name (TODO: note to self: use regex expression for faster and cleaner results)
        string[] strParts = strName.Split(',');
        if (strParts.Length != 2)
        {
            Debug.LogError("[BoardCoord] Invalid board piece naming format: " + strName);
        }
        else
        {
            string strPart1 = strParts[0];
            string strRow   = strPart1.Substring(strPart1.IndexOf('[') + 1).Trim();

            string strPart2 = strParts[1];
            string strCol   = strPart2.Substring(0, strPart2.IndexOf(']')).Trim();

            result.row = int.Parse(strRow);
            result.col = int.Parse(strCol);
        }

        return(result);
    }
示例#24
0
 public Pawn(Team team, BoardCoord position, bool canEnPassantCapture = true, uint initialMoveLimit = 2) : base(team, position)
 {
     m_pieceType              = Piece.Pawn;
     this.validEnPassant      = false;
     this.canEnPassantCapture = canEnPassantCapture;
     this.initialMoveLimit    = initialMoveLimit;
 }
示例#25
0
        public override List <BoardCoord> CalculateAvailableMoves(ChessPiece mover)
        {
            BoardCoord[]      templateMoves  = mover.CalculateTemplateMoves().ToArray();
            List <BoardCoord> availableMoves = new List <BoardCoord>(templateMoves.Length);

            for (int i = 0; i < templateMoves.Length; i++)
            {
                availableMoves.Add(templateMoves[i]);
            }

            if (mover is King && mover.MoveCount == 0)
            {
                availableMoves.AddRange(TryAddAvailableCastleMoves(mover));
            }
            else if (mover is Pawn)
            {
                BoardCoord enPassantMove = TryAddAvailableEnPassantMove((Pawn)mover);
                if (enPassantMove != BoardCoord.NULL)
                {
                    availableMoves.Add(enPassantMove);
                }
                if (checkingForCheck == false && CanPromote((Pawn)mover, availableMoves.ToArray()))
                {
                    OnDisplayPromotionUI(true);
                }
            }

            return(availableMoves);
        }
示例#26
0
 public Vector3 GetBoardPosition(BoardCoord coord)
 {
     return(new Vector3(
                _collider.transform.position.x + (((float)coord.X - 0.5f) * _collider.size.x / 8) - _collider.size.x / 2,
                0,
                _collider.transform.position.z + (((float)coord.Y - 0.5f) * _collider.size.z / 8) - _collider.size.z / 2
                ));
 }
	public virtual void InitComponent(AbstractBoardRenderer _boardRenderer) {
//		Board = owner;
		BoardPosition = new BoardCoord(-1, -1);
		BoardRenderer = _boardRenderer;
		
		// Parent this board piece to the owner's transform.
		cachedTransform.parent = BoardRenderer.cachedTransform;
	}
示例#28
0
 public AbstractBoardPiece this[BoardCoord boardPos] {
     get {
         return(this[boardPos.row, boardPos.col]);
     }
     set {
         this[boardPos.row, boardPos.col] = value;
     }
 }
示例#29
0
    public void UpdateBoardPieceGridTransform(Match3BoardPiece boardPiece, BoardCoord newGridPos)
    {
        Vector3 gridOffset = Vector3.zero;

        gridOffset.x = newGridPos.col * boardRenderer.horizontalTileDistance + boardRenderer.horizontalTileOffset;
        gridOffset.y = -newGridPos.row * boardRenderer.verticalTileDistance + boardRenderer.verticalTileOffset;
        boardPiece.transform.localPosition = gridOffset;
    }
示例#30
0
    public void Setup(BoardCoord boardCoord, BoardSquareType boardSquareType)
    {
        this.boardSquareType = boardSquareType;

        gameObject.name = boardSquareType.ToString() + "_" + boardCoord.col + "_" + boardCoord.row;

        boardSquareView.SetSpriteForBoardSquare(boardSquareType);
    }
示例#31
0
 public void SetCustomBoardCoordinateKey(BoardCoord coordToChange, string newAlgebraicKey)
 {
     if (ContainsCoord(coordToChange))
     {
         coordinates[coordToChange].algebraicKey    = newAlgebraicKey;
         coordinates[coordToChange].boardChunk.name = newAlgebraicKey;
     }
 }
        private bool IsPieceInCheckMateAfterThisMove(ChessPiece pieceToCheck, ChessPiece mover, BoardCoord dest)
        {
            if (AssertContainsCoord(dest))
            {
                if (checkingForCheckmate)
                {
                    return(false);
                }

                // Temporarily simulate the move actually happening
                ChessPiece originalOccupier = board.GetCoordInfo(dest).occupier;
                ChessPiece originalLastMover;
                BoardCoord oldPos = mover.GetBoardPosition();
                SimulateMove(mover, dest, originalOccupier, out originalLastMover);

                ChessPiece occupier = null;
                if (mover is Pawn)
                {
                    occupier = CheckPawnEnPassantCapture((Pawn)mover);
                }

                // Check whether the piece is checkmated after this temporary move
                bool hasAnyMoves = false;
                checkingForCheckmate = true;
                foreach (ChessPiece piece in GetPieces(pieceToCheck.GetTeam()))
                {
                    if (piece.IsAlive && hasAnyMoves == false)
                    {
                        BoardCoord[] availableMoves = CalculateAvailableMoves(piece).ToArray();
                        for (int i = 0; i < availableMoves.Length; i++)
                        {
                            if (IsPieceInCheckAfterThisMove(pieceToCheck, piece, availableMoves[i]))
                            {
                                continue;
                            }
                            else
                            {
                                hasAnyMoves = true;
                            }
                        }
                    }
                }
                checkingForCheckmate = false;

                if (occupier != null)
                {
                    board.GetCoordInfo(occupier.GetBoardPosition()).occupier = occupier;
                    occupier.IsAlive = true;
                    occupier.gameObject.SetActive(true);
                }

                // Revert the temporary move back to normal
                RevertSimulatedMove(mover, dest, originalOccupier, originalLastMover, oldPos);

                return(hasAnyMoves == false);
            }
            return(false);
        }
示例#33
0
    /// <summary>
    /// Initialize game board
    /// </summary>
    /// <returns></returns>
    public bool InitBoard()
    {
        boardStatus = new GameObject[NUM_BOARD_ROW][];
        for (int i = 0; i < NUM_BOARD_ROW; i++)
        {
            boardStatus[i] = new GameObject[NUM_BOARD_COL];
        }


        for (int i = 0; i < 8; i++)
        {
            boardStatus[i][0] =
                Instantiate(heroCards[i].heroModelPrefab,
                            BoardCoord.GetBoardCoordVector3(i, 0),
                            heroCards[i].heroModelPrefab.transform.rotation,
                            pieceZone.transform);
            boardStatus[i][0].GetComponent <Piece>().Initialize(TeamColor.White, heroCards[i]);
            boardStatus[i][0].GetComponent <Piece>().MovePosition(new BoardCoord(i, 0));

            boardStatus[i][NUM_BOARD_ROW - 1] =
                Instantiate(heroCards[i + NUM_PIECE_PREFABS / 2].heroModelPrefab,
                            BoardCoord.GetBoardCoordVector3(i, NUM_BOARD_COL - 1),
                            heroCards[i + NUM_PIECE_PREFABS / 2].heroModelPrefab.transform.rotation,
                            pieceZone.transform);
            boardStatus[i][NUM_BOARD_ROW - 1].GetComponent <Piece>().Initialize(TeamColor.Black, heroCards[i + NUM_PIECE_PREFABS / 2]);
            boardStatus[i][NUM_BOARD_ROW - 1].GetComponent <Piece>().MovePosition(new BoardCoord(i, NUM_BOARD_COL - 1));
        }

        kingBlack = boardStatus[3][7].GetComponent <Piece>();
        kingWhite = boardStatus[3][0].GetComponent <Piece>();

        // code for when num of user's piece set are 18
        if (NUM_PIECE_PREFABS == 18)
        {
            for (int i = 0; i < NUM_PIECE_PREFABS / 2 - 1; i++)    // instantiate pawn
            {
                boardStatus[i][1] =
                    Instantiate(heroCards[8].heroModelPrefab,
                                BoardCoord.GetBoardCoordVector3(i, 1),
                                heroCards[8].heroModelPrefab.transform.rotation,
                                pieceZone.transform);
                boardStatus[i][1].GetComponent <Piece>().Initialize(TeamColor.White, heroCards[8]);
                boardStatus[i][1].GetComponent <Piece>().MovePosition(new BoardCoord(i, 1));

                boardStatus[i][NUM_BOARD_ROW - 2] =
                    Instantiate(heroCards[8 + NUM_PIECE_PREFABS / 2].heroModelPrefab,
                                BoardCoord.GetBoardCoordVector3(i, NUM_BOARD_COL - 2),
                                heroCards[8 + NUM_PIECE_PREFABS / 2].heroModelPrefab.transform.rotation,
                                pieceZone.transform);
                boardStatus[i][NUM_BOARD_ROW - 2].GetComponent <Piece>().Initialize(TeamColor.Black, heroCards[8 + NUM_PIECE_PREFABS / 2]);
                boardStatus[i][NUM_BOARD_ROW - 2].GetComponent <Piece>().MovePosition(new BoardCoord(i, NUM_BOARD_COL - 2));
            }
        }

        ResetPiecesMovableCount();

        return(true);
    }
示例#34
0
	/// <summary>
	/// Gets the next pattern coordinate for this pattern shape.
	/// It will return null when there are no more points available for this pattern.
	/// </summary>
	/// <returns>
	/// The next pattern coordinate.
	/// </returns>
	public override bool GetNextPatternCoord(out BoardCoord result) {
		result.row = 0;
		result.col = 0;
		if ( (startRow <= endRow && iteratorIdx <= endRow) || (startRow > endRow && iteratorIdx >= startRow) ) {
			result.row = (startRow < endRow) ? iteratorIdx++ : iteratorIdx--;
			result.col = columnIdx;
//			result = new BoardCoord(startRow < endRow ? iteratorIdx++ : iteratorIdx--, columnIdx);
			return true;
		}

		return false;
	}
示例#35
0
        public Piece(string stringType, PieceColour pieceColour, Vector2 pos)
        {
            //Constants
            mPieceTexture = Content.Load<Texture2D>(stringType);
            Type = Helpers.GetPieceType(stringType);
            Colour = pieceColour;

            //Updated on move
            BoardTile = Helpers.TileToBoardCoord((int)pos.X,(int)pos.Y);
            Position = Helpers.TileToPixel((int) pos.X, (int) pos.Y);
            TilePosition = new TilePosition(){ X = (int)pos.Y,Y = (int)pos.X};
            CollisionRect = new Rectangle((int)Position.X, (int)Position.Y, 64, 64);
        }
	protected BoardCoord ConvertToBoardCoord(Vector3 position)
	{
		BoardCoord returnValue = new BoardCoord(-1, -1);
		
		position.x /= Screen.width;
		position.y /= Screen.height;
		
		Vector3 worldSpacePosition = Match3BoardGameLogic.Instance.gameCamera.ViewportToWorldPoint(position);
		Vector3 boardSpacePosition = Match3BoardRenderer.Instance.transform.InverseTransformPoint(worldSpacePosition);
		
		returnValue.col = Convert.ToInt32(boardSpacePosition.x / Match3BoardRenderer.Instance.horizontalTileDistance);
		returnValue.row = Convert.ToInt32(-boardSpacePosition.y / Match3BoardRenderer.Instance.verticalTileDistance);
		
//		Debug.LogWarning("[BoardPieceTouchController] Found: " + returnValue.col + " " + returnValue.row);
		
		return returnValue;
	}
示例#37
0
	public void OffsetBy(BoardCoord offset) {
		row += offset.row;
		col += offset.col;
	}
	public Match3Tile SpawnTileAt(BoardCoord boardPos, bool offBoardTile = false, bool noLockedTiles = false, bool isBoardSetup = false) 
	{
		return SpawnTileAt(boardPos.row, boardPos.col, offBoardTile, noLockedTiles);
	}
	public abstract bool GetNextPatternCoord(out BoardCoord result);
	public Match3Tile SpawnSpecificTileAt(BoardCoord spawnPos, System.Type tileType, TileColorType prefabDefaultColor, bool offBoardTile, bool isBoardSetup)
	{
		return SpawnSpecificTileAt(spawnPos.row, spawnPos.col, tileType, prefabDefaultColor, offBoardTile, isBoardSetup);
	}
示例#41
0
	/// <summary>
	/// Parses the name of the coordinate from the name of a board piece which must use a valid format like: [3,4] BoardPiece.
	/// </summary>
	/// <returns>
	/// The parsed BoardCoord from the given board piece name.
	/// </returns>
	/// <param name='strName'>
	/// Board piece game object name.
	/// </param>
	public static BoardCoord ParseCoordFromString(string strName) {
		BoardCoord result = new BoardCoord(-1, -1);
		
		//TODO: this can be optimized with a regex expression (no time to implement this now)
		
		// Extract the board piece name from the gameobject name (TODO: note to self: use regex expression for faster and cleaner results)
		string[] strParts = strName.Split(',');
		if (strParts.Length != 2) {
			Debug.LogError("[BoardCoord] Invalid board piece naming format: " + strName);
		} else {
			string strPart1 = strParts[0];
			string strRow = strPart1.Substring(strPart1.IndexOf('[') + 1).Trim();
			
			string strPart2 = strParts[1];
			string strCol = strPart2.Substring(0, strPart2.IndexOf(']')).Trim();
			
			result.row = int.Parse(strRow);
			result.col = int.Parse(strCol);
		}
		
		return result;
	}
示例#42
0
	public BoardCoord(BoardCoord other) {
		row = other.row;
		col = other.col;
	}
示例#43
0
	public AbstractBoardPiece this[BoardCoord boardPos] {
		get {
			return this[boardPos.row, boardPos.col];
		}
		set {
			this[boardPos.row, boardPos.col] = value;
		}
	}
	/// <summary>
	/// Raises the board piece button pressed event when pressing a level editor button in the Unity scene view.
	/// </summary>
	/// <param name='refBoardPiece'>
	/// Board piece.
	/// </param>
	/// <param name='rowIdx'>
	/// Row index.
	/// </param>
	/// <param name='colIdx'>
	/// Col index.
	/// </param>
	void OnBoardPieceButtonPressed(ref Match3BoardPiece refBoardPiece, BoardCoord boardPos) 
	{
		// Validate the current board tool selection (the currently selected prefab)
//		editor.selectedBoardTool = Selection.activeGameObject;
		object selectedToolObj = null;
		if (editor.selectedBoardTool != null) {
			if (editor.selectedBoardTool.GetComponent<Match3BoardPiece>()) {
				selectedToolObj = editor.selectedBoardTool.GetComponent<Match3BoardPiece>();
			} if (editor.selectedBoardTool.GetComponent<Match3Tile>()) {
				selectedToolObj = editor.selectedBoardTool.GetComponent<Match3Tile>();
			}
		}
		
		if ( selectedToolObj is Match3BoardPiece ) {
			// Get the currently selected board tool type
			if ( !LevelEditorUtils.IsPrefabInArray(editor.boardRenderer.prefabsPieces, editor.selectedBoardTool) ) {
				EditorUtility.DisplayDialog("Level Editor", "The selected board prefab is not added to the Match3BoardRenderer pieces prefab list!", "Ok");
				return;
			}

			// Spawn a new board piece
			editor.SpawnBoardPieceAt(boardPos, editor.selectedBoardTool);
		} else if ( selectedToolObj is Match3Tile ) {
			// Get the currently selected board tool type
			if ( !LevelEditorUtils.IsPrefabInArray(editor.boardRenderer.tilesPrefabs, editor.selectedBoardTool) ) {
				EditorUtility.DisplayDialog("Level Editor", "The selected board prefab is not added to the Match3BoardRenderer tiles prefab list!", "Ok");
				return;
			} else if (refBoardPiece == null) {
				// Spawn a default board piece if none found at the current board position.
				editor.SpawnBoardPieceAt(boardPos, editor.defaultBoardPiece.gameObject);
				editor.UpdateBoardPieceGridTransform(refBoardPiece, boardPos);
			}
			
			// Spawn a new tile on the selected board piece.
			editor.SpawnTileAt(refBoardPiece, boardPos, editor.selectedBoardTool);
		} else {
			EditorUtility.DisplayDialog("Level Editor", "The selected board prefab type is not supported!", "Ok");
			return;
		}
	}
示例#45
0
	public void OffsetByAndClamp(BoardCoord offset, int clampToMaxRow, int clampToMaxColumn) {
		OffsetByAndClamp(offset.row, offset.col, clampToMaxRow, clampToMaxColumn);
	}
	protected void CheckBoardTouch(Vector3 position, CustomInput.TouchInfo touchInfo)
	{
		boardCoord = ConvertToBoardCoord(position);
			
		if(boardCoord.row < 0 || boardCoord.row >= Match3BoardRenderer.Instance.Board.NumRows || boardCoord.col < 0 || boardCoord.col >= Match3BoardRenderer.Instance.Board.NumColumns)
		{
			return;
		}
		
		CustomInput.TouchInfo modifiedTouchInfo = new CustomInput.TouchInfo(touchInfo);
		modifiedTouchInfo.position = position;
		
		if(prevBoardCoord != boardCoord)
		{
			boardPiece = Match3BoardRenderer.Instance.Board[boardCoord.row, boardCoord.col];
			RaiseOnNewBoardPieceSelected(boardPiece, modifiedTouchInfo);
			prevBoardCoord = boardCoord;
		}
	}
示例#47
0
 public static BoardCoord TileToBoardCoord(int x, int y)
 {
     var boardCoord = new BoardCoord();
     switch (y)
     {
         case 0:
             boardCoord.YRank = "8";
             break;
         case 1:
             boardCoord.YRank = "7";
             break;
         case 2:
             boardCoord.YRank = "6";
             break;
         case 3:
             boardCoord.YRank = "5";
             break;
         case 4:
             boardCoord.YRank = "4";
             break;
         case 5:
             boardCoord.YRank = "3";
             break;
         case 6:
             boardCoord.YRank = "2";
             break;
         case 7:
             boardCoord.YRank = "1";
             break;
     }
     switch (x)
     {
         case 0:
             boardCoord.XRank = "a";
             break;
         case 1:
             boardCoord.XRank = "b";
             break;
         case 2:
             boardCoord.XRank = "c";
             break;
         case 3:
             boardCoord.XRank = "d";
             break;
         case 4:
             boardCoord.XRank = "e";
             break;
         case 5:
             boardCoord.XRank = "f";
             break;
         case 6:
             boardCoord.XRank = "g";
             break;
         case 7:
             boardCoord.XRank = "h";
             break;
     }
     return boardCoord;
 }
示例#48
0
        public static BoardCoord MoveXY(string XRank, int Xquantity, string YRank, int Yquantity)
        {
            var x = PositionCharToInt(XRank);
            var y = Convert.ToInt32(YRank);

            x += Xquantity;

            XRank = PositionIntToChar(x);
            x = PositionCharToInt(XRank);

            y += Yquantity;

            BoardCoord newPosition = new BoardCoord() {XRank=XRank,YRank=y.ToString()};

            return newPosition;
        }