Exemple #1
0
        public static IEnumerable<IMove> GetAllMovesFromField(GameBoard board, BoardPosition fromFieldPosition, out bool forcedOnly)
        {
            PlayerColor player = board[fromFieldPosition].Occupation;
            List<IMove> moves = new List<IMove>();

            var firstTargets = GetPossibleTargetFields(board, fromFieldPosition, out forcedOnly);

            if (!forcedOnly)
            {
                moves.AddRange(firstTargets.Select(pos => new SimpleMove(player, fromFieldPosition, pos, board[fromFieldPosition].Piece == PieceType.King, false)));
                return moves;
            }

            JumpTree tree = new JumpTree(fromFieldPosition, firstTargets, board);
            ConstructJumpTree(ref tree);

            var paths = tree.Linearize();
            tree = null;

            foreach (var path in paths)
            {
                if (path.Count == 2)
                {
                    moves.Add(new SimpleMove(player, path[0], path[1], board[fromFieldPosition].Piece == PieceType.King, true));
                }
                else
                {
                    CompoundMove move = CompoundMove.FromPositions(player, path.First(), path.Last(), board[fromFieldPosition].Piece == PieceType.King, path.GetRange(1, path.Count - 2).ToArray());
                    moves.Add(move);
                }
            }

            return moves;
        }
Exemple #2
0
        private IEnumerable<BoardPosition> GetBoardPieces(IVirtualBoard board, BoardPosition piece, MainWindow.Surround direction)
        {
            Func<BoardPosition, BoardPosition> dir = p =>
            {
                switch (direction)
                {
                    case MainWindow.Surround.Top:
                        return board.TopOf(p);
                    case MainWindow.Surround.Right:
                        return board.RightOf(p);
                    case MainWindow.Surround.Bottom:
                        return board.BottomOf(p);
                    case MainWindow.Surround.Left:
                        return board.LeftOf(p);
                    default:
                        throw new ArgumentOutOfRangeException("direction");
                }
            };

            var borderingPiece = dir(piece);
            if (borderingPiece != null && borderingPiece.Piece.RootBoardPiece == piece.Piece.RootBoardPiece)
            {
                yield return borderingPiece;

                var borderingPiece2 = dir(borderingPiece);
                if (borderingPiece2 != null && borderingPiece2.Piece.RootBoardPiece == piece.Piece.RootBoardPiece)
                    yield return borderingPiece2;
            }
        }
		public IMoveResults MovePawn(int rowFrom, int columnFrom, int rowTo, int columnTo) {
			BreakthroughPawn pawn = core.PawnAt(rowFrom, columnFrom);
			BreakthroughPawn target = core.PawnAt(rowTo, columnTo);
			BreakthroughPawn killed = null;
			BoardPosition from = new BoardPosition(rowFrom, columnFrom);
			BoardPosition to = new BoardPosition(rowTo, columnTo);
			bool gameOver = false;
			Player winner = pawn.Player;

			if (!ValidateMove(rowFrom, columnFrom, rowTo, columnTo)) {
				return new BreakthroughMoveResults(false, killed, from, to, gameOver, winner);
			}

			if (target != null) {
				core.RemovePawn(target.Row, target.Column);
				killed = target;
			}

			// If the pawn reaches the end of the board the game is over.
			if (rowTo == 0 || rowTo == core.Size-1) {
				gameOver = true;
			}

			core.MovePawn(rowFrom, columnFrom, rowTo, columnTo);

			// Swap the turn.
			if (core.Turn == Player.white) {
				core.Turn = Player.black;
			}
			else {
				core.Turn = Player.white;
			}

			return new BreakthroughMoveResults(true, killed, from, to, gameOver, winner);
		}
 public ChessPosition( ChessPosition chessPos )
 {
     this.posType = chessPos.posType;
     this.nRank = chessPos.nRank;
     this.nPile = chessPos.nPile;
     this.pos = chessPos.pos;
 }
        protected virtual bool MoveDownSolves( BoardPosition position )
        {
            var firstBottomOf = _board.BottomOf( position );

            if ( firstBottomOf == null || firstBottomOf.Piece == position.Piece )
                return false;

            var secondBottomOf = _board.BottomOf( firstBottomOf );
            var thirdBottomOf = _board.BottomOf( secondBottomOf );

            var firstNewLeftOf = _board.LeftOf( firstBottomOf );
            var secondNewLeftOf = _board.LeftOf( firstNewLeftOf );

            var firstNewRightOf = _board.RightOf( firstBottomOf );
            var secondNewRightOf = _board.RightOf( firstNewRightOf );

            bool alignsBottom = ( secondBottomOf != null && thirdBottomOf != null )
                             && ( position.Piece == secondBottomOf.Piece )
                             && ( position.Piece == thirdBottomOf.Piece );

            bool alignsLeft = ( firstNewLeftOf != null && secondNewLeftOf != null )
                              && ( position.Piece == firstNewLeftOf.Piece )
                              && ( position.Piece == secondNewLeftOf.Piece );

            bool alignsRight = ( firstNewRightOf != null && secondNewRightOf != null )
                               && ( position.Piece == firstNewRightOf.Piece )
                               && ( position.Piece == secondNewRightOf.Piece );

            bool alignsLeftRight = ( firstNewLeftOf != null && firstNewRightOf != null )
                                   && ( position.Piece == firstNewLeftOf.Piece )
                                   && ( position.Piece == firstNewRightOf.Piece );

            return alignsBottom || alignsLeft || alignsRight || alignsLeftRight;
        }
Exemple #6
0
 public void HandleBattle(UnitPiece attacker, BoardPosition attackerPosition, UnitPiece defender, BoardPosition defenderPosition)
 {
     BattleResult result = UnitUtilities.ResolveBattle(attacker.Rank, defender.Rank);
     // Based on result, update players
     switch (result)
     {
         case BattleResult.Success:
             {
                 // Remove from defender owner
                 defender.Owner.Pieces.Remove(defender);
                 break;
             }
         case BattleResult.Fail:
             {
                 // Remove from attacker owner
                 attacker.Owner.Pieces.Remove(attacker);
                 break;
             }
         case BattleResult.Split:
             {
                 //Remove both
                 attacker.Owner.Pieces.Remove(attacker);
                 defender.Owner.Pieces.Remove(defender);
                 break;
             }
         default:
             {
                 break;
             }
     }
     EventManager.Raise(new UnitBattleResultEvent(attacker, defender, attackerPosition, defenderPosition, result));
     turnComplete = true;
 }
Exemple #7
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="boardPositions"></param>
 public Board(BoardPosition[,] boardPositions)
 {
     this.EvaluationValue = 0;
     amountOfRedItems = 0;
     amountOfWhiteItems = 0;
     this.boardPositions = boardPositions;
     CalculateMovableTiles();
 }
 public UnitBattleResultEvent(UnitPiece attacker, UnitPiece defender, BoardPosition attackerPosition, BoardPosition defenderPosition, BattleResult result)
     : base(attacker)
 {
     this.defender = defender;
     this.result = result;
     this.attackerPosition = attackerPosition;
     this.defenderPosition = defenderPosition;
 }
 public void Constructor_GivenInternalFile8_ThrowsException()
 {
     try {
         BoardPosition boardPosition = new BoardPosition(8, 0);
         Assert.Fail("Expected a ChessBoardException to be thrown!");
     }
     catch (ChessBoardException ex) {
         Assert.That(ex.ExceptionReason, Is.EqualTo(ExceptionReason.InvalidBoardPosition));
     }
 }
        public void Constructor_GivenFileaRank1_Succeeds()
        {
            BoardPosition boardPosition = new BoardPosition('a', 1);

            Assert.That(boardPosition.File, Is.EqualTo('a'));
            Assert.That(boardPosition.Rank, Is.EqualTo(1));
            Assert.That(boardPosition.InternalFile, Is.EqualTo(0));
            Assert.That(boardPosition.InternalRank, Is.EqualTo(0));
            Assert.That(boardPosition.Name, Is.EqualTo("a1"));
        }
        public IList<ValidationError> ValidateMove(Game game, Enums.PlayerType owner, BoardPosition boardPosition)
        {
            var warnings = new List<ValidationError>();
            var isMoveLegitimate = _moveValidationSpecification.IsMoveValid(game, owner, boardPosition);

            if(!isMoveLegitimate)
                warnings.Add(new ValidationError { Type = "InvalidMove", Message = "Sorry this move is not legal, try another move to keep playing." });

            return warnings;
        }
 public GameMove Build(Enums.PlayerType owner, BoardPosition position)
 {
     var move = new GameMove
     {
         Id = _id,
         Owner = owner,
         Position = position
     };
     return move;
 }
 public static GameMove CreateFrom(Enums.PlayerType owner, BoardPosition position)
 {
     var move = new GameMove
     {
         Id = Guid.NewGuid(),
         Owner = owner,
         Position = position
     };
     return move;
 }
        public void Can_Clear_Piece_From_Position()
        {
            // arrange
            var boardPosition = new BoardPosition(1, 1, new Piece(2, 3, PieceColor.Green));

            // act
            boardPosition.ClearPieceFromPosition();

            // assert
            Assert.IsFalse(boardPosition.ContainsPiece());
        }
Exemple #15
0
        public BoardPosition PlayTurn(TicTacToeBoard board)
        {
            var random = new Random();

            BoardPosition move;
            do
            {
                move = new BoardPosition(random.Next(1, 4), random.Next(1, 4));
            } while (!board.SquareIsFree(move));

            return move;
        }
Exemple #16
0
        public static bool IsPositionInBattleSquare(BoardPosition boardPosition)
        {
            if (boardPosition.Row >= outerBoarderSquareCount + 1 && boardPosition.Row <= rowCount - outerBoarderSquareCount)
            {
                if (boardPosition.Column >= outerBoarderSquareCount + 1 && boardPosition.Column <= columnCount - outerBoarderSquareCount)
                {
                    return true;
                }
            }

            return false;
        }
        public void Verifies_If_Board_Position_Is_Occupied_By_Piece()
        {
            // arrange
            var boardPositionWithPiece = new BoardPosition(1, 1, new Piece(2, 3, PieceColor.Green));
            var boardPositionWithoutPiece = new BoardPosition(1, 1);

            // act

            // assert
            Assert.IsTrue(boardPositionWithPiece.ContainsPiece());
            Assert.IsFalse(boardPositionWithoutPiece.ContainsPiece());
        }
Exemple #18
0
    public Transform GetTransformForPosition(BoardPosition position)
    {
        Transform transform = default(Transform);

        GameObject target = null;
        if(board.TryGetValue(position, out target))
        {
            transform = target.transform;
        }

        return transform;
    }
        public void Sets_Row_And_Column_Only_On_Instantiation()
        {
            // arrange
            var positionRow = 3;
            var positionColumn = 4;

            // act
            var boardPosition = new BoardPosition(positionRow, positionColumn);

            // assert
            Assert.AreEqual(positionRow, boardPosition.Row);
            Assert.AreEqual(positionColumn, boardPosition.Column);
        }
Exemple #20
0
    public void AddPiece(BoardPosition position, UnitRank rank)
    {
        //Check for existing piece, remove it if needed.
        //Debug.Log("atteming to add " + UnitUtilities.ReadableRank(rank) + " at " + position.ToString());
        bool equal = false;
        if (pieces.ContainsKey(position))
        {
            UnitPiece existing;
            if (pieces.TryGetValue(position, out existing))
            {
                if (existing.Rank.Equals(rank))
                {
                    //We're not going to remove then add the same exact piece to the same position
                    equal = true;
                }
                else
                {
                    RemovePiece(position);
                }
            }

        }
        if (!equal)
        {
            Transform target = BoardManager.GetTransformForPosition(position);
            if (!EqualityComparer<Transform>.Default.Equals(target, default(Transform)))
            {
                GameObject plane = Instantiate(UnitPlane);
                UnitPiece piece = GeneratePiece(rank, plane);
                if (piece.Owner != null)
                {
                    piece.Piece.transform.SetParent(piece.Owner.Holder.transform);
                    plane.name = UnitUtilities.ReadableRank(rank);
                    plane.layer = LayerMask.NameToLayer("Pieces");
                    Vector3 planePos = target.position;
                    planePos.z = GOLayer.UNIT_LAYER;
                    plane.transform.position = planePos;
                    Renderer r = plane.GetComponent<Renderer>();
                    r.material = MaterialManager.GetRankMaterial(rank);
                    pieces.Add(position, piece);
                    EventManager.Raise(new UnitPlacedEvent(position, piece));
                }
                else
                {
                    piece.Destroy();
                    Destroy(plane);
                }
            }
        }
    }
        public void Sets_Row_And_Column_And_Piece_On_Instantiation()
        {
            // arrange
            var positionRow = 3;
            var positionColumn = 4;
            var piece = new Piece(3, 4, PieceColor.Orange);

            // act
            var boardPosition = new BoardPosition(positionRow, positionColumn, piece);

            // assert
            Assert.AreEqual(positionRow, boardPosition.Piece.Row);
            Assert.AreEqual(positionColumn, boardPosition.Column);
        }
		public BreakthroughMoveResults(bool success, IPawn pawnKilled, BoardPosition start, BoardPosition end, bool gameOver, Player winner) {
			Success = success;
			GameOver = gameOver;
			Winner = winner;

			Path = new List<BoardPosition>(2);
			Path.Add(start);
			Path.Add(end);

			PawnsKilled = new List<IPawn>(1);
			if (pawnKilled != null) {
				PawnsKilled.Add(pawnKilled);
			}
		}
    static void ProcessBoard(BoardPosition[] board, int startPosition)
    {
        var position = startPosition;
        
        while (position < 100)
        {
            var currentPosition = board[position];
            var nextPosition = board[position + 1];
            var nextThrowsAndDice = currentPosition.ThrowsAndDice.Advance();

            nextPosition.SetThrowsAndDice(nextThrowsAndDice);

            if (currentPosition.JumpToPosition.HasValue)
            {
                var targetPosition = board[currentPosition.JumpToPosition.Value];
                var isUpdated = targetPosition.SetThrowsAndDice(currentPosition.ThrowsAndDice.Reset());

                if (currentPosition.IsSnake)
                {
                    if (isUpdated)
                    {
                        position = currentPosition.JumpToPosition.Value;
                        continue;
                    }
                    else if(currentPosition.ThrowsAndDice.DiceEyes == 6)
                    {
                        var nextSetPosition = FindNextNoSnakeSetPosition(board, position + 1);
                        if (nextSetPosition == -1)
                        {
                            if (board[100].ThrowsAndDice == null)
                            {
                                board[100].ThrowsAndDice = new ThrowsAndDice();
                            }
                            board[100].ThrowsAndDice.Throws = -1;
                            break;
                        }
                        else
                        {
                            position = nextSetPosition;
                            continue;
                        }
                    }
                }
            }

            position++;
        }

        Console.WriteLine(board[100].ThrowsAndDice.Throws);
    }
        private IEnumerable<ITicTacToePlayer> GenerateLine(Predicate<BoardPosition> equation)
        {
            var e = _boardStatus.GetEnumerator();
            for (var row = _boundaries.TopLeft.Row; row <= _boundaries.BottomRight.Row; row++)
            {
                for (var column = _boundaries.TopLeft.Column; column <= _boundaries.BottomRight.Column; column++)
                {
                    var position = new BoardPosition(row, column);
                    e.MoveNext();

                    if(equation(position))
                        yield return e.Current;
                }
            }
        }
		public CheckersMoveResults(bool success, bool turnOver, IPawn pawnKilled, BoardPosition start, BoardPosition end, bool gameOver, Player winner, bool becameKing) {
			Success = success;
			TurnOver = turnOver;
			GameOver = gameOver;
			Winner = winner;

			Path = new List<BoardPosition>(2);
			Path.Add(start);
			Path.Add(end);

			PawnsKilled = new List<IPawn>(1);
			if (pawnKilled != null) {
				PawnsKilled.Add(pawnKilled);
			}

			BecameKing = becameKing;
		}
    public ChessPosition( int nPosRank, int nPosPile )
    {
        this.posType = GetPositionType( nPosRank, nPosPile );
        if( this.posType != BoardPositionType.eNone ) {

            this.nRank = nPosRank;
            this.nPile = nPosPile;

            this.pos = (BoardPosition)(nPosPile * ChessData.nNumRank + nPosRank);
        }
        else {

            this.nRank = -1;
            this.nPile = -1;
            this.pos = BoardPosition.InvalidPosition;
        }
    }
        public void Sets_Row_And_Column_For_Piece_When_Set_To_Position()
        {
            // arrange
            var piece = new Piece(3, 4, PieceColor.Orange);

            // act
            var boardPosition = new BoardPosition(1, 1, piece);
            var firstPieceRow = boardPosition.Piece.Row;
            var firstPieceColumn = boardPosition.Piece.Column;
            boardPosition.SetPiece(new Piece(5, 6, PieceColor.Green));

            // assert
            Assert.AreEqual(1, boardPosition.Row);
            Assert.AreEqual(1, boardPosition.Column);
            Assert.AreEqual(1, firstPieceRow);
            Assert.AreEqual(1, firstPieceColumn);
            Assert.AreEqual(1, boardPosition.Piece.Row);
            Assert.AreEqual(1, boardPosition.Piece.Column);
        }
    public ChessPosition( BoardPosition boardPos )
    {
        int nPosRank = 0, nPosPile = 0;
        this.posType = ChessPosition.CalcPositionIndex( boardPos, ref nPosRank, ref nPosPile );
        if( this.posType != BoardPositionType.eNone ) {

            this.nRank = nPosRank;
            this.nPile = nPosPile;

            this.pos = boardPos;
        }
        else {

            this.nRank = -1;
            this.nPile = -1;

            this.pos = BoardPosition.InvalidPosition;
        }
    }
Exemple #29
0
        public Board()
        {
            this.Positions = new BoardPosition[columnCount, rowCount];
            for (int row = 1; row <= rowCount; row++)
            {
                for (int column = 1; column <= columnCount; column++)
                {
                    var boardPosition = new BoardPosition(row, column);

                    // assign a piece to the position if it is not in the battle square
                    if (!IsPositionInBattleSquare(boardPosition))
                    {
                        var pieceColor = (row % 2 == 0 && column % 2 == 0 || row % 2 != 0 && column % 2 != 0) ? PieceColor.Green : PieceColor.Orange;
                        boardPosition.SetPiece(new Piece(0, 0, pieceColor));
                    }

                    this.Positions[row - 1, column - 1] = boardPosition;
                }
            }
        }
Exemple #30
0
        public JumpTree(BoardPosition root, IEnumerable<BoardPosition> targets, GameBoard board)
        {
            _root = new JumpTreeNode
            {
                Depth = 0,
                Position = root,
                Board = board
            };

            NodeCount = 1;

            foreach (BoardPosition pos in targets)
            {
                GameBoard boardCopy = _root.Board.Copy();
                SimpleMove move = new SimpleMove(boardCopy[_root.Position].Occupation, _root.Position, pos, boardCopy[_root.Position].Piece == PieceType.King);
                boardCopy.SetCapture(move);
                boardCopy.DoMove(move, true);
                _root.Children.Add(new JumpTreeNode { Board = boardCopy, Depth = _root.Depth + 1, Parent = _root, Position = pos, CheckAgain = !move.IsUpgrade });
                ++NodeCount;
            }
        }
 public BoardPositionEvent(BoardPosition position)
 {
     this.position = position;
 }
Exemple #32
0
 /// <summary>
 /// Constructs a ChessMove that moves a piece from one position to another
 /// </summary>
 /// <param name="start">the starting position of the piece to move</param>
 /// <param name="end">the position where the piece will end up</param>
 public ChessMove(BoardPosition start, BoardPosition end)
 {
     StartPosition = start;
     EndPosition   = end;
     MoveType      = ChessMoveType.Normal;
 }
Exemple #33
0
 /// <summary>
 /// Constructs a ChessMove that performs a "special" move from one position to another.
 /// </summary>
 /// <param name="start">the starting position of the piece to move</param>
 /// <param name="end">the position where the piece will end up</param>
 /// <param name="type">the special chess move type to perform</param>
 public ChessMove(BoardPosition start, BoardPosition end, ChessMoveType type) :
     this(start, end)
 {
     MoveType = type;
 }
 public SpawnInfo(PieceInfo piece, BoardPosition newPosition)
 {
     PieceInfo   = piece;
     NewPosition = newPosition;
 }
 public PlayerModel(BoardPosition initialPosition, int lives)
 {
     this.position      = initialPosition;
     this.numberOfLives = lives;
     this.numberOfMoves = 0;
 }
 /// <summary>
 /// Looks up a ChessPiece by position on the board
 /// </summary>
 /// <param name="pos">The position the query</param>
 /// <returns>A ChessPiece reference or null</returns>
 public ChessPiece GetPieceByPosition(BoardPosition pos) => _board.GetPieceByPosition(pos);
Exemple #37
0
 public BoardTileType getValueForPosition(BoardPosition position)
 {
     return(board[position.x, position.y]);
 }
Exemple #38
0
        //
        // Summary:
        //     Create an array with the movements actually avaliable to the Dame.
        //
        // Returns:
        //     An array of booleans with the same size of the board where the
        //     positions contain a true value if it is a possible movement;
        //     otherwise it contains false.
        public override bool[,] PossibleTargets()
        {
            // 4-----1
            // -4---1-
            // --8-5--
            // ---D---
            // --7-6--
            // -3---2-
            // 3-----2

            bool[,] possibleTargets = new bool[Board.Height, Board.Width];
            TwoDimensionsArrayPosition arrPos = BoardPosition.ToArrayPosition(Board.Height);

            bool withoutCaptures = true;

            // NE (1) (Only catch avaliable)
            for (int arrRow = arrPos.Row - 1, arrColumn = arrPos.Column + 1; arrRow >= 0 && arrColumn < Board.Width; arrRow--, arrColumn++)
            {
                if (Board.Pieces(arrRow, arrColumn) != null)
                {
                    if (Board.Pieces(arrRow, arrColumn).Team != Team && arrRow - 1 >= 0 && arrColumn + 1 < Board.Width && Board.Pieces(arrRow - 1, arrColumn + 1) == null)
                    {
                        possibleTargets[arrRow - 1, arrColumn + 1] = true;
                        withoutCaptures = false;
                        break;
                    }
                    else
                    {
                        break;
                    }
                }
            }

            // SE (2) (Only catch avaliable)
            for (int arrRow = arrPos.Row + 1, arrColumn = arrPos.Column + 1; arrRow < Board.Height && arrColumn < Board.Width; arrRow++, arrColumn++)
            {
                if (Board.Pieces(arrRow, arrColumn) != null)
                {
                    if (Board.Pieces(arrRow, arrColumn).Team != Team && arrRow + 1 < Board.Height && arrColumn + 1 < Board.Width && Board.Pieces(arrRow + 1, arrColumn + 1) == null)
                    {
                        possibleTargets[arrRow + 1, arrColumn + 1] = true;
                        withoutCaptures = false;
                        break;
                    }
                    else
                    {
                        break;
                    }
                }
            }

            // SW (3) (Only catch avaliable)
            for (int arrRow = arrPos.Row + 1, arrColumn = arrPos.Column - 1; arrRow < Board.Height && arrColumn >= 0; arrRow++, arrColumn--)
            {
                if (Board.Pieces(arrRow, arrColumn) != null)
                {
                    if (Board.Pieces(arrRow, arrColumn).Team != Team && arrRow + 1 < Board.Height && arrColumn - 1 >= 0 && Board.Pieces(arrRow + 1, arrColumn - 1) == null)
                    {
                        possibleTargets[arrRow + 1, arrColumn - 1] = true;
                        withoutCaptures = false;
                        break;
                    }
                    else
                    {
                        break;
                    }
                }
            }

            // NW (4) (Only catch avaliable)
            for (int arrRow = arrPos.Row - 1, arrColumn = arrPos.Column - 1; arrRow >= 0 && arrColumn >= 0; arrRow--, arrColumn--)
            {
                if (Board.Pieces(arrRow, arrColumn) != null)
                {
                    if (Board.Pieces(arrRow, arrColumn).Team != Team && arrRow - 1 >= 0 && arrColumn - 1 >= 0 && Board.Pieces(arrRow - 1, arrColumn - 1) == null)
                    {
                        possibleTargets[arrRow - 1, arrColumn - 1] = true;
                        withoutCaptures = false;
                        break;
                    }
                    else
                    {
                        break;
                    }
                }
            }

            if (withoutCaptures)
            {
                // NE (5) (Without catch case)
                if (arrPos.Row - 1 >= 0 && arrPos.Column + 1 < Board.Width && Board.Pieces(arrPos.Row - 1, arrPos.Column + 1) == null)
                {
                    possibleTargets[arrPos.Row - 1, arrPos.Column + 1] = true;
                }

                // SE (6) (Without catch case)
                if (arrPos.Row + 1 < Board.Height && arrPos.Column + 1 < Board.Width && Board.Pieces(arrPos.Row + 1, arrPos.Column + 1) == null)
                {
                    possibleTargets[arrPos.Row + 1, arrPos.Column + 1] = true;
                }

                // SW (7) (Without catch case)
                if (arrPos.Row + 1 < Board.Height && arrPos.Column - 1 >= 0 && Board.Pieces(arrPos.Row + 1, arrPos.Column - 1) == null)
                {
                    possibleTargets[arrPos.Row + 1, arrPos.Column - 1] = true;
                }

                // NW (8) (Without catch case)
                if (arrPos.Row - 1 >= 0 && arrPos.Column - 1 >= 0 && Board.Pieces(arrPos.Row - 1, arrPos.Column - 1) == null)
                {
                    possibleTargets[arrPos.Row - 1, arrPos.Column - 1] = true;
                }
            }

            return(possibleTargets);
        }
Exemple #39
0
 private void UpdateBoard(BoardPosition[,] boardState, BoardPosition move, TeamName teamName)
 {
     boardState[move.XIndex, move.YIndex].IsOccupied = true;
     boardState[move.XIndex, move.YIndex].Owner      = teamName;
 }
 public TicTacToeMove(BoardPosition position)
 {
     Position = position;
 }
Exemple #41
0
        private void CreatePieceFactory(BoardPosition position)
        {
            var bKing = position.Where(x => x.Value == 'k').ToList();
            var wKing = position.Where(x => x.Value == 'K').ToList();

            if (wKing.Count != 1 || bKing.Count != 1)
            {
                return;
            }

            this.WhiteKing = new King(true, this.GetCell, wKing[0].Key);
            this.BlackKing = new King(false, this.GetCell, bKing[0].Key);

            foreach (KeyValuePair <string, char> kvp in position)
            {
                if (kvp.Value == 'K')
                {
                    this.GetCell(kvp.Key).CurrentPiece = this.WhiteKing;
                }
                else if (kvp.Value == 'k')
                {
                    this.GetCell(kvp.Key).CurrentPiece = this.BlackKing;
                }
                else
                {
                    var cell = this.GetCell(kvp.Key);
                    switch (kvp.Value)
                    {
                    case 'R':
                        cell.CurrentPiece = new Rook(true, this.GetCell, kvp.Key, this.BlackKing);
                        break;

                    case 'r':
                        cell.CurrentPiece = new Rook(false, this.GetCell, kvp.Key, this.WhiteKing);
                        break;

                    case 'N':
                        cell.CurrentPiece = new Knight(true, this.GetCell, kvp.Key);
                        break;

                    case 'n':
                        cell.CurrentPiece = new Knight(false, this.GetCell, kvp.Key);
                        break;

                    case 'B':
                        cell.CurrentPiece = new Bishop(true, this.GetCell, kvp.Key, this.BlackKing);
                        break;

                    case 'b':
                        cell.CurrentPiece = new Bishop(false, this.GetCell, kvp.Key, this.WhiteKing);
                        break;

                    case 'Q':
                        cell.CurrentPiece = new Queen(true, this.GetCell, kvp.Key, this.BlackKing);
                        break;

                    case 'q':
                        cell.CurrentPiece = new Queen(false, this.GetCell, kvp.Key, this.WhiteKing);
                        break;

                    case 'P':
                        cell.CurrentPiece = new Pawn(true, this.GetCell, kvp.Key);
                        break;

                    case 'p':
                        cell.CurrentPiece = new Pawn(false, this.GetCell, kvp.Key);
                        break;

                    default:
                        break;
                    }
                }
            }
        }
Exemple #42
0
    // Update is called once per frame
    void Update()
    {
        hideHandPos = defaultHandPos + hideHandOffset;

        Ray        mouseRay     = cam.ScreenPointToRay(Input.mousePosition);
        RaycastHit interfaceHit = new RaycastHit();

        Physics.Raycast(mouseRay, out interfaceHit);
        if (Input.GetMouseButtonDown(1))
        {
            selectify = null;
        }
        if (selectify != null)
        {
            selectShow.SetActive(true);
            selectShow.transform.position  = selectify.transform.position;
            selectShow.transform.rotation  = selectify.transform.rotation;
            selectShow.transform.position -= selectify.transform.forward * .005f;
            actionLine.positionCount       = 0;

            hand.transform.position = hand.transform.position * (1 - Time.deltaTime) + hideHandPos * Time.deltaTime;
        }
        else
        {
            hand.transform.position = hand.transform.position * (1 - Time.deltaTime) + defaultHandPos * Time.deltaTime;
            targetBoard.SetActive(false);
        }
        if (interfaceHit.collider)
        {
            Debug.DrawLine(new Vector3(0, 0, 0), interfaceHit.transform.position);
            Card          rayCard  = interfaceHit.collider.GetComponent <Card>();
            BoardPosition bordComp = interfaceHit.collider.GetComponent <BoardPosition>();
            if (selectify != null && selectify.type == Card.cardType.targetBoard && rayCard == null)
            {
                targetBoard.SetActive(true);
            }
            else
            {
                targetBoard.SetActive(false);
            }

            if (Input.GetMouseButtonDown(0) && rayCard != null)
            {
                if (rayCard.state == Card.cardState.onboard && selectify != null)
                {
                    if (rayCard.isValidTarget(selectify))
                    {
                        hand.removeCard(selectify);
                        rayCard.playCardToThis(selectify);
                        selectify = null;
                    }
                }
                if (hand.hand.Contains(rayCard))
                {
                    selectify = rayCard;
                }
            }
            else if (Input.GetMouseButtonDown(0) && bordComp != null && selectify != null)
            {
                if (bordComp.isPlayableHere(selectify))
                {
                    hand.removeCard(selectify);
                    if (selectify.type == Card.cardType.targetBoard)
                    {
                        bool applyOnce = false;
                        foreach (BoardPosition pos in hand.board.boardPositions)
                        {
                            if (pos.unitCard != null && pos.unitCard.type == Card.cardType.creature)
                            {
                                Debug.Log("attempt");
                                selectify.GetComponent <targetAction>().actOnTarget(pos.unitCard);
                                applyOnce = true;
                            }
                        }

                        /*for (int col = 0; col <= 4; col++)
                         * {
                         *  for(int row = 0; row <= 7; row++)
                         *  {
                         *      Debug.Log("pos" + row + ":" + col);
                         *      BoardPosition applypos = hand.board.getBoardPosition(row, col);
                         *      if (applypos.unitCard != null && applypos.unitCard.type == Card.cardType.creature)
                         *      {
                         *          Debug.Log("attempt");
                         *          selectify.GetComponent<targetAction>().actOnTarget(applypos.unitCard);
                         *          applyOnce = true;
                         *      }
                         *  }
                         * }*/
                        selectify.transform.parent   = null;
                        selectify.transform.position = new Vector3(0, 2, 0);
                        if (!applyOnce)
                        {
                            Destroy(selectify);
                        }
                    }
                    else
                    {
                        hand.board.addCardToBoard(selectify, bordComp.row, bordComp.col, hand.dir);
                    }
                    selectify = null;
                }
            }
            if ((selectify != null && (selectify.type != Card.cardType.targetBoard))
                &&
                ((bordComp != null && bordComp.isPlayableHere(selectify)) || (rayCard != null && rayCard.isValidTarget(selectify))))
            {
                if (selectify.type == Card.cardType.targetCol)
                {
                    if (bordComp != null)
                    {
                        targetCol.SetActive(true);
                        targetCol.transform.position = bordComp.transform.position - new Vector3(0, 0, bordComp.transform.position.z);
                    }
                }
                else if (selectify.type == Card.cardType.targetRow)
                {
                    if (bordComp != null)
                    {
                        targetRow.SetActive(true);
                        targetRow.transform.position = bordComp.transform.position - new Vector3(bordComp.transform.position.x, 0, 0);
                    }
                }
                else
                {
                    GameObject targ = bordComp != null ? bordComp.gameObject : rayCard.gameObject;
                    targetShow.SetActive(true);
                    targetShow.transform.position = targ.transform.position + targ.transform.forward * .05f;
                    if (bordComp != null)
                    {
                        targetShow.transform.rotation = new Quaternion(1, 0, 0, 1);
                    }
                    else
                    {
                        targetShow.transform.rotation = targ.transform.rotation;
                    }
                }
            }
            else
            {
                targetShow.SetActive(false);
            }
            if (selectify != null && (
                    bordComp != null && bordComp.isPlayableHere(selectify) ||
                    rayCard != null && rayCard.isValidTarget(selectify)
                    ))
            {
                actionLine.positionCount = 20;
                Debug.DrawLine(selectify.transform.position, interfaceHit.transform.position);
                for (int i = 0; i < actionLine.positionCount; i++)
                {
                    float   percentLine = i / (actionLine.positionCount - 1f);
                    float   leanBias    = selectify.transform.position.x > 0 ? Mathf.Sin(percentLine * Mathf.PI) : -Mathf.Sin(percentLine * Mathf.PI);
                    Vector3 hoverHeight = new Vector3(leanBias * 2, Mathf.Sin(percentLine * Mathf.PI) * 4, 0);
                    actionLine.SetPosition(i, selectify.transform.position * (1 - percentLine) + hoverHeight + interfaceHit.transform.position * percentLine);
                }

                if (rayCard != null)
                {
                    targetShow.SetActive(true);
                    targetShow.transform.position = interfaceHit.transform.position - interfaceHit.transform.forward * .05f;
                }
                else if (bordComp != null && selectify.type != Card.cardType.targetBoard)
                {
                    targetShow.SetActive(true);
                    targetShow.transform.position = interfaceHit.transform.position + interfaceHit.transform.forward * .05f;
                }
            }
            else if (selectify == null)
            {
                selectShow.SetActive(false);
            }
        }
        else
        {
            targetShow.SetActive(false);
            targetBoard.SetActive(false);
        }
    }
Exemple #43
0
 //
 // Summary:
 //     The basic contructor of the Dame that only pass its own the
 //     parameters to its own superclass.
 //
 // Parameters:
 //   boardPosition:
 //     The position of this piece in the board.
 //
 //   board:
 //     The board on which the piece belongs.
 //
 //   team:
 //     The team of the piece.
 public Dame(BoardPosition boardPosition, Board.Board board, Team team) : base("D", boardPosition, board, team)
 {
 }
 /// <summary>
 /// Generates all the possible moves of a piece
 /// </summary>
 /// <param name="pos">Position of the piece to query</param>
 /// <returns>A sequence of moves and their type</returns>
 public IEnumerable <MoveResult> PossibleMoves(BoardPosition pos) => _board.PossibleMoves(pos);
Exemple #45
0
 public void InitializeBoard(BoardPosition position)
 {
     InitializeCells();
     CreatePieceFactory(position);
 }
        public void InitialBoard8x8()
        {
            var board = BoardPosition.InitialSetup(8);

            board.Should().Be(BoardPosition.FromString("4444,4444,4444,0000,0000,5555,5555,5555", ","));
        }
Exemple #47
0
 public ChessBoard(BoardPosition position) : this()
 {
     this.InitializeBoard(position);
     this.InitializeKingComponents();
     this.UpdateBoardState();
 }
Exemple #48
0
    public void GenerateSmartSpawns()
    {
        // Get all my pieces
        List <PieceInfo> piecesToSpawn = new List <PieceInfo>(myPieces.AllPieces.Count);

        foreach (PieceInfo piece in myPieces.AllPieces)
        {
            piecesToSpawn.Add(piece);
        }

        // Get rows
        int backRow = side == Side.A ? 0 : 7;
        int midRow  = side == Side.A ? 1 : 6;

        // 75% to spawn flag on back row
        // 25% to spawn flag on mid row
        PieceInfo     flag    = ExtractPieceFromList(piecesToSpawn, PieceRank.Flag);
        BoardPosition flagPos = new BoardPosition(
            Random.Range(0, Board.WIDTH),
            Random.value > 0.25f ? backRow : midRow);

        gameManager.SpawnPiece(new SpawnInfo(flag, flagPos));

        // Get guard pieces for the flag
        PieceInfo guard1 = ExtractPieceFromList(piecesToSpawn, PieceRank.Spy);
        PieceInfo guard2 = ExtractPieceFromList(piecesToSpawn, PieceRank.Private);

        // 3rd guard can be 3, 4, or 5 star general, equally likely
        PieceRank guard3Rank   = PieceRank.General5;
        float     guard3Chance = Random.value;

        if (guard3Chance > 0.3333f)
        {
            guard3Rank = PieceRank.General3;
        }
        else if (guard3Chance > 0.6666f)
        {
            guard3Rank = PieceRank.General4;
        }
        PieceInfo guard3 = ExtractPieceFromList(piecesToSpawn, guard3Rank);

        // Get guard spawns
        List <BoardPosition> guardSpawns = new List <BoardPosition>();

        // Add sides
        AddBoardPositionIfValid(guardSpawns, flagPos.Left);
        AddBoardPositionIfValid(guardSpawns, flagPos.Right);

        // Add next row
        if (side == Side.A)
        {
            AddBoardPositionIfValid(guardSpawns, flagPos.UpperLeft);
            AddBoardPositionIfValid(guardSpawns, flagPos.Up);
            AddBoardPositionIfValid(guardSpawns, flagPos.UpperRight);
        }
        else
        {
            AddBoardPositionIfValid(guardSpawns, flagPos.DownLeft);
            AddBoardPositionIfValid(guardSpawns, flagPos.Down);
            AddBoardPositionIfValid(guardSpawns, flagPos.DownRight);
        }

        // Randomize spawns
        guardSpawns.Shuffle();

        // Spawn guard pieces
        gameManager.SpawnPiece(new SpawnInfo(guard1, guardSpawns[0]));
        gameManager.SpawnPiece(new SpawnInfo(guard2, guardSpawns[1]));
        gameManager.SpawnPiece(new SpawnInfo(guard3, guardSpawns[2]));

        // List all possible spawns
        float leftValue  = 0f;
        float midValue   = 0f;
        float rightValue = 0f;
        List <BoardPosition> leftFlank  = new List <BoardPosition>();
        List <BoardPosition> midFlank   = new List <BoardPosition>();
        List <BoardPosition> rightFlank = new List <BoardPosition>();

        // Left flank
        for (int i = 0; i < Board.WIDTH / 3; i++)
        {
            for (int j = minSpawnHeight; j <= maxSpawnHeight; j++)
            {
                PieceInfo pieceInfo = board.GetPieceFromPosition(i, j);
                if (pieceInfo != null)
                {
                    leftValue += pieceInfo.Rank.GetValue();
                }
                else
                {
                    leftFlank.Add(new BoardPosition(i, j));
                }
            }
        }

        // Middle flank
        for (int i = Board.WIDTH / 3; i < Board.WIDTH / 3 * 2; i++)
        {
            for (int j = minSpawnHeight; j <= maxSpawnHeight; j++)
            {
                PieceInfo pieceInfo = board.GetPieceFromPosition(i, j);
                if (pieceInfo != null)
                {
                    midValue += pieceInfo.Rank.GetValue();
                }
                else
                {
                    midFlank.Add(new BoardPosition(i, j));
                }
            }
        }

        // Right flank
        for (int i = Board.WIDTH / 3 * 2; i < Board.WIDTH; i++)
        {
            for (int j = minSpawnHeight; j <= maxSpawnHeight; j++)
            {
                PieceInfo pieceInfo = board.GetPieceFromPosition(i, j);
                if (pieceInfo != null)
                {
                    rightValue += pieceInfo.Rank.GetValue();
                }
                else
                {
                    rightFlank.Add(new BoardPosition(i, j));
                }
            }
        }

        // Types of spawns. Both equally likely
        // 1. Conservative - Equally distribute to all 3 flanks
        // 2. Blitz - Concentrate power in 1 flank
        if (Random.value > 0.5f)
        {
            // Conservative - Equally distribute
            Debug.Log("Conservative spawning");

            // Shuffle first
            piecesToSpawn.Sort((pieceInfo1, pieceInfo2) => pieceInfo2.Rank.GetValue().CompareTo(pieceInfo1.Rank.GetValue()));
            leftFlank.Shuffle();
            midFlank.Shuffle();
            rightFlank.Shuffle();

            while (piecesToSpawn.Count > 0)
            {
                PieceInfo pieceToSpawn = ExtractPieceFromList(piecesToSpawn, piecesToSpawn[0].Rank);

                // Find smallest flank in terms of value
                if (leftValue <= midValue && leftValue <= rightValue && leftFlank.Count > 0)
                {
                    SpawnPieceFromPositionList(leftFlank, pieceToSpawn);
                    leftValue += pieceToSpawn.Rank.GetValue();
                }
                else if (midValue <= leftValue && midValue <= rightValue && midFlank.Count > 0)
                {
                    SpawnPieceFromPositionList(midFlank, pieceToSpawn);
                    midValue += pieceToSpawn.Rank.GetValue();
                }
                else
                {
                    SpawnPieceFromPositionList(rightFlank, pieceToSpawn);
                    rightValue += pieceToSpawn.Rank.GetValue();
                }
            }
        }
        else
        {
            // Blitz
            Debug.Log("Blitz spawning");

            piecesToSpawn.Sort((pieceInfo1, pieceInfo2) => pieceInfo2.Rank.GetValue().CompareTo(pieceInfo1.Rank.GetValue()));

            // Choose 1 flank
            List <BoardPosition> chosenFlank;
            List <BoardPosition> otherFlanks;

            float flankChance = Random.value;
            if (flankChance < 0.3333f)
            {
                chosenFlank = leftFlank;
                otherFlanks = midFlank;
                otherFlanks.AddRange(rightFlank);
            }
            else if (flankChance < 0.6666f)
            {
                chosenFlank = midFlank;
                otherFlanks = leftFlank;
                otherFlanks.AddRange(rightFlank);
            }
            else
            {
                chosenFlank = rightFlank;
                otherFlanks = leftFlank;
                otherFlanks.AddRange(midFlank);
            }

            chosenFlank.Shuffle();
            otherFlanks.Shuffle();

            foreach (PieceInfo piece in piecesToSpawn)
            {
                // If chosen flank is not empty,
                if (chosenFlank.Count > 0)
                {
                    // 80% chosen blitz flank
                    // 20% for other flanks
                    flankChance = Random.value;
                    if (flankChance < 0.8f)
                    {
                        SpawnPieceFromPositionList(chosenFlank, piece);
                    }
                    else
                    {
                        SpawnPieceFromPositionList(otherFlanks, piece);
                    }
                }
                else
                {
                    SpawnPieceFromPositionList(otherFlanks, piece);
                }
            }
        }
    }
Exemple #49
0
 public void OnRoundCompletion()
 {
     _lastMove = null;
 }
Exemple #50
0
 public void setTileForPosition(BoardPosition position, BoardTileType tileType)
 {
     board[position.x, position.y] = tileType;
 }