public ChessboardSearchTask(WorkFlowTask parent, CaptureCamera captureCamera, Chessboard chessboard)
     : base(parent)
 {
     CaptureCamera = captureCamera;
     Chessboard = chessboard;
     WriteLine("Taking Snapshot");
 }
 public ChessboardSearchTask(Window window, CaptureCamera captureCamera, Chessboard chessboard)
     : base(window)
 {
     CaptureCamera = captureCamera;
     Chessboard = chessboard;
     WriteLine("Taking Snapshot");
 }
        public VirtualProjector(string name, string uuid, Size imageSize, PointF principal, double focalLength, Screen screen, Chessboard chessboard, CaptureCamera captureCamera)
            : base(name, uuid, imageSize, principal, focalLength, screen, chessboard, captureCamera)
        {
            OrbitCamera = new OrbitCamera("{0} Orbit".FormatWith(name), "N/A", imageSize, principal, focalLength,
                Intrinsics.NearPlaneDistance, Intrinsics.FarPlaneDistance) { Color = Color.DarkCyan.Alpha(0.7f), };
            Color = Color.DarkKhaki.Alpha(0.6f);
            
            ProgramTask.AttachInputToCamera(Program.WhenInput.Where(input => !input.KeyPressed(Keys.C)), Window, OrbitCamera);

            Program.WhenInput.Where(input => input.KeyDown(Keys.P)).Subscribe(input =>
            {
                var frustum = new Frustum(OrbitCamera, Intrinsics.ImageSize);

                var plane = new Plane(Vector3.UnitZ, 0);

                var p0 = frustum.IntersectWithPlane(ProjectorQuadCorners[0].X, ProjectorQuadCorners[0].Y, plane).ToPointF();
                var p1 = frustum.IntersectWithPlane(ProjectorQuadCorners[1].X, ProjectorQuadCorners[1].Y, plane).ToPointF();
                var p2 = frustum.IntersectWithPlane(ProjectorQuadCorners[2].X, ProjectorQuadCorners[2].Y, plane).ToPointF();
                var p3 = frustum.IntersectWithPlane(ProjectorQuadCorners[3].X, ProjectorQuadCorners[3].Y, plane).ToPointF();

                var quadCorners = new[] { p0, p1, p2, p3, };

                // Chessboard.HomographTo(quadCorners);
            });
        }
 public ChessboardShapeTask(Window window, Projector projector, Chessboard chessboard)
     : base(window)
 {
     Projector = projector;
     Chessboard = chessboard;
     ColoredChessboard = new ColoredChessboard(Chessboard, Color.Black, Color.White);
     LoadOrDefault(projector.Window.ClientSize);
 }
        public CalibrateIndirectlyTask(Window window, IEnumerable<CaptureCamera> captureCameras, Projector projector, Chessboard chessboard)
            : base(window)
        {
            CaptureCameras = captureCameras;
            Chessboard = chessboard;
            Projector = projector;

            ProjectorQuadCorners = Chessboard.GetDefaultImageQuadCorners(projector.Window.ClientSize);
            WorldToProjectorHom = Chessboard.GetHomographyTo(ProjectorQuadCorners);
            ColoredChessboard = new ColoredChessboard(Chessboard, Color.Black, Color.White, WorldToProjectorHom.ToMatrixFromHomogeneous3x3());

            Circles = Chessboard.Saddles.Select(s => new Circle2D(s.ToVector3(z: 0.01f), 10, 4, Color.Crimson) { AlreadyInScreenSpace = false } ).ToList();
        }
Exemple #6
0
 public List<square> GetNeighbours(Chessboard _Board)
 {
     List<square> neighs = new List<square>();
     for (int iColDelta = -1; iColDelta <= 1; iColDelta++)
         for (int iRowDelta = -1; iRowDelta <= 1; iRowDelta++)
     {
         if (iColDelta == 0 && iRowDelta == 0) // don’t check yourself
             continue;
         int iNeighCol = m_iCol + iColDelta;
         int iNeighRow = m_iRow + iRowDelta;
         if  (iNeighCol >= 0 && iNeighCol < _Board.m_iSize &&
              iNeighRow >= 0 && iNeighRow < _Board.m_iSize)
                 neighs.Add(_Board.GetSquare(iNeighCol, iNeighRow));
     }
     return neighs;
 }
Exemple #7
0
            public void StartNewGame()
            {
                redPlayer = new Player(this, Players.Red, takenChessmenPic, lostChessmenPic, "Красный игрок");
                yellowPlayer = new Player(this, Players.Yellow, takenChessmenPic, lostChessmenPic, "Желтый игрок");
                redPlayer.SetAlly(yellowPlayer);
                yellowPlayer.SetAlly(redPlayer);
                blackPlayer = new Player(this, Players.Black, takenChessmenPic, lostChessmenPic, "Черный игрок");
                bluePlayer = new Player(this, Players.Blue, takenChessmenPic, lostChessmenPic, "Синий игрок");
                blackPlayer.SetAlly(bluePlayer);
                bluePlayer.SetAlly(blackPlayer);
                //dopilit'
                turn = Players.Black;
                ToggleTurn();

                logTurn = "";
                logBuffer = "";
                chessboard = new Chessboard(this, 0, 0, chessboardPic.Width, chessboardPic.Height, arrangement);
                chessboard.SetStatusBar(statusBar);
                chessboardPic.MouseClick -= chessboardPic_MouseClick;
                chessboardPic.MouseClick += chessboardPic_MouseClick;
                chessboardPic.MouseMove -= chessboardPic_MouseMove;
                chessboardPic.MouseMove += chessboardPic_MouseMove;
                surrenderButton.Click -= surrenderButton_Click;
                surrenderButton.Click += surrenderButton_Click;
                prisonersChangeButton.Click -= prisonersChangeButton_Click;
                prisonersChangeButton.Click += prisonersChangeButton_Click;
                chessboard.ShowChessboard(chessboardPic);
                numberOfTurn = 1;
                //dopilit'
            }
Exemple #8
0
        public override Chessboard GenerateBoard()
        {
            Chessboard board = new Chessboard(8, 8, this);

            board[new Coordinate(0, 0)] = new Rook {
                Color = TeamColor.White
            };
            board[new Coordinate(1, 0)] = new Knight {
                Color = TeamColor.White
            };
            board[new Coordinate(2, 0)] = new Bishop {
                Color = TeamColor.White
            };
            board[new Coordinate(3, 0)] = new Queen {
                Color = TeamColor.White
            };
            board[new Coordinate(4, 0)] = new King {
                Color = TeamColor.White
            };
            board[new Coordinate(5, 0)] = new Bishop {
                Color = TeamColor.White
            };
            board[new Coordinate(6, 0)] = new Knight {
                Color = TeamColor.White
            };
            board[new Coordinate(7, 0)] = new Rook {
                Color = TeamColor.White
            };

            board[new Coordinate(0, 1)] = new Pawn {
                Color = TeamColor.White
            };
            board[new Coordinate(1, 1)] = new Pawn {
                Color = TeamColor.White
            };
            board[new Coordinate(2, 1)] = new Pawn {
                Color = TeamColor.White
            };
            board[new Coordinate(3, 1)] = new Pawn {
                Color = TeamColor.White
            };
            board[new Coordinate(4, 1)] = new Pawn {
                Color = TeamColor.White
            };
            board[new Coordinate(5, 1)] = new Pawn {
                Color = TeamColor.White
            };
            board[new Coordinate(6, 1)] = new Pawn {
                Color = TeamColor.White
            };
            board[new Coordinate(7, 1)] = new Pawn {
                Color = TeamColor.White
            };

            board[new Coordinate(0, 7)] = new Rook {
                Color = TeamColor.Black
            };
            board[new Coordinate(1, 7)] = new Knight {
                Color = TeamColor.Black
            };
            board[new Coordinate(2, 7)] = new Bishop {
                Color = TeamColor.Black
            };
            board[new Coordinate(3, 7)] = new Queen {
                Color = TeamColor.Black
            };
            board[new Coordinate(4, 7)] = new King {
                Color = TeamColor.Black
            };
            board[new Coordinate(5, 7)] = new Bishop {
                Color = TeamColor.Black
            };
            board[new Coordinate(6, 7)] = new Knight {
                Color = TeamColor.Black
            };
            board[new Coordinate(7, 7)] = new Rook {
                Color = TeamColor.Black
            };

            board[new Coordinate(0, 6)] = new Pawn {
                Color = TeamColor.Black
            };
            board[new Coordinate(1, 6)] = new Pawn {
                Color = TeamColor.Black
            };
            board[new Coordinate(2, 6)] = new Pawn {
                Color = TeamColor.Black
            };
            board[new Coordinate(3, 6)] = new Pawn {
                Color = TeamColor.Black
            };
            board[new Coordinate(4, 6)] = new Pawn {
                Color = TeamColor.Black
            };
            board[new Coordinate(5, 6)] = new Pawn {
                Color = TeamColor.Black
            };
            board[new Coordinate(6, 6)] = new Pawn {
                Color = TeamColor.Black
            };
            board[new Coordinate(7, 6)] = new Pawn {
                Color = TeamColor.Black
            };

            return(board);
        }
Exemple #9
0
        public override void SolveProblem(Chessboard chessBoard)
        {
            int    sizeOfSingleGeneration = chessBoard.Parameters.SizeOfSingleGeneration;
            double percentOfElitism       = chessBoard.Parameters.PercentOfElitism / 100;
            double crossoverProbability   = chessBoard.Parameters.CrossoverProbability / 100;
            double mutationProbability    = chessBoard.Parameters.MutationProbability / 100;
            int    numberOfGenerations    = chessBoard.Parameters.NumberOfGenerations;

            int boardSize = chessBoard.Size;
            int steps     = 0;

            var generation = new List <ChessPiece[, ]>(); // generation -> list of states

            // generate initial generation
            for (int i = 0; i < sizeOfSingleGeneration; i++)
            {
                var generatedState = this.GenerateRandomBoardState(boardSize);
                generation.Add(generatedState);
            }

            var bestState  = chessBoard.Board;
            int bestResult = chessBoard.HeuristicResult;

            // N iterations
            for (int i = 0; i < numberOfGenerations; i++)
            {
                // calculate h for each state and find the best
                bestState  = ReturnBestState(generation, boardSize);
                bestResult = Heuristic(bestState, boardSize);
                if (bestResult == 0)
                {
                    break;
                }

                var newGeneration = new List <ChessPiece[, ]>();
                SortListOfStates(generation, boardSize);
                // best best m << k are copied into next generation
                var elite = GetElite(generation, percentOfElitism);
                newGeneration = elite;

                while (newGeneration.Count != sizeOfSingleGeneration)
                {
                    // 1. Selection
                    ChessPiece[,] chromosome1 = SelectChromosome(generation);
                    ChessPiece[,] chromosome2 = SelectChromosome(generation);

                    // 2. Crossover
                    Crossover(chromosome1, chromosome2, boardSize, crossoverProbability);
                    // 3. Mutation
                    Mutation(chromosome1, chromosome2, boardSize, mutationProbability);

                    newGeneration.Add(chromosome1);
                    newGeneration.Add(chromosome2);
                }

                steps++;
                generation = newGeneration;
            }

            bestState  = ReturnBestState(generation, boardSize);
            bestResult = Heuristic(bestState, boardSize);

            chessBoard.Steps           = steps;
            chessBoard.Board           = bestState;
            chessBoard.HeuristicResult = bestResult;
        }
Exemple #10
0
 public Bishop(PlayerColor color, Cell cell, Chessboard chessboard) : base(PieceType.Bishop, color, cell, chessboard)
 {
 }
 protected override bool IsValidRule(
     PieceBase piece,
     Position newPosition,
     Chessboard chessboard) => chessboard
 .GetPiece(newPosition)
 .Fold(true)(otherPiece => !piece.SameColor(otherPiece));
Exemple #12
0
 public CalibrateTask(Window window, Camera camera, Chessboard chessboard)
     : base(window)
 {
     Camera = camera;
     Chessboard = chessboard;
 }
 private static IExpectedResultStep MoveTo(Chessboard chessboard)
 {
     return(ValidateMoveTestDataBuilder.ForChessPiece(ChessPiece).MoveTo(chessboard));
 }
Exemple #14
0
 public Bishop(Chessboard chessboard, Color color) : base(chessboard, color)
 {
 }
Exemple #15
0
        /// <inheritdoc/>
        public IEnumerable <Move> GetMoves(Piece piece, Coordinate position, Chessboard board, bool guardedSquaresOnly = false)
        {
            // The 4 directions from the piece.
            for (int n = 0; n < 4; n++)
            {
                // Sets a direction for the checker
                int xDir = 1;
                int yDir = 1;
                switch (n)
                {
                case 0:
                    xDir = 1;
                    yDir = 0;
                    break;

                case 1:
                    xDir = -1;
                    yDir = 0;
                    break;

                case 2:
                    xDir = 0;
                    yDir = 1;
                    break;

                case 3:
                    xDir = 0;
                    yDir = -1;
                    break;

                default:
                    break;
                }

                // Checker
                for (int i = 1; i < board.Height * board.Width; i++)
                {
                    // Position update
                    Coordinate checkPosition = new Coordinate((i * xDir) + position.File, (i * yDir) + position.Rank);

                    // If the checking position is outside of the board.
                    if (checkPosition.Rank >= board.Height || checkPosition.Rank < 0 ||
                        checkPosition.File >= board.Width || checkPosition.File < 0)
                    {
                        break;
                    }

                    // whether the position is occupied.
                    Piece occupyingPiece = board.GetPiece(checkPosition);

                    // is position empty?
                    if (occupyingPiece is null)
                    {
                        yield return(new Move(checkPosition, position, piece, false, piece.Color));

                        continue;
                    }
                    else if (guardedSquaresOnly) // if not empty
                    {
                        yield return(new Move(checkPosition, position, piece, false, piece.Color));

                        break;
                    }

                    // There is a enemy piece
                    if (occupyingPiece.Color != piece.Color || guardedSquaresOnly)
                    {
                        // Sends the move.
                        yield return(new Move(checkPosition, position, piece, true, piece.Color));
                    }

                    break;
                }
            }
        }
        private async Task <IActionResult> ProcessStep(SkillRequest request, Coordinates coords)
        {
            Session session = request.Session;
            var     state   = new State(Database.Context, session);

            Logger.LogInformation(LoggingEvents.Game, "User reaches coordinates {0}", coords);
            Logger.LogTrace(LoggingEvents.Game, "{0} moves, last reached {1}", state.MovesCount, state.LastReached);

            if (!coords.IsValid)
            {
                // Something went wrong
                Logger.LogError(LoggingEvents.Game, "Invalid coordinates");

                var response = ResponseBuilder.Ask(
                    new SsmlOutputSpeech {
                    Ssml = @"<speak>Non ho capito. Ripeti le coordinate per favore.</speak>"
                },
                    new Reprompt {
                    OutputSpeech = new SsmlOutputSpeech {
                        Ssml = @"<speak>Quali sono le <emphasis level=""moderate"">coordinate</emphasis> dello spazio in cui ti trovi?</speak>"
                    }
                }
                    );
                return(Ok(response));
            }

            if (state.IsSessionStart)
            {
                // First position, can ignore direction
                if (Chessboard.IsStartPosition(coords))
                {
                    Direction startDir = Chessboard.GetStartDirection(coords);
                    Logger.LogDebug(LoggingEvents.Game, "User in {0} should look towards {1}", coords, startDir);

                    Coordinates effectiveTarget = new Coordinates(coords.Column, coords.Row, startDir);
                    state.RecordDestination(effectiveTarget, true);

                    if (effectiveTarget.Direction != coords.Direction)
                    {
                        // Hint at correct direction
                        var progResp = new ProgressiveResponse(request);
                        await progResp.SendSpeech(string.Format(
                                                      "OK. Sei in {0}, {1}. Assicurati di girarti verso {2}.",
                                                      effectiveTarget.Column.FromColumnIndex(),
                                                      effectiveTarget.Row,
                                                      effectiveTarget.Direction.Value.ToLocale()
                                                      ));

                        coords = effectiveTarget;
                    }
                }
                else
                {
                    Logger.LogDebug(LoggingEvents.Game, "User in {0}, not a valid starting position", coords);

                    return(Ok(ResponseBuilder.Ask("Devi partire in uno spazio sul bordo della scacchiera. Spostati e dimmi dove sei.", null)));
                }
            }
            else if (!coords.Direction.HasValue)
            {
                // Not first position, requires direction:
                // register coordinates in session and ask for direction
                if (session.Attributes == null)
                {
                    session.Attributes = new Dictionary <string, object>();
                }
                session.Attributes["row"] = coords.Row;
                session.Attributes["col"] = coords.Column;

                var response = ResponseBuilder.Ask(
                    new SsmlOutputSpeech {
                    Ssml = @"<speak>OK. In che direzione stai guardando?</speak>"
                },
                    new Reprompt {
                    OutputSpeech = new SsmlOutputSpeech {
                        Ssml = @"<speak>Dimmi in che <emphasis level=""moderate"">direzione</emphasis> stai guardando.</speak>"
                    }
                },
                    session
                    );
                return(Ok(response));
            }

            session.Attributes = new Dictionary <string, object>(); // clean up session attributes

            // Check for destination to reach
            var destination = state.LastDestination;

            if (destination.HasValue)
            {
                if (destination.Value.Equals(coords))
                {
                    Logger.LogInformation(LoggingEvents.Game, "Correct cell");

                    state.ReachDestination();

                    var progResp = new ProgressiveResponse(request);
                    await progResp.SendSpeech("Sei nel posto giusto!");
                }
                else if (destination.Value.LocationEquals(coords))
                {
                    Logger.LogInformation(LoggingEvents.Game, "Wrong direction, expected {0}", destination.Value);

                    var response = ResponseBuilder.Ask("Stai guardando nella direzione sbagliata. Riprova.", null, session);
                    return(Ok(response));
                }
                else
                {
                    Logger.LogInformation(LoggingEvents.Game, "Wrong cell, expected {0}", destination.Value);

                    var response = ResponseBuilder.Ask("Purtroppo sei nella casella sbagliata. Riprova.", null, session);
                    return(Ok(response));
                }
            }

            if (state.MovesCount >= Chessboard.MaxLevel)
            {
                Logger.LogInformation(LoggingEvents.Game, "User completed last level");

                return(Ok(ResponseBuilder.Tell(
                              new SsmlOutputSpeech {
                    Ssml = @"<speak>Complimenti! Hai completato <emphasis level=""moderate"">Cody Maze</emphasis> con successo.</speak>"
                }
                              )));
            }

            // Assign new destination
            Logger.LogInformation(LoggingEvents.Game, "Generating new destination (step {0})", state.MovesCount);
            (var mazeDestination, var instructions) = Chessboard.GenerateMazeForLevel(coords, state.MovesCount);
            if (!mazeDestination.IsValid)
            {
                Logger.LogError(LoggingEvents.Game, "Invalid coordinates generated for maze level {0}", state.MovesCount);
                return(await InternalError());
            }
            state.RecordDestination(mazeDestination);

            return(Ok(ResponseBuilder.Ask(
                          new SsmlOutputSpeech {
                Ssml = string.Format(
                    @"<speak>Esegui le seguenti istruzioni{1}. <emphasis level=""strong"">{0}</emphasis>.</speak>",
                    instructions,
                    (state.MovesCount <= 2) ? " e poi dimmi le tue coordinate e direzione" : string.Empty
                    )
            }, new Reprompt {
                OutputSpeech = new SsmlOutputSpeech {
                    Ssml = string.Format(
                        @"<speak>Esegui le istruzioni. <emphasis level=""strong"">{0}</emphasis>.</speak>",
                        instructions
                        )
                }
            },
                          session
                          )));
        }
        private Task <IActionResult> ProcessHelpAndBacktrack(SkillRequest request, IntentRequest intent)
        {
            Logger.LogInformation(LoggingEvents.Game, "Help request received");

            Session session = request.Session;
            var     state   = new State(Database.Context, session);

            session.Attributes = new Dictionary <string, object>(); // clean up session attributes

            if (state.IsSessionStart)
            {
                return(Task.FromResult <IActionResult>(
                           Ok(ResponseBuilder.Ask(
                                  "Dopo aver preparato la scacchiera, posizionati in uno degli spazi sul bordo. Poi dimmi dove ti trovi, specificando colonna e poi riga.",
                                  null,
                                  session
                                  ))
                           ));
            }
            else
            {
                var coords = state.LastReached;
                if (!coords.HasValue)
                {
                    Logger.LogError(LoggingEvents.Game, "Cannot find last reached position for user");
                    return(InternalError());
                }

                (var mazeDestination, var instructions) = Chessboard.GenerateMazeForLevel(coords.Value, state.MovesCount - 1);
                if (!mazeDestination.IsValid || state.LastDestination != mazeDestination)
                {
                    Logger.LogError(LoggingEvents.Game, "Regenerated destination for maze level {0} is {1} instead of previously generated {2}", state.MovesCount, mazeDestination, state.LastDestination);
                    return(InternalError());
                }

                return(Task.FromResult <IActionResult>(
                           Ok(ResponseBuilder.Ask(
                                  new SsmlOutputSpeech {
                    Ssml = string.Format(
                        @"<speak>Torna alla casella <emphasis level=""strong"">{0}, {1},</emphasis> e girati verso {2}. Poi esegui le istruzioni: <emphasis level=""strong"">{3}</emphasis>.</speak>",
                        coords.Value.Column.FromColumnIndex(),
                        coords.Value.Row,
                        coords.Value.Direction.Value.ToLocale(),
                        instructions
                        )
                }, new Reprompt {
                    OutputSpeech = new SsmlOutputSpeech {
                        Ssml = string.Format(
                            @"<speak>Parti da <emphasis level=""strong"">{0}, {1},</emphasis> verso {2}. Esegui le istruzioni: <emphasis level=""strong"">{3}</emphasis>.</speak>",
                            coords.Value.Column.FromColumnIndex(),
                            coords.Value.Row,
                            coords.Value.Direction.Value.ToLocale(),
                            instructions
                            )
                    }
                },
                                  session
                                  ))
                           ));
            }
        }
 public bool IsGameFinished(Chessboard chessboard, GameHistory gameHistory, ChessColor lastTurnBy)
 {
     return(!GetAvailableMoves(chessboard, lastTurnBy.GetOppositeChessColor(), gameHistory).Any() ||
            gameHistory.IsPositionRepeatedThreeTimes);
 }
Exemple #19
0
        public override List <Cell> CouldMenace(Chessboard board, Cell point)
        {
            var menacing = new List <Cell>();

            var nP = point.NewWithOffset(-2, -1);
            var cs = board.GetCellState(nP, team);

            if (cs != CellState.invalidPos)
            {
                menacing.Add(nP);
            }

            nP = point.NewWithOffset(-1, -2);
            cs = board.GetCellState(nP, team);
            if (cs != CellState.invalidPos)
            {
                menacing.Add(nP);
            }

            nP = point.NewWithOffset(+2, -1);
            cs = board.GetCellState(nP, team);
            if (cs != CellState.invalidPos)
            {
                menacing.Add(nP);
            }

            nP = point.NewWithOffset(-1, +2);
            cs = board.GetCellState(nP, team);
            if (cs != CellState.invalidPos)
            {
                menacing.Add(nP);
            }

            nP = point.NewWithOffset(+1, -2);
            cs = board.GetCellState(nP, team);
            if (cs != CellState.invalidPos)
            {
                menacing.Add(nP);
            }

            nP = point.NewWithOffset(-2, +1);
            cs = board.GetCellState(nP, team);
            if (cs != CellState.invalidPos)
            {
                menacing.Add(nP);
            }

            nP = point.NewWithOffset(+1, +2);
            cs = board.GetCellState(nP, team);
            if (cs != CellState.invalidPos)
            {
                menacing.Add(nP);
            }

            nP = point.NewWithOffset(+2, +1);
            cs = board.GetCellState(nP, team);
            if (cs != CellState.invalidPos)
            {
                menacing.Add(nP);
            }

            return(menacing);
        }
Exemple #20
0
        public override List <Move> Moves(Chessboard board, Cell position)
        {
            var moves = new List <Move>();

            var nP = position.NewWithOffset(-2, -1);
            var cs = board.GetCellState(nP, team);

            if (cs != CellState.invalidPos && cs != CellState.ally)
            {
                moves.Add(new Move {
                    piece = this, from = position, to = nP
                });
            }

            nP = position.NewWithOffset(-1, -2);
            cs = board.GetCellState(nP, team);
            if (cs != CellState.invalidPos && cs != CellState.ally)
            {
                moves.Add(new Move {
                    piece = this, from = position, to = nP
                });
            }

            nP = position.NewWithOffset(+2, -1);
            cs = board.GetCellState(nP, team);
            if (cs != CellState.invalidPos && cs != CellState.ally)
            {
                moves.Add(new Move {
                    piece = this, from = position, to = nP
                });
            }

            nP = position.NewWithOffset(-1, +2);
            cs = board.GetCellState(nP, team);
            if (cs != CellState.invalidPos && cs != CellState.ally)
            {
                moves.Add(new Move {
                    piece = this, from = position, to = nP
                });
            }

            nP = position.NewWithOffset(+1, -2);
            cs = board.GetCellState(nP, team);
            if (cs != CellState.invalidPos && cs != CellState.ally)
            {
                moves.Add(new Move {
                    piece = this, from = position, to = nP
                });
            }

            nP = position.NewWithOffset(-2, +1);
            cs = board.GetCellState(nP, team);
            if (cs != CellState.invalidPos && cs != CellState.ally)
            {
                moves.Add(new Move {
                    piece = this, from = position, to = nP
                });
            }

            nP = position.NewWithOffset(+1, +2);
            cs = board.GetCellState(nP, team);
            if (cs != CellState.invalidPos && cs != CellState.ally)
            {
                moves.Add(new Move {
                    piece = this, from = position, to = nP
                });
            }

            nP = position.NewWithOffset(+2, +1);
            cs = board.GetCellState(nP, team);
            if (cs != CellState.invalidPos && cs != CellState.ally)
            {
                moves.Add(new Move {
                    piece = this, from = position, to = nP
                });
            }

            return(moves);
        }
Exemple #21
0
 public YellowPawn(ChessmenParameters chessmanParameters, Chessboard chessboard)
     : base(chessmanParameters, chessboard)
 {
 }
Exemple #22
0
        private bool CanMove(Position position)
        {
            ChessPiece cp = Chessboard.ChessPiece(position);

            return(cp == null || cp.Color != Color);
        }
Exemple #23
0
 private Chessman GetNewCorrectPawn(ChessmenParameters chessmanParameters, Chessboard chessboard)
 {
     Chessman result;
     switch ((int)chessmanParameters.player)
     {
         case 0: result = new YellowPawn(chessmanParameters, chessboard);
             break;
         case 1: result = new RedPawn(chessmanParameters, chessboard);
             break;
         case 2: result = new BluePawn(chessmanParameters, chessboard);
             break;
         case 3: result = new BlackPawn(chessmanParameters, chessboard);
             break;
         default:
             {
                 result = null;
                 break;
             }
     }
     return result;
 }
Exemple #24
0
 public Bishop(Color color, Chessboard chessboard) : base(color, chessboard)
 {
 }
 private static IExpectedChessboardStateStep WithInitialChessboardState(Chessboard chessboard)
 {
     return(PieceMoveTestDataBuilder.ForChessPiece(ChessPiece).WithInitialChessboardState(chessboard));
 }
Exemple #26
0
 public BlackPawn(ChessMatchState chessGameState, Chessboard chessboard)
     : base(chessGameState, chessboard)
 {
 }
Exemple #27
0
        private List <Chessboard> ChangeBoard(int size, int numberOfStates, List <Chessboard> chessboardStates, Chessboard chessboard)
        {
            for (int n = 0; n < numberOfStates; n++)
            {
                int[] compareArray   = new int[size];
                int[] heuristicArray = new int[size];
                chessboardStates[n].GetQueensPlacament().CopyTo(compareArray, 0);

                //in each iteration of for loop given chessboard will be moved to it's best possible state
                chessboardStates[n].SetQueensPlacement(MoveQueensInChessboard(chessboardStates[n].GetQueensPlacament(), size, heuristicArray));


                //If array wasn't changed it will be replaced by a new random one
                if (ArrayNotChanged(chessboardStates[n].GetQueensPlacament(), compareArray))
                {
                    chessboard.FillWithRandomPlacements();
                    chessboardStates[n].SetQueensPlacement(chessboard.GetQueensPlacament());
                }
            }
            return(chessboardStates);
        }
Exemple #28
0
        private bool CanMove(Position position)
        {
            var piece = Chessboard.GetPiece(position);

            return(piece == null || piece.Color != this.Color);
        }
Exemple #29
0
        static void Main(string[] args)
        {
            var     p1     = new Player("Matteo");
            var     p2     = new PlayerMediumComputer("CPU1");
            IPlayer toMove = p1;

            int xs, ys, xe, ye;
            var b = new Chessboard(p1, p2);

            do
            {
                try{
                    Console.Clear();
                    Console.WriteLine(b.ToString());

                    Console.WriteLine("Turn: {0}", toMove.Name);

                    Console.WriteLine("Let move from...");
                    Console.Write("V:");
                    xs = int.Parse(Console.ReadLine());
                    Console.WriteLine();
                    Console.Write("H:");
                    ys = int.Parse(Console.ReadLine());

                    Console.WriteLine("Let move to...");
                    Console.Write("V:");
                    xe = int.Parse(Console.ReadLine());
                    Console.WriteLine();
                    Console.Write("H:");
                    ye = int.Parse(Console.ReadLine());

                    b.MovePawn(toMove, xs, ys, xe, ye);

                    if (toMove == p1)
                    {
                        toMove = p2;
                    }
                    else
                    {
                        toMove = p1;
                    }
                }catch (Exception e) {
                    Console.WriteLine(e.Message);
                    Console.WriteLine("Press to continue...");
                    Console.ReadLine();
                }
            } while (b.Winner == null);

            Console.WriteLine("Press to simulate legal move (5,1) -> (4,2)...");
            Console.ReadLine();

            b.MovePawn(p2, 5, 1, 4, 2);

            Console.WriteLine(b.ToString());

            Console.WriteLine("Press to simulate play...");
            Console.ReadLine();

            b.SimulatePlay();

            Console.WriteLine("Winner is {0} with score {1}", b.Winner.Name, b.Winner.Score);
            Console.WriteLine("Loser is {0} with score {1}", b.Loser.Name, b.Loser.Score);
        }
Exemple #30
0
        private bool TestRookForCastling(Position position)
        {
            var piece = Chessboard.GetPiece(position);

            return(piece != null && piece is Rook && piece.Color == Color && piece.Moves == 0);
        }
Exemple #31
0
 protected WhitePiece(ChessMatchState chessGameState, Chessboard chessboard)
     : base(chessGameState, ChessPlayer.White, chessboard)
 {
 }
Exemple #32
0
        public override bool[,] PossibleMoves()
        {
            bool[,] matrix = new bool[Chessboard.Lines, Chessboard.Columns];

            var position = new Position(0, 0);

            // N
            position.SetValues(Position.Line - 1, Position.Column);
            if (Chessboard.ValidPosition(position) && CanMove(position))
            {
                matrix[position.Line, position.Column] = true;
            }

            // NE
            position.SetValues(Position.Line - 1, Position.Column + 1);
            if (Chessboard.ValidPosition(position) && CanMove(position))
            {
                matrix[position.Line, position.Column] = true;
            }

            // E
            position.SetValues(Position.Line, Position.Column + 1);
            if (Chessboard.ValidPosition(position) && CanMove(position))
            {
                matrix[position.Line, position.Column] = true;
            }

            // SE
            position.SetValues(Position.Line + 1, Position.Column + 1);
            if (Chessboard.ValidPosition(position) && CanMove(position))
            {
                matrix[position.Line, position.Column] = true;
            }

            // S
            position.SetValues(Position.Line + 1, Position.Column);
            if (Chessboard.ValidPosition(position) && CanMove(position))
            {
                matrix[position.Line, position.Column] = true;
            }

            // SW
            position.SetValues(Position.Line + 1, Position.Column - 1);
            if (Chessboard.ValidPosition(position) && CanMove(position))
            {
                matrix[position.Line, position.Column] = true;
            }

            // W
            position.SetValues(Position.Line, Position.Column - 1);
            if (Chessboard.ValidPosition(position) && CanMove(position))
            {
                matrix[position.Line, position.Column] = true;
            }

            // NW
            position.SetValues(Position.Line - 1, Position.Column - 1);
            if (Chessboard.ValidPosition(position) && CanMove(position))
            {
                matrix[position.Line, position.Column] = true;
            }

            if (Moves == 0 && !game.Mate)
            {
                // Roque Pequeno #SpecialMove
                var firstPosition = new Position(Position.Line, Position.Column + 3);
                if (TestRookForCastling(firstPosition))
                {
                    var positionOne = new Position(Position.Line, Position.Column + 1);
                    var positionTwo = new Position(Position.Line, Position.Column + 2);
                    if (Chessboard.GetPiece(positionOne) == null && Chessboard.GetPiece(positionTwo) == null)
                    {
                        matrix[Position.Line, Position.Column + 2] = true;
                    }
                }
                // Roque Grande #SpecialMove
                var secondPosition = new Position(Position.Line, Position.Column - 4);
                if (TestRookForCastling(secondPosition))
                {
                    var positionOne   = new Position(Position.Line, Position.Column - 1);
                    var positionTwo   = new Position(Position.Line, Position.Column - 2);
                    var positionThree = new Position(Position.Line, Position.Column - 3);
                    if (Chessboard.GetPiece(positionOne) == null && Chessboard.GetPiece(positionTwo) == null && Chessboard.GetPiece(positionThree) == null)
                    {
                        matrix[Position.Line, Position.Column - 2] = true;
                    }
                }
            }

            return(matrix);
        }
 internal ValidatorBaseTests(ValidatorBase validator, IReadOnlyCollection <PieceBase> pieces)
 {
     this.validator  = validator;
     this.chessboard = new List <PieceBase>(pieces);
 }
Exemple #34
0
 public King(Chessboard chessboard, Color color, ChessGame game) : base(chessboard, color)
 {
     this.game = game;
 }
Exemple #35
0
 public Bishop(ChessmenParameters chessmanParameters, Chessboard chessboard)
     : base(chessmanParameters, chessboard)
 {
 }
Exemple #36
0
 public BlackKnight(ChessMatchState chessGameState, Chessboard chessboard)
     : base(chessGameState, chessboard)
 {
 }
Exemple #37
0
            public King(ChessmenParameters chessmanParameters, Chessboard chessboard)
                : base(chessmanParameters, chessboard)
            {
                if (horizontal == 9)
                {
                    horizontal = 8;
                    graphHorizontal = 9;
                }
                else
                {
                    if (horizontal == 0)
                    {
                        horizontal = 1;
                        graphHorizontal = 0;
                    }
                    else
                    {
                        graphHorizontal = horizontal;
                    }
                }

                if (vertical == 9)
                {
                    vertical = 8;
                    graphVertical = 9;
                }
                else
                {
                    if (vertical == 0)
                    {
                        vertical = 1;
                        graphVertical = 0;
                    }
                    else
                    {
                        graphVertical = vertical;
                    }
                }
            }
        private void Save(Chessboard chessboard, Vector3[] fourImageCorners)
        {
            var df = new DictionaryFile();

            df.Set("tileCount.Width", chessboard.TileCount.Width);
            df.Set("tileCount.Height", chessboard.TileCount.Height);

            df.Set("imageCorner0.X", fourImageCorners[0].X);
            df.Set("imageCorner0.Y", fourImageCorners[0].Y);
            df.Set("imageCorner1.X", fourImageCorners[1].X);
            df.Set("imageCorner1.Y", fourImageCorners[1].Y);
            df.Set("imageCorner2.X", fourImageCorners[2].X);
            df.Set("imageCorner2.Y", fourImageCorners[2].Y);
            df.Set("imageCorner3.X", fourImageCorners[3].X);
            df.Set("imageCorner3.Y", fourImageCorners[3].Y);

            using (var sw = File.CreateText(FourCornersPath))
                df.Save(sw);
        }
Exemple #39
0
            /* Numbers of chessmen are: 0 - King, 1 - Queen, 2 - Bishop, 3 - Knight, 4 - Tower,
             * 5 - Pawn of Queen, 6 - Pawn of Bishop, 7 - Pawn of Knight, 8 - Pawn of Tower.
             * Numbers of players are: 0 - Yellow, 1 - Red, 2 - Blue, 3 - Black.
             * Number of arrangement - numberOfArrangement. */
            public Chessman CreateNewChessman(string playersColor, string chessmanName, Chessboard chessboard)
            {
                int indexOfPlayer = -1;
                int indexOfChessman = -1;
                ChessmenParameters chessmanParam = new ChessmenParameters();
                Chessman result;
                //gets number of player
                switch (playersColor)
                {
                    case "Yellow": indexOfPlayer = 0;
                        break;
                    case "Red": indexOfPlayer = 1;
                        break;
                    case "Blue": indexOfPlayer = 2;
                        break;
                    case "Black": indexOfPlayer = 3;
                        break;
                    default:
                        {
                            MessageBox.Show("Внутренняя ошибка, невозможно выполнить действие");
                            return null;
                        }
                }

                //gets number of chessman
                switch (chessmanName)
                {
                    case "King": indexOfChessman = 0;
                        break;
                    case "Queen": indexOfChessman = 1;
                        break;
                    case "Bishop": indexOfChessman = 2;
                        break;
                    case "Knight": indexOfChessman = 3;
                        break;
                    case "Tower": indexOfChessman = 4;
                        break;
                    case "PawnOfQueen": indexOfChessman = 5;
                        chessmanName = "Pawn of Queen";
                        break;
                    case "PawnOfBishop": indexOfChessman = 6;
                        chessmanName = "Pawn of Bishop";
                        break;
                    case "PawnOfKnight": indexOfChessman = 7;
                        chessmanName = "Pawn of Knight";
                        break;
                    case "PawnOfTower": indexOfChessman = 8;
                        chessmanName = "Pawn of Tower";
                        break;
                    default:
                        {
                            MessageBox.Show("Внутренняя ошибка, невозможно выполнить действие");
                            return null;
                        }
                }

                //set parameters
                chessmanParam.horizontal = positionOfChessmen[numberOfArrangement, indexOfPlayer, indexOfChessman, 1];
                chessmanParam.vertical = positionOfChessmen[numberOfArrangement, indexOfPlayer, indexOfChessman, 0];
                chessmanParam.ruNameNominative = GetNominativeRu(indexOfPlayer, indexOfChessman);
                chessmanParam.engName = playersColor + ' ' + chessmanName;
                chessmanParam.chessmanBitmap = chessmanBitmap[indexOfPlayer, indexOfChessman];
                chessmanParam.ruNameAccusative = GetAccusativeRu(indexOfPlayer, indexOfChessman);
                chessmanParam.kindOfChessman = (ChessmenNames)indexOfChessman;
                chessmanParam.player = (Players)indexOfPlayer;
                chessmanParam.ruAttack = GetAttackRu(indexOfChessman);
                chessmanParam.ruMove = GetMoveRu(indexOfChessman);
                switch (indexOfChessman)
                {
                    case 0: result = new King(chessmanParam, chessboard);
                        break;
                    case 1: result = new Queen(chessmanParam, chessboard);
                        break;
                    case 2: result = new Bishop(chessmanParam, chessboard);
                        break;
                    case 3: result = new Knight(chessmanParam, chessboard);
                        break;
                    case 4: result = new Tower(chessmanParam, chessboard);
                        break;
                    case 5: result = GetNewCorrectPawn(chessmanParam, chessboard);
                        break;
                    case 6: result = GetNewCorrectPawn(chessmanParam, chessboard);
                        break;
                    case 7: result = GetNewCorrectPawn(chessmanParam, chessboard);
                        break;
                    case 8: result = GetNewCorrectPawn(chessmanParam, chessboard);
                        break;
                    default:
                        {
                            result = null;
                            break;
                        }
                }
                return result;
            }
        private static void Save(Chessboard chessboard, PointF[] projectorQuadCorners)
        {
            var df = new DictionaryFile();

            df.Set("tileCount.Width", chessboard.TileCount.Width);
            df.Set("tileCount.Height", chessboard.TileCount.Height);

            df.Set("corner0.X", projectorQuadCorners[0].X);
            df.Set("corner0.Y", projectorQuadCorners[0].Y);
            df.Set("corner1.X", projectorQuadCorners[1].X);
            df.Set("corner1.Y", projectorQuadCorners[1].Y);
            df.Set("corner2.X", projectorQuadCorners[2].X);
            df.Set("corner2.Y", projectorQuadCorners[2].Y);
            df.Set("corner3.X", projectorQuadCorners[3].X);
            df.Set("corner3.Y", projectorQuadCorners[3].Y);

            using (var sw = File.CreateText(FourCornersPath))
                df.Save(sw);
        }
Exemple #41
0
 public BluePawn(ChessmenParameters chessmanParameters, Chessboard chessboard)
     : base(chessmanParameters, chessboard)
 {
 }
Exemple #42
0
 private void OnDestroy()
 {
     Instance = null;
 }
Exemple #43
0
 public Pawn(Chessboard chessboard, Color color, ChessMatch chessMatch) : base(chessboard, color)
 {
     this.chessMatch = chessMatch;
 }
Exemple #44
0
        private static void PlayEngineGame()
        {
            Stopwatch sw = new Stopwatch();

            //Chessboard position = new Chessboard(false);
            //Chessboard position = Utils.LoadPositionFromFenString("1rbq1bnr/pp1kpppp/2p5/P1PP4/Q7/4P3/5PPP/RNB1KBNR w KQ - 0 15");
            //Chessboard position = Utils.LoadPositionFromFenString("r1k2bnr/p3pppp/8/2P5/4b3/8/3N1PPP/R1B1KBNR b KQ - 1 20"); // Castling problems
            //Chessboard position = Utils.LoadPositionFromFenString("R1rqkb1r/1Ppbpppp/7n/8/3P4/2P1P3/3N1PPP/2BQKBNR b KQkq - 2 25");
            //Chessboard position = Utils.LoadPositionFromFenString("r1bqkbnr/pppppppp/2P5/8/P2P4/2P1P3/5PPP/RNBQKBNR b KQkq - 0 12");
            //Chessboard position = Utils.LoadPositionFromFenString("1r2kbnr/pqpbpppp/8/8/3P4/2P1P3/3N1PPP/1RBQKBNR b Kk - 2 30");
            //Chessboard position = Utils.LoadPositionFromFenString("4kbnr/p1p1pppp/4b3/N7/3P4/2P1P3/5PPP/2B1KBNR b Kk 16 2 32");
            //Chessboard position = Utils.LoadPositionFromFenString("8/3nbkpp/p2rp3/8/K7/2P5/4BPPP/2B3NR w - - 10 42");
            //Chessboard position = Utils.LoadPositionFromFenString("8/8/5k2/K3R1p1/6p1/2r5/7P/6N1 w - - 10 48");
            //Chessboard position = Utils.LoadPositionFromFenString("2k2bnr/pr2pppp/2P5/8/4b3/8/3N1PPP/R1B1KBNR w KQ - 5 21");
            //Chessboard position = Utils.LoadPositionFromFenString("6r1/pk1b1pp1/2p5/2P2n1p/8/8/5PPP/2B1KBNR w K - 3 54");
            //Chessboard position = Utils.LoadPositionFromFenString("4r3/pk1b1pp1/2p5/2P2n1B/8/8/5PPP/2B1K1NR w K - 0 56"); //Problematic
            //Chessboard position = Utils.LoadPositionFromFenString("2k1b3/3r1pp1/2p4n/2P3K1/5P2/3B4/3B2PP/6NR w - - 7 70");
            //Chessboard position = Utils.LoadPositionFromFenString("4k3/7K/2p5/2P5/8/8/8/8 w - - 10 83");
            //Chessboard position = Utils.LoadPositionFromFenString("8/2kbrpp1/p1p5/2P2n2/5P2/6PB/4N2P/2B1K2R b K - 0 67");
            //Chessboard position = Utils.LoadPositionFromFenString("8/4k3/2p2pp1/p4n2/1rb2PB1/8/6PP/2B1K1NR w K - 8 81");
            //Chessboard position = Utils.LoadPositionFromFenString("4k3/1R2N1K1/8/8/8/8/8/8 b - - 4 151");
            //Chessboard position = Utils.LoadPositionFromFenString("3k4/R5K1/3N4/8/8/8/8/8 b - - 14 156");
            //Chessboard position = Utils.LoadPositionFromFenString("8/4k3/5pp1/p1p2n2/1rb2PB1/8/6PP/2B1K1NR w K - 8 81");
            //Chessboard position = Utils.LoadPositionFromFenString("8/4k3/5pp1/p1p2B2/1rb2P2/8/6PP/2B1K1NR b K - 1 82");
            //Chessboard position = Utils.LoadPositionFromFenString("8/5k2/5pp1/p1p2n2/1rb2PB1/8/6PP/2B1K1NR w K - 8 81");
            //Chessboard position = Utils.LoadPositionFromFenString("8/1k6/5pp1/p1p5/1rb2P1P/3B4/3B2P1/4K1NR b K - 12 41");
            Chessboard position = Utils.LoadPositionFromFenString("r4r1k/1bpq1p1n/p1np4/1p1Bb1BQ/P7/6R1/1P3PPP/1N2R1K1 w - - 4 28"); // Mate in 4

            //Chessboard position = Utils.LoadPositionFromFenString("4rr1k/1Ppq1p1n/2np4/3B2BQ/8/6b1/1P3PPP/1N2R1K1 b - - 8 32");
            //Chessboard position = Utils.LoadPositionFromFenString("5k2/2p4n/8/p3Q3/5r2/8/5q1P/7K b - - 17 59");
            //Chessboard position = Utils.LoadPositionFromFenString("r1b1k2r/ppppnppp/2n2q2/2b5/3NP3/2P1B3/PP3PPP/RN1QKB1R w KQkq - 5 13");
            //Chessboard position = Utils.LoadPositionFromFenString("rnb1kb1r/ppppnppp/5q2/6B1/3pP3/2N2N2/PPP2PPP/R2QKB1R b KQkq - 4 1");
            //Chessboard position = Utils.LoadPositionFromFenString("rnb1kb1r/ppppnppp/3q4/6B1/4P3/2p2N2/PPPK1PPP/R2Q1B1R w kq - 3 32");
            //Chessboard position = Utils.LoadPositionFromFenString("rnb1kb1r/3p1ppp/p2q4/1ppNn1B1/B3P3/P7/R1PQ1PPP/4NRK1 w kq 17 0 16");
            //Chessboard position = Utils.LoadPositionFromFenString("rnb1kb1r/3p1ppp/p2q4/QppNn1B1/B3P3/P7/R1P2PPP/4NRK1 b kq 17 0 16");
            //Chessboard position = Utils.LoadPositionFromFenString("r1b1k1nr/pppp1ppp/8/4P3/1P6/6P1/PP2Q2P/RNB1KBNq b KQkq - 0 6");
            //Chessboard position = Utils.LoadPositionFromFenString("1n1qkb1r/4pppp/2p3b1/3nP3/r5P1/3B3P/PPPP1P2/R1BQK2R w KQkq - 0 11");

            position.PrintBoard();

            while (true)
            {
                //try
                //{
                sw.Start();

                Search.Initialize(position, 5);

                sw.Stop();
                //}
                //catch
                //{
                //    position.PrintBoard();
                //    System.Console.WriteLine("\n\nERROR");
                //    System.Console.ReadLine();
                //}

                if (position.MaximizingSideBestMove.Direction != Direction.Castle)
                {
                    Move bestMove = new Move(
                        position.MaximizingSideBestMove.FromSquare,
                        position.MaximizingSideBestMove.ToSquare,
                        position.MaximizingSideBestMove.Direction);

                    position.MakeMove(bestMove);
                }
                else
                {
                    Move bestMove = new Move(
                        position.MaximizingSideBestMove.KingFromSquare,
                        position.MaximizingSideBestMove.KingToSquare,
                        position.MaximizingSideBestMove.RookFromSquare,
                        position.MaximizingSideBestMove.RookToSquare);

                    position.MakeMove(bestMove);
                }

                position.PrintBoard();

                System.Console.WriteLine("\n\nMove: " + position.MoveCounter);
                System.Console.WriteLine("Fifty-move rule: " + position.FiftyMoveCounter);
                System.Console.WriteLine("Hash: " + ZobristHasher.GetZobristHash(position));
                System.Console.WriteLine("Side to move: " + position.SideToMove);
                System.Console.WriteLine("EnPassant square: " + position.EnPassantSquare);
                System.Console.WriteLine("Visited nodes: " + Search.VisitedNodes);
                System.Console.WriteLine("Elapsed: " + sw.Elapsed);
                System.Console.ReadLine();

                sw.Reset();
            }
        }
Exemple #45
0
        public override void HandleKeyboardInput()
        {
            KeyboardState keyState = Keyboard.GetState();

            chessboard = (Chessboard)Game.Services.GetService(typeof(Chessboard));
            if (keyState.IsKeyDown(Keys.I))
            {
                chessboard.Blocked = true;
            }
            if (keyState.IsKeyDown(Keys.O))
            {
                chessboard.Blocked = false;
            }
            // to see if the camera is moving while switching between turns .
            if (!isLerping)
            {
                if (keyState.IsKeyDown(Keys.D1))
                {
                    changeCamera();
                }



                ///////////////////////////////////////////////////////////////////////////////////////////////////
                // do the movement for the player One
                if (isPlayerOneCamera)
                {
                    // rotate the camera position around the YAxis
                    if (keyState.IsKeyDown(Keys.A))
                    {
                        // rotate up
                        P1CurrentYRotation = Quaternion.CreateFromRotationMatrix(Matrix.CreateFromAxisAngle(P1yAxis, MathHelper.ToRadians(-1)));
                    }
                    else if (keyState.IsKeyDown(Keys.D))
                    {
                        // rotate down
                        P1CurrentYRotation = Quaternion.CreateFromRotationMatrix(Matrix.CreateFromAxisAngle(P1yAxis, MathHelper.ToRadians(1)));
                    }
                    else
                    {
                        // no rotation
                        P1CurrentYRotation = Quaternion.Identity;
                    }

                    // apply the current yRotation to the xAxis
                    P1xAxis = Vector3.Transform(P1xAxis, Matrix.CreateFromQuaternion(P1CurrentYRotation));

                    ////////////////////////////////////////
                    //perform the zoom opeeration
                    if (keyState.IsKeyDown(Keys.Z))
                    {
                        // zoom out
                        currentPlayerOnePosition = Vector3.Lerp(currentPlayerOnePosition, target, -0.02f);
                        //position = currentPlayerOnePosition;
                    }
                    if (keyState.IsKeyDown(Keys.Q))
                    {
                        // zoom in
                        currentPlayerOnePosition = Vector3.Lerp(currentPlayerOnePosition, target, 0.02f);
                        //position = currentPlayerOnePosition;
                    }

                    if (keyState.IsKeyDown(Keys.W))
                    {
                        // layer up

                        if (P1UpDown < 15)
                        {
                            P1UpDown += 0.15f;
                            currentPlayerOnePosition += new Vector3(0, 0.15f, 0);
                            target += new Vector3(0, 0.15f, 0);
                        }
                    }
                    if (keyState.IsKeyDown(Keys.S))
                    {
                        // layer down
                        if (P1UpDown > 0)
                        {
                            P1UpDown -= 0.15f;
                            currentPlayerOnePosition -= new Vector3(0, 0.15f, 0);
                            target -= new Vector3(0, 0.15f, 0);
                        }
                    }
                }
                else
                {
                    // do the movement for the player Two
                    ///////////////////////////////////////////////////////////////////////////////////////////////////
                    // rotate the camera position around the YAxis

                    if (keyState.IsKeyDown(Keys.A))
                    {
                        // rotate up
                        P2CurrentYRotation = Quaternion.CreateFromRotationMatrix(Matrix.CreateFromAxisAngle(P2yAxis, MathHelper.ToRadians(-1)));
                    }
                    else if (keyState.IsKeyDown(Keys.D))
                    {
                        // rotate down
                        P2CurrentYRotation = Quaternion.CreateFromRotationMatrix(Matrix.CreateFromAxisAngle(P2yAxis, MathHelper.ToRadians(1)));
                    }
                    else
                    {
                        // no rotation
                        P2CurrentYRotation = Quaternion.Identity;
                    }

                    // apply the current yRotation to the xAxis
                    P2xAxis = Vector3.Transform(P2xAxis, Matrix.CreateFromQuaternion(P2CurrentYRotation));

                    ////////////////////////////////////////
                    //perform the zoom opeeration
                    if (keyState.IsKeyDown(Keys.Z))
                    {
                        // zoom out
                        currentPlayerTwoPosition = Vector3.Lerp(currentPlayerTwoPosition, target, -0.02f);
                        //position = currentPlayerOnePosition;
                    }
                    if (keyState.IsKeyDown(Keys.Q))
                    {
                        // zoom in
                        currentPlayerTwoPosition = Vector3.Lerp(currentPlayerTwoPosition, target, 0.02f);
                        //position = currentPlayerOnePosition;
                    }

                    if (keyState.IsKeyDown(Keys.W))
                    {
                        // layer up
                        if (P2UpDown < 15)
                        {
                            P2UpDown += 0.15f;
                            currentPlayerTwoPosition += new Vector3(0, 0.15f, 0);
                            target += new Vector3(0, 0.15f, 0);
                        }
                    }
                    if (keyState.IsKeyDown(Keys.S))
                    {
                        // layer down
                        if (P2UpDown > 0)
                        {
                            P2UpDown -= 0.15f;
                            currentPlayerTwoPosition -= new Vector3(0, 0.15f, 0);
                            target -= new Vector3(0, 0.15f, 0);
                        }
                    }
                }
            }
            else
            {
                if (isPlayerOneCamera)
                {
                    if (!setPlayerOneCamera())
                    {
                        UpdateViewMatrix();
                    }
                    else
                    {
                        isLerping = false;
                        //limit = 0;
                    }
                }
                else
                if (!setPlayerTwoCamera())
                {
                    UpdateViewMatrix();
                }
                else
                {
                    isLerping = false;
                    //limit = 0;
                }
            }
            UpdateViewMatrix();

            base.HandleKeyboardInput();
        }
Exemple #46
0
 private void Awake()
 {
     Instance          = this;
     lastChessPosition = new Vector2Int(-9999, -9999);
 }