Пример #1
0
        internal static Image GetSquareImage(Square square, Piece piece = null)
        {
            if (piece == null)
                return boardImageCache["Empty"][square.GetSquareColor()];

            var squareColor = square.GetSquareColor();
            var key = piece.Player + piece.GetType().Name;
            return boardImageCache[key][squareColor];
        }
Пример #2
0
        public override bool Equals(object obj)
        {
            Piece other = obj as Piece;

            if (other.GetType() == GetType())
            {
                if (other.color.Equals(color))
                {
                    return(true);
                }
            }
            return(false);
        }
Пример #3
0
        public static void ClickOnTargetSquare(object sender, MouseButtonEventArgs e)
        {
            if (APieceHasBeenPicked == true)
            {
                int       col, row;
                Square    selectedSquare;
                Rectangle selectedRectangle;

                // Translates the clicked on rectangle to the right square.
                GetSelectedSquare(sender, out col, out row, out selectedSquare, out selectedRectangle);

                Square from = CurrentlySelectedSquare;
                Square to   = selectedSquare;

                if (SelectedPiece.GetType() == typeof(King) &&
                    SelectedPiece.regularlMoves.Contains(to) &&
                    (to.Col == SelectedPiece.Square.Col + 2 || to.Col == SelectedPiece.Square.Col - 3))
                {
                    if (to.Col == SelectedPiece.Square.Col + 2)
                    {
                        (SelectedPiece as King).Castle("Short");
                    }
                    else
                    {
                        (SelectedPiece as King).Castle("Long");
                    }
                }
                // Check if the move is legal for the selected piece.
                else if (SelectedPiece.IsMoveLeagel(from, to) == true)
                {
                    // If move is leagel move the piece to the selected square
                    //  and clear all Board flags.
                    SelectedPiece.Move(from, to);

                    // Switch turn to other player.
                    SwitchPlayer();
                }
            }
        }
Пример #4
0
        private void InitGrid()
        {
            var images = new Dictionary <Color, Dictionary <Type, Bitmap> >();

            #region filling up images
            var whites = new Dictionary <Type, Bitmap>();
            var blacks = new Dictionary <Type, Bitmap>();
            images[Color.White] = whites;
            images[Color.Black] = blacks;

            whites[Type.Bishop] = Properties.Resources.BishopW;
            whites[Type.Pawn]   = Properties.Resources.PawnW;
            whites[Type.Knight] = Properties.Resources.KnightW;
            whites[Type.Queen]  = Properties.Resources.QueenW;
            whites[Type.King]   = Properties.Resources.KingW;
            whites[Type.Rook]   = Properties.Resources.RookW;

            blacks[Type.Bishop] = Properties.Resources.BishopB;
            blacks[Type.Pawn]   = Properties.Resources.PawnB;
            blacks[Type.Knight] = Properties.Resources.KnightB;
            blacks[Type.Queen]  = Properties.Resources.QueenB;
            blacks[Type.King]   = Properties.Resources.KingB;
            blacks[Type.Rook]   = Properties.Resources.RookB;
            #endregion

            for (int i = 0; i < 8; i++)
            {
                for (int j = 0; j < 8; j++)
                {
                    grid[i, j] = new GraphicCell(i, j, this);

                    Piece piece = logic.getCellContent(i, j);
                    if (piece != null)
                    {
                        grid[i, j].Image = images[piece.GetColor()][piece.GetType()];
                    }
                }
            }
        }
Пример #5
0
        /// <summary>
        /// Start a new game
        /// </summary>
        public void Start()
        {
            Board  newBoard     = new Board();
            string randomOption = null;

            do
            {
                Console.WriteLine();
                Console.WriteLine(Resource.RandomPlay + " Y / N");
                randomOption = Console.ReadLine();
                randomOption = randomOption.ToUpper();
            }while (randomOption != "Y" && randomOption != "N");


            if (randomOption == "Y")
            {
                newBoard.InitialicePiecesRandom();
            }
            else
            {
                newBoard.InitialicePieces();
            }

            bool again = false;

            do
            {
                newBoard.DrawBoard();

                Piece currentPiece = null;
                while (currentPiece == null)
                {
                    Coordinate currentCoordinates = ReadNewCoordinates();
                    currentPiece = newBoard.SearchPieces(currentCoordinates.Column, currentCoordinates.Row);
                    if (currentPiece != null)
                    {
                        Console.WriteLine(Resource.SelectedPiece + " " + currentPiece.GetType().Name.ToString() + " - " + currentPiece.Color.ToString());
                        Console.WriteLine();
                        Console.WriteLine(Resource.DestinationCoordinates);
                        Coordinate newCoordinates = ReadNewCoordinates();
                        Console.WriteLine();

                        ShowsErrorMessage(newBoard.NewMove(currentPiece, newCoordinates));
                    }
                    else
                    {
                        Console.WriteLine(Resource.CoordinateNotValid);
                        Console.WriteLine();
                    }
                }
                ;

                Console.ForegroundColor = ConsoleColor.White;

                string continueOption = null;
                Console.WriteLine(Resource.WantToContinue + " Y / N");
                continueOption = Console.ReadLine();
                continueOption = continueOption.ToUpper();
                if (continueOption == "Y")
                {
                    again = true;
                    //Console.Clear();
                }
                else
                {
                    again = false;
                }
            } while (again);
        }
Пример #6
0
        internal bool DoMove(Piece piece, Position newPos, Chessboard board)
        {
            bool Obstacle = false;

            // Store a temporary state of the board
            Chessboard tempBoard     = Chessboard.DeepClone(board);
            Piece      pieceMirrored = DeepClone(piece);


            // Check if there any same-side pieces in the way of the moving piece
            // Knight is an eception
            if (!piece.GetType().Equals(typeof(Knight)))
            {
                int Dx = newPos.X - piece.CurrentPosition.X;
                int Dy = newPos.Y - piece.CurrentPosition.Y;

                // Perform mirror operations when needed
                Position newPosMirrored = new Position(newPos.X, newPos.Y);
                if (Dx < 0)
                {
                    tempBoard.State  = HorizontalMirror(tempBoard.State);
                    newPosMirrored.X = (ushort)(7 - newPos.X);
                    pieceMirrored.CurrentPosition.X = (ushort)(7 - piece.CurrentPosition.X);
                }
                if (Dy < 0)
                {
                    tempBoard.State  = VerticalMirror(tempBoard.State);
                    newPosMirrored.Y = (ushort)(7 - newPos.Y);
                    pieceMirrored.CurrentPosition.Y = (ushort)(7 - piece.CurrentPosition.Y);
                }

                Dx = newPosMirrored.X - pieceMirrored.CurrentPosition.X;
                Dy = newPosMirrored.Y - pieceMirrored.CurrentPosition.Y;

                if (Dx == 0)
                {
                    for (int iy = pieceMirrored.CurrentPosition.Y + 1; iy < newPosMirrored.Y; iy++)
                    {
                        if (tempBoard.State[newPosMirrored.X, iy] == null)
                        {
                            continue;
                        }

                        if (iy < newPosMirrored.Y && tempBoard.State[newPosMirrored.X, iy].Side != pieceMirrored.Side)
                        {
                            Obstacle = true;
                        }

                        if (tempBoard.State[newPosMirrored.X, iy].Side == pieceMirrored.Side)
                        {
                            Obstacle = true;
                        }
                    }
                }
                else if (Dy == 0) // Connection line between moves is horizontal
                {
                    for (int ix = pieceMirrored.CurrentPosition.X + 1; ix < newPosMirrored.X; ix++)
                    {
                        if (tempBoard.State[ix, newPosMirrored.Y] == null)
                        {
                            continue;
                        }

                        if (ix < newPosMirrored.X && tempBoard.State[ix, newPosMirrored.Y].Side != pieceMirrored.Side)
                        {
                            Obstacle = true;
                        }

                        if (tempBoard.State[ix, newPosMirrored.Y].Side == pieceMirrored.Side)
                        {
                            Obstacle = true;
                        }
                    }
                }
                else if (Dy / Dx == 1) // Connection line between moves is diagonal
                {
                    int ix = pieceMirrored.CurrentPosition.X + 1;
                    int iy = pieceMirrored.CurrentPosition.Y + 1;

                    for (int i = pieceMirrored.CurrentPosition.X; i < newPosMirrored.X; i++)
                    {
                        if (tempBoard.State[ix, iy] == null)
                        {
                            ix++;
                            iy++;
                            continue;
                        }

                        if (tempBoard.State[ix, iy].Side == pieceMirrored.Side)
                        {
                            Obstacle = true;
                        }

                        if (ix < newPosMirrored.X && iy < newPosMirrored.Y && tempBoard.State[ix, iy].Side != pieceMirrored.Side)
                        {
                            Obstacle = true;
                        }

                        ix++;
                        iy++;
                    }
                }
            }


            // Check if in the end position of the move there is a piece of the same side
            if (board.State[newPos.X, newPos.Y]?.Side == piece.Side)
            {
                Obstacle = true;
            }

            if (!Obstacle)
            {
                board.State[newPos.X, newPos.Y] = piece;
                board.State[piece.CurrentPosition.X, piece.CurrentPosition.Y] = null;
                piece.CurrentPosition.X = newPos.X;
                piece.CurrentPosition.Y = newPos.Y;
                return(true);
            }
            return(false);
        }
Пример #7
0
        //Turn function
        public static bool turn()
        {
            //determine current player
            string player = PLAYERS[turns % 2];

            //Draw board and prompt
            Console.Clear();
            Console.WriteLine(board);
            Console.WriteLine(String.Format("Where would you like to move, {0}?", player));
            Console.WriteLine("\tType 'h' for help");

            //request input
            string input = Console.ReadLine();

            //Lambda for printing help menu;
            Action printH = () => {
                Console.WriteLine("Type [piece],[location] to move your piece.");
                Console.WriteLine("\tEx: 'wp1,a-3'");
                Console.WriteLine("Type [piece] to see a piece's moves.");
                Console.WriteLine("\tEx: 'wp1'");
                //After, printing instructions, request another input and
                //		return to original logic flow
                input = Console.ReadLine();
            };

            //Check for 'h' (or 'H')
            if (input.ToUpper().Equals("H"))
            {
                printH();
            }

            //loop variables
            bool   validMove = false;
            string message   = null;

            //Do, while the user has not entered a valid input, or moved
            do
            {
                while (!verify.Match(input).Success || message != null)
                {
                    if (message != null)
                    {
                        Console.WriteLine(message);
                    }
                    Console.WriteLine("Invalid input!  Try again!");
                    message = null;
                    input   = Console.ReadLine();
                    //Check for 'h' (or 'H')
                    if (input.ToUpper().Equals("H"))
                    {
                        printH();
                    }
                }
                //If input contains a "," and it passed the Regex match, then it must be a movement action
                if (input.Contains(","))
                {
                    string   piece;
                    string   move;
                    string[] splits = input.Split(",");
                    piece = splits[0];
                    move  = splits[1];

                    //Retrieving piece from board
                    Piece p = Chess.GetBoard().GetPiece(piece);
                    if (p != null)
                    {
                        if (p.GetColor() == PLAYTYPES[turns % 2])
                        {
                            //Parsing moveTo location
                            int   col    = ((int)move[0]) - 'a';
                            int   row    = 8 - (((int)move[2]) - '0');
                            Point target = new Point(row, col);

                            //Getting piece's moves
                            List <Point> moves = p.GetMoves();


                            //Searching through movelist for a point matching the moveTo coordinate
                            bool found = moves.Exists((point) => point.Equals(target));

                            //movepiece
                            if (found)
                            {
                                bool moved;
                                (moved, message) = MovePiece(p, target);

                                //If piece was able to move
                                if (moved)
                                {
                                    if (p.GetType() == typeof(Pawn))
                                    {
                                        ((Pawn)p).SetMoved(moved);

                                        //A pawn cannot move backwards, so the only time
                                        //		any pawn can reach the edge of the field is when it
                                        //		hits the opposite edge, turn the piece into a queen
                                        if (p.GetLoc().X == 7 || p.GetLoc().X == 0)
                                        {
                                            Chess.GetBoard().SetPiece(new Queen(p.GetColor(), p.GetLoc()), p.GetLoc());
                                        }
                                    }

                                    if (message != null && message.Equals("Check mate!"))
                                    {
                                        return(false);
                                    }
                                    validMove = true;
                                }
                                //Else if piece couldn't move (checking self)!
                                //		move was not valid, try again
                                else
                                {
                                }
                            }
                            else
                            {
                                message = "Cannot move there!";
                                //return false;
                            }
                        }
                        else
                        {
                            message = "Not your piece";
                            //return false;
                        }
                    }
                    //Invalid move location
                    else
                    {
                        message = String.Format("Cannot move there!\n\t" +
                                                "Type '{0}' to view the moves of piece {0}", piece);
                    }
                }
                //Else, printing moves of piece
                else
                {
                    //Getting piece
                    Piece piece = Chess.GetBoard().GetPiece(input);

                    //Getting piece's moves
                    List <Point> moves = piece.GetMoves();


                    string str = Chess.GetBoard().ToString(moves);


                    //Prining new board
                    Console.Clear();
                    Console.WriteLine(Chess.GetBoard().ToString(moves));
                    Console.WriteLine("Type 'x' to remove x's!");
                    input = Console.ReadLine();
                    //Check for 'h' (or 'H')
                    if (input.ToUpper().Equals("H"))
                    {
                        printH();
                    }
                    else if (input.ToUpper().Equals("X"))
                    {
                        //Printing cleared board
                        Console.Clear();
                        Console.WriteLine(Chess.GetBoard());
                        Console.WriteLine("Continue!");
                        input = Console.ReadLine();
                    }
                }
            }while (!validMove);


            turns++;
            return(true);
        }
Пример #8
0
        /// <summary>
        /// Assess the current state of the game, in favor of a certain color (whoIsToPlay).
        /// Returns an integer between -100 and 100, ranking how good the state of the game is for specified color.
        /// </summary>
        private int assess(Logic game, Color Color) // pretty much heuristic
        {
            /*
             * L = my pieces sum - his pices sum (on start: 39 - 39 = 0, but after we lost the queen -9)
             * we multiply L by a large wieght (say 10,000) to make it matter very much. -> queenloss = -90,000
             *
             * C = for each piece in the center: if its ours sum its value (1, 3, 5, 9) if its his piece, sum his minus value
             * multiply this by, say, 1.
             * if we are not in the center but hes too, then c = 0. if we both control it equally, then C = 0
             * C becomes somethinh when there is a diference.
             *
             * V = our king safety - his. this one's weight = 100
             */


            // todo return a number from -inf(we lose) to inf(we win)
            // optional aspects:
            // are we (or they) close to the centre
            // are any piece lost
            // is the king vulnerable
            int       centerControl, piecesLost, kingVulnerability, pieceEaten;
            const int a = 1, b = 10000, c = 100, d = 0;
            //First we'll check whoIsToPlay's control over the center.
            //1: How many pieces from each side physically occupy the center?
            int countWhite = occupyCenter(game, Color.White);
            int countBlack = occupyCenter(game, Color.Black);

            centerControl = this.Color == Color.White ? a * (countWhite - countBlack) : a * (countBlack - countWhite);

            //Next, we will compare our losses against the opponent's.
            countWhite = 0;
            countBlack = 0;
            int WhiteVulnerability = 0, BlackVulnerability = 0; // num of opponent's pieces that can get into king palace

            Cell whiteKing = game.FindKing(Color.White), blackKing = game.FindKing(Color.Black);

            HashSet <Cell> surroundingWhiteKing = new HashSet <Cell>();
            HashSet <Cell> surroundingBlackKing = new HashSet <Cell>();

            for (int i = whiteKing.I - 2; i < whiteKing.I + 2; i++)
            {
                for (int j = whiteKing.J - 2; j < whiteKing.J + 2; j++)
                {
                    if (game.validIndexes(i, j))
                    {
                        surroundingWhiteKing.Add(game.grid[i, j]);
                    }
                }
            }

            for (int i = blackKing.I - 2; i < blackKing.I + 2; i++)
            {
                for (int j = blackKing.J - 2; j < blackKing.J + 2; j++)
                {
                    if (game.validIndexes(i, j))
                    {
                        surroundingBlackKing.Add(game.grid[i, j]);
                    }
                }
            }

            for (int i = 0; i < 8; i++)
            {
                for (int j = 0; j < 8; j++)
                {
                    if (game.grid[i, j].piece != null)
                    {
                        if (game.grid[i, j].piece.GetColor() == Color.White)
                        {
                            countWhite += worths[game.grid[i, j].piece.GetType()];

                            foreach (var move in game.GetValidMoves(game.grid[i, j]))
                            {
                                if (surroundingWhiteKing.Contains(move))
                                {
                                    WhiteVulnerability++;
                                    break;
                                }
                            }
                        }

                        else
                        {
                            countBlack += worths[game.grid[i, j].piece.GetType()];

                            foreach (var move in game.GetValidMoves(game.grid[i, j]))
                            {
                                if (surroundingBlackKing.Contains(move))
                                {
                                    BlackVulnerability++;
                                    break;
                                }
                            }
                        }
                    }
                }
            }

            piecesLost        = this.Color == Color.White ? b * (countWhite - countBlack) : b * (countBlack - countWhite);
            kingVulnerability = this.Color == Color.White ? c * (countWhite - countBlack) : b * (countBlack - countWhite);

            //Finally, we will assess the pieces we can eat, and our pieces, which can be eaten.
            int eatenValue, whatAteMeValue, threatValue;

            if (eaten != null)
            {
                eatenValue     = PieceValue(eaten.GetType());
                whatAteMeValue = PieceValue(whatIMoved.piece.GetType());
                threatValue    = ThreatValue();

                pieceEaten = eatenValue - whatAteMeValue - threatValue; //If value of eaten piece is more than what ate him,
                                                                        //that is good for current player. If threat on current
                                                                        //player's piece is positive, it is bad because the player is
                                                                        //threatened by lesser piece.
            }

            else
            {
                whatAteMeValue = PieceValue(whatIMoved.piece.GetType());
                threatValue    = ThreatValue();

                pieceEaten = whatAteMeValue - threatValue;
            }

            //RECENTLY COMMENTED
            //Console.WriteLine(whatIMoved.piece.GetColor() + "  " + whatIMoved.I + " " + whatIMoved.J + " " + centerControl + " " + piecesLost + " " + kingVulnerability + " " + pieceEaten + "\t sum: " + (a * centerControl + b * piecesLost + c * kingVulnerability + d * pieceEaten));

            return(a * centerControl + b * piecesLost + c * kingVulnerability + d * pieceEaten);
        }
Пример #9
0
 public static Image GetPieceImage(Piece piece)
 {
     return GetPieceImage(piece.Player, piece.GetType());
 }
Пример #10
0
 public static void eliminer(Piece piece, Piece echange)
 {
     //Piece swapP=piece;
     //Case swapC = echange;
     plateau[piece.getHorizontal(), piece.getVertical()] = new Case(piece.getHorizontal(), piece.getVertical());
     plateau[echange.getHorizontal(), echange.getVertical()] = Piece.construct(piece.GetType().Name, echange.getHorizontal(), echange.getVertical(), piece.getColor());
 }