public static Checker[,] StringToField(string str) { var field = new Checker[8, 8]; if (str.Length != 64) throw new ArgumentException("not correct argument string in method StringToField"); for (var i = 0; i < 8; i++) for (var j = 0; j < 8; j++) { switch (str[i * 8 + j]) { case '1': field[i, j] = new Checker(Color.White, false); break; case '2': field[i, j] = new Checker(Color.Black, false); break; case '3': field[i, j] = new Checker(Color.White, true); break; case '4': field[i, j] = new Checker(Color.Black, true); break; } } return field; }
public HashSet<Move> AddBindingForQueens(Checker[,] field, Color color) { var ans = new HashSet<Move>(); for (var i = 0; i < 8; i++) for (var j = 0; j < 8; j++) if (field[i, j] != null && field[i, j].Color == color && field[i, j].IsQueen) AddToHash(ans, Bind(field, new Point(i, j), color)); return ans; }
public List<Move> MakeTurn(Checker[,] field) { Func<Point, bool> InField = (point => point.X < 8 && point.X >= 0 && point.Y < 8 && point.Y >= 0); var answer = new List<Move>(); var valid = new Validator(); var way = (Color == Color.White) ? -1 : 1; var listOfMyCheckersWhoCanMove = new List<Move>(); var bindingMoves = valid.GetBindingMoves(field, Color); if (bindingMoves.Count > 0) { var tempMap = new Checker[8, 8]; for (var i = 0; i < 8; i++) for (var j = 0; j < 8; j++) if (field[i, j] != null) tempMap[i, j] = new Checker(field[i, j].Color, field[i, j].IsQueen); answer.Add(bindingMoves.ToArray()[Program.Rand.Next(0, bindingMoves.Count)]); valid.MakeMove(tempMap, answer[0]); var from = answer[0].To; var array = valid.GetBindingMoves(tempMap, Color).Where(x => x.From == from).ToArray(); var counter = array.Length; while (counter > 0) { var rand = Program.Rand.Next(0, counter); var move = new Move(from, array[rand].To); answer.Add(move); valid.MakeMove(tempMap, move); from = move.To; array = valid.GetBindingMoves(tempMap, Color).Where(x => x.From == from).ToArray(); counter = array.Length; } return answer; } for (var i = 0; i < 8; i++) // составляем список всех возможных фигур, которые могут ходить for (var j = 0; j < 8; j++) if (field[i, j] != null && field[i, j].Color == Color) { if (InField(new Point(i + 1, j + way)) && field[i + 1, j + way] == null) listOfMyCheckersWhoCanMove.Add(new Move(new Point(i, j), new Point(i + 1, j + way))); if (InField(new Point(i - 1, j + way)) && field[i - 1, j + way] == null) listOfMyCheckersWhoCanMove.Add(new Move(new Point(i, j), new Point(i - 1, j + way))); if (InField(new Point(i + 1, j - way)) && field[i + 1, j - way] == null && field[i, j].IsQueen) listOfMyCheckersWhoCanMove.Add(new Move(new Point(i, j), new Point(i + 1, j - way))); if (InField(new Point(i - 1, j - way)) && field[i - 1, j - way] == null && field[i, j].IsQueen) listOfMyCheckersWhoCanMove.Add(new Move(new Point(i, j), new Point(i - 1, j - way))); } if (listOfMyCheckersWhoCanMove.Count > 0) //если в этом списке что-то есть -- добавляем рандомный эл-т и заканчиваем ход { var rand = Program.Rand.Next(0, listOfMyCheckersWhoCanMove.Count); var move = listOfMyCheckersWhoCanMove[rand]; answer.Add(move); return answer; } MessageBox.Show(Color.ToString() + " lose"); Environment.Exit(0); return null; }
public List<Move> MakeTurn(Checker[,] field) { var fieldInString = Serializer.FieldToString(field); process.StandardInput.WriteLine(fieldInString); var movesInString = process.StandardOutput.ReadLine(); Logs.AddToLog(process.StartInfo.Arguments.Split(' ')[1] + "'s turn: " + movesInString); if (movesInString == "White LOSE" || movesInString == "Black LOSE") { if (movesInString == "White LOSE") Program.Winner--; else Program.Winner++; Console.WriteLine(movesInString); Logs.AddToLog(movesInString); if (Program.GamesCount != Program.BestOf) { Program.GamesCount++; var thr = new Thread(Program.Gaming); thr.Start(); Thread.CurrentThread.Abort(); } else { if (Program.Winner > 0) { var res = "WHITE WON THE GAME!!!"; Logs.AddToLog(res); Console.WriteLine(res); if (Program.usingTimer) Console.WriteLine("White's longest move: {0}ms. Black's longest move: {1}ms.", Program.MaxWhite, Program.MaxBlack); } if (Program.Winner < 0) { var res = "BLACK WON THE GAME!!!"; Logs.AddToLog(res); Console.WriteLine(res); if (Program.usingTimer) Console.WriteLine("White's longest move: {0}ms. Black's longest move: {1}ms.", Program.MaxWhite, Program.MaxBlack); } if (Program.Winner == 0) { var res = "DRAW!"; Logs.AddToLog(res); Console.WriteLine(res); if (Program.usingTimer) Console.WriteLine("White's longest move: {0}ms. Black's longest move: {1}ms.", Program.MaxWhite, Program.MaxBlack); } Logs.Done(); Environment.Exit(0); } } return Serializer.StringToMoves(movesInString); }
public static string FieldToString(Checker[,] field) { var answer = ""; foreach (var value in field) { if (value == null) { answer+='0'; continue; } answer += (value.Color == Color.Black ? 1 : 0) + (value.IsQueen ? 2 : 0) + 1; } return answer; }
public MyForm(Checker[,] field) { black.Initialize(Color.Black); white.Initialize(Color.White); //to make a turn mark your fields to go one by one and press "T". To simulate a game //press space button. Happy gaming, your BandW404 team! FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; this.field = field; validator = new Validator(); StartPosition = FormStartPosition.CenterScreen; ClientSize = new Size(ElementSize * 8, ElementSize * 8); DoubleBuffered = true; Text = "Checkers"; tickCount = 0; this.KeyDown += MyForm_KeyDown; this.MouseClick += MyForm_MouseClick; }
public bool CanSelectChecker(Checker checker) { if (checker != null) { var isOwnChecker = CurrentPlayer.PlaysWhites == checker.IsWhite; if (!isOwnChecker) { return false; } if (checkersWithTakes.Count > 0) { return checkersWithTakes.Contains(checker); } return !IsCheckerBlocked(checker); } return false; }
public HashSet<Move> GetBindingMoves(Checker[,] field, Color playerColor) { var ans = new HashSet<Move>(); for (var i = 0; i < 8; i++) for (var j = 0; j < 8; j++) if (field[i, j] != null && field[i, j].Color == playerColor) for (var di = -1; di < 2; di += 2) for (var dj = -1; dj < 2; dj += 2) { var from = new Point(i, j); var enemy = new Point(i + di, j + dj); var free = new Point(i + di * 2, j + dj * 2); if (InField(enemy) && field[enemy.X, enemy.Y] != null && field[enemy.X, enemy.Y].Color != playerColor && InField(free) && field[enemy.X, enemy.Y].Color != Color.Beated && field[free.X, free.Y] == null) ans.Add(new Move(from, free)); } AddToHash(ans, AddBindingForQueens(field, playerColor)); return ans; }
public void Initialize(ContentManager Content) { whitecheckers = new List<Checker>(); blackcheckers = new List<Checker>(); int w1 = 0, w2 = 0; int h1 = 0, h2 = 0; for (int i = 0; i < 12; i++) { Checker checkerw = new Checker(); Checker checkerb = new Checker(); if (i < 4) { w2 = 60 + i * 120; w1 = 0 + i * 120; h1 = 420; h2 = 0; } if ((4 <= i) && (i < 8)) { w2 = -480 + i * 120; w1 = -420 + i * 120; h1 = 360; h2 = 60; } if ((i < 12) && (8 <= i)) { w2 = -900 + i * 120; w1 = -960 + i * 120; h1 = 300; h2 = 120; } checkerw.Initialize(Content, "Graphics\\white", new Vector2(w1, h1), 1); whitecheckers.Add(checkerw); checkerb.Initialize(Content, "Graphics\\black", new Vector2(w2, h2), 2); blackcheckers.Add(checkerb); } }
public void Update(Checker[,] field) { this.field = field; Invalidate(); }
public void DrawCell(Checker checker) { Console.Write(checker.DrawChecker()); }
public void RemoveChecker(Checker checker) { Checkers.Remove(checker); return; }
private bool IsOwnChecker(Checker checker) { return checker.IsWhite == CurrentPlayer.PlaysWhites; }
private bool IsTakePossible(Checker currentChecker, List<Coordinate> emptyCellsBehindEnemy) { return EnemiesCoordinates.Count > 0 && emptyCellsBehindEnemy.Count > 0 && !possibleTakes.ContainsKey(currentChecker); }
public bool IsCheckerBlocked(Checker checker) { var isDirectionBlocked = new bool[4]; var x = checker.Coordinate.X; var y = checker.Coordinate.Y; for (var i = 0; i < directions.Length; i++) { var twoEnemiesInARow = false; var friendlyChecker = false; var reverseMove = false; var outOfBoard = false; var firstX = x + directions[i][0]; var firstY = y + directions[i][1]; var currentCoordinate = new Coordinate(x, y); var firstCoordinate = new Coordinate(firstX, firstY); var firstChecker = checkers.GetChecker(firstCoordinate); if (Board.DoesCellExist(firstCoordinate)) { var secondX = x + 2 * directions[i][0]; var secondY = y + 2 * directions[i][1]; var secondCoordinate = new Coordinate(secondX, secondY); var secondChecker = checkers.GetChecker(secondCoordinate); var isFirstCellEmpty = IsCellEmpty(firstCoordinate); var isSecondCellEmpty = IsCellEmpty(secondCoordinate); if (!isFirstCellEmpty) { if (IsOwnChecker(firstChecker)) { friendlyChecker = true; } else if (Board.DoesCellExist(secondCoordinate) && !isSecondCellEmpty && !IsOwnChecker(secondChecker)) { twoEnemiesInARow = true; } } } else { outOfBoard = true; } if (!checker.IsQueen && !IsMoveForward(currentCoordinate, firstCoordinate)) { reverseMove = true; } isDirectionBlocked[i] = twoEnemiesInARow || friendlyChecker || reverseMove || outOfBoard; } return isDirectionBlocked.All(value => value.Equals(true)); }
public void FindPossibleTakes(Checker currentChecker) { var currentCoordinate = new Coordinate(currentChecker.Coordinate.X, currentChecker.Coordinate.Y); EnemiesCoordinates = new List<Coordinate>(); var emptyCellsBehindEnemy = new List<Coordinate>(); var searchEnd = 1; if (currentChecker.IsQueen) { searchEnd = 7; } foreach (var direction in directions) { for (var depth = 1; depth <= searchEnd; depth++) { var coordinateToCheck = new Coordinate(currentCoordinate.X + depth * direction[0], currentCoordinate.Y + depth * direction[1]); if (!Board.DoesCellExist(coordinateToCheck) || IsCellEmpty(coordinateToCheck)) continue; var checkerToCheck = checkers.GetChecker(coordinateToCheck); var isOwnChecker = currentChecker.IsWhite == checkerToCheck.IsWhite; if (isOwnChecker) break; EnemiesCoordinates.Add(coordinateToCheck); for (var landingDepth = 1; landingDepth <= searchEnd; landingDepth++) { var nextCoordinate = new Coordinate( coordinateToCheck.X + landingDepth * direction[0], coordinateToCheck.Y + landingDepth * direction[1]); var isNextCellEmpty = IsCellEmpty(nextCoordinate); if (!isNextCellEmpty) { depth = searchEnd; break; } if (Board.DoesCellExist(nextCoordinate)) { emptyCellsBehindEnemy.Add(nextCoordinate); } } } } if (IsTakePossible(currentChecker, emptyCellsBehindEnemy)) { possibleTakes.Add(currentChecker, emptyCellsBehindEnemy); } }
public void CheckerBecomesQueen(Checker checker) { const int topRow = 0; const int bottomRow = 7; var isAtBottomRow = checker.Coordinate.X == bottomRow; var isAtTopRow = checker.Coordinate.X == topRow; if ((checker.IsWhite || !isAtBottomRow) && (!checker.IsWhite || !isAtTopRow)) return; checker.ChangeToQueen(); }
public bool IsLegalMove(Color player, Position src, Position dest) { if (src.row < 0 || src.row > 7 || src.col < 0 || src.col > 7 || dest.row < 0 || dest.row > 7 || dest.col < 0 || dest.col > 7) { return(false); //Checks to see if the moves entered were on available on the board } //Checks to ensure the player moved more than 0 squares or less than 2 squares int rowDistance = Math.Abs(dest.row - src.row); int colDistance = Math.Abs(dest.col - src.col); if (colDistance == 0 || rowDistance == 0) //checks to make sure that the checker is not moving in a straight line { return(false); } if (rowDistance / colDistance != 1) //checks that the move is diagonal { return(false); } if (rowDistance > 2) //Player selected a square beyond it movement square choices { return(false); } if (colDistance > 2) //Player selected a square beyond it movement square choices { return(false); } Checker c = board.GetChecker(src); if (c == null) //There is no checker at the src selection { return(false); } if (Program.playerTurn != c.Team) { return(false); } c = board.GetChecker(dest); if (c != null) //Make sure there is no checker at the dest selection { return(false); } if (rowDistance == 2) //checks that if they player did move 2 was it because of a capture { if (IsCapture(src, dest)) { return(true); } else { return(false); } } else { return(true); } }
public void MoveChecker(Checker checker, Position dest) { _checkers.Remove(checker); checker.Position = dest; _checkers.Add(checker); }
public void ProcessInput() { ///NOTE: If you want to, you can try to validate the source position ///right after the user enters the data by checking if there is a checker ///at the given position Console.WriteLine("Select a checker to move (Row, Column):"); string[] src = Console.ReadLine().Split(','); // I skipped user input validation here Console.WriteLine("Select a square to move to (Row, Column):"); string[] dest = Console.ReadLine().Split(','); // I skipped user input validation here // usually we need to check if src.Count==2 before we retrieve data src[0] and src[1] // you can add the check if you want to. Likewise, we usually check dest.Count==2 as well Position from = new Position(int.Parse(src[0]), int.Parse(src[1])); Position to = new Position(int.Parse(dest[0]), int.Parse(dest[1])); ///TODO: Now you have all building blocks, it is your turn to put them together /// //1. Get the checker at the source position: // hint: use GetChecker function Checker srcChecker = board.GetChecker(from); if (srcChecker == null) { Console.WriteLine("Invalid source position. Try again."); } else { if (IsLegalMove(srcChecker.Team, from, to)) { if (this.IsCapture(from, to)) { Checker capturedChecker = this.GetCaptureChecker(from, to); board.RemoveChecker(capturedChecker); } board.MoveChecker(srcChecker, to); } else { Console.WriteLine("Invalid Move! Check your source and destinations"); } } DrawBoard(); //2. If there is no checker at the source position // notify the user of the error, then stop //3. If there is a checker at the source position // then check if the move from the source position to the destination position // is a legal move // // 3.1. // If (this is a legal move) // { // Move the checker to the destination position // If (this is also a capture move) // { // Find the checker that will be captured // Remove the captured checker from the board // } // } // else (this is not a legal move) // { // Notify the user of the error and then stop // } // Re-draw the board after each move }
public void MakeMove(Checker[,] field, Move move) { var delta = GetDelta(move); var dx = delta.Item1; var dy = delta.Item2; var x = move.From.X; var y = move.From.Y; var checker = new Checker(field[x,y].Color, field[x,y].IsQueen); var color = field[x, y].Color; field[x, y] = null; for (var i = 0; i < 8; i++) if (InField(new Point(x + dx * i, y + dy * i))) { if (move.To.X == x + dx * i && move.To.Y == y + dy * i) { field[x + dx * i, y + dy * i] = checker; if (y + dy * i == 0 && checker.Color == Color.White) field[x + dx * i, y + dy * i] = new Checker(checker.Color, true); if (y + dy * i == 7 && checker.Color == Color.Black) field[x + dx * i, y + dy * i] = new Checker(checker.Color, true); break; } if (field[x + dx * i, y + dy * i] != null && field[x + dx * i, y + dy * i].Color != color) { checkersTODelete.Add(new Point(x + dx * i, y + dy * i)); field[x + dx * i, y + dy * i] = new Checker(Color.Beated, false); } } }
public Game() { Board board = new Board(); board.GenerateCheckers(); board.DrawBoard(); Console.WriteLine("\nIf you want to move a checker one space diagonally forward, enter 'move'."); Console.WriteLine("\nIf a jump is available for one of your checker, you must enter 'jump'."); string choice = Console.ReadLine(); do { switch (choice) { case "move": Console.WriteLine("Enter checker Row to move:"); int row = int.Parse(Console.ReadLine()); Console.WriteLine("Enter checker Column:"); int column = int.Parse(Console.ReadLine()); if (board.SelectChecker(row, column) != null) { Checker checker = board.SelectChecker(row, column); Console.WriteLine("Move to which Row: "); int newRow = int.Parse(Console.ReadLine()); Console.WriteLine("Move to which Column: "); int newColumn = int.Parse(Console.ReadLine()); checker.Position = new int[] { newRow, newColumn }; board.DrawBoard(); } else { Console.WriteLine("Invalid input"); Console.WriteLine("Enter a valid checker Row:"); row = int.Parse(Console.ReadLine()); Console.WriteLine("Enter a valid checker Column:"); column = int.Parse(Console.ReadLine()); } break; case "jump": Console.WriteLine("Select checker Row to remove:"); int removeRow = int.Parse(Console.ReadLine()); Console.WriteLine("Select checker Column to remove:"); int removeColumn = int.Parse(Console.ReadLine()); Checker changeChecker = board.SelectChecker(removeRow, removeColumn); board.RemoveChecker(changeChecker); board.DrawBoard(); break; default: Console.WriteLine("Invalid input."); break; } } while (board.CheckForWin() != true); }
Checker[,] GetMapFrom(string filename) { var map = new Checker[8, 8]; var file = File.ReadAllLines("Maps\\" + filename); for (var i = 0; i < 8; i++) for (var j = 0; j < 8; j++) switch (file[i][j]) { case '1': map[j, i] = new Checker(Color.White, false); break; case '2': map[j, i] = new Checker(Color.Black, false); break; case '3': map[j, i] = new Checker(Color.White, true); break; case '4': map[j, i] = new Checker(Color.Black, true); break; default: break; } return map; }
public bool IsLegalMove(Color player, Position source, Position destination) { // 1. Both the source position and the destination position // must be integers between 0 and 7 if (source.Row < 0 || source.Row > 7 || source.Column < 0 || source.Column > 7 || destination.Row < 0 || destination.Row > 7 || destination.Column < 0 || destination.Column > 7) { return(false); } // 2. The row distance between the destination position and the source position // must be larger than 0 AND less than or equal to 2 int rowDistance = Math.Abs(destination.Row - source.Row); int colDistance = Math.Abs(destination.Column - source.Column); if (colDistance == 0 || rowDistance == 0) { return(false); } if (rowDistance / colDistance != 1) { return(false); } if (rowDistance > 2) { return(false); } Checker c = board.GetChecker(source); if (c == null) // this is no checker at the source position { return(false); } c = board.GetChecker(destination); if (c != null) // the destination position has been taken { return(false); } // If we get here, that means the source position has a checker AND the destination position is empty // AND destination.Row != source.Row AND destination.Column != source.Destination if (rowDistance == 2) { if (IsCapture(source, destination)) { return(true); } else { return(false); } } else { return(true); } }
private bool IsQuennTurnCorrect(Checker[,] field, Color playerColor, Move turn) { var possibleAttack = Bind(field, new Point(turn.From.X, turn.From.Y), playerColor); return possibleAttack.Contains(turn) || IsRightQueenMove(turn, field, playerColor); }
public void Click(bool allowRender) { if (_desk.IsGameFinished) { return; } if (Checker == null) { // _desk.Set_ShotDownCeckerCell(null); if (_desk.AllowedPositions.Contains(_position)) { // move to new position var cell = _desk.Get_selectedCell(); Checker = cell.Checker; var position = cell.GetCellPosition(); var startCell = _desk.GetCell(position); startCell.Checker = null; if (!Checker.IsQuean && ( _desk.CurrentWhiteTurn && Checker.IsWhite && _position.Get_row() == _desk.Height - 1 || !_desk.CurrentWhiteTurn && !Checker.IsWhite && _position.Get_row() == 0 )) { Checker.SetAsQuean(); } if (_desk.NeedBeat) { //remove Checkers between startCell and cell var diagonals = startCell.GetCellDiagonals(); var selectedDiagonal = diagonals.FirstOrDefault(diagonal => diagonal.Cells.Contains(this)); if (selectedDiagonal != null) { foreach (var deskCell in selectedDiagonal.Cells) { var selectedChecker = _desk.GetCell(deskCell.GetCellPosition()).Checker; if (selectedChecker == null) { continue; } if (deskCell == this) { break; } if (selectedChecker.IsWhite) { _desk.Set_whiteCount(_desk.Get_whiteCount() - 1); } else { _desk.Set_blackCount(_desk.Get_blackCount() - 1); } if (deskCell.Checker == null) { continue; } selectedChecker.ShotDown(); _desk.Set_ShotDownCeckerCell(deskCell); break; } } Click(false); _desk.CheckIfNeedBeate(this); } if (!_desk.NeedBeat) { _desk.BattleCheckersPositions.Clear(); _desk.CurrentWhiteTurn = !_desk.CurrentWhiteTurn; _desk.EndTurn(); //todo: need good working if (!_desk.Get_isBotSimulation() && _desk.IsGameFinished) { return; } _desk.UnselectLastCell(); _desk.CheckIfNeedBeate(); if (allowRender) { _desk.NotifyOfDeskChanged(); } _desk.BotTurn(); if (allowRender) { _desk.NotifyOfDeskChanged(); } } if (allowRender) { _desk.NotifyOfDeskChanged(); } return; } _desk.UnselectLastCell(); _desk.SetSelectedCell(this); } if (Checker != null) { if (_desk.Get_allowCheats() && !_desk.Get_isBotSimulation() && _desk.CurrentPlayerIsHuman() && Keyboard.IsKeyDown(Key.LeftCtrl) && Keyboard.IsKeyDown(Key.LeftAlt)) //Cheats { if (Keyboard.IsKeyDown(Key.Q)) { Checker.SetAsQuean(); } if (Keyboard.IsKeyDown(Key.D)) { if (!Checker.IsShotDown && Checker.IsWhite) { _desk.Set_whiteCount(_desk.Get_whiteCount() - 1); } else { _desk.Set_blackCount(_desk.Get_blackCount() - 1); } Checker = null; _desk.AllowedPositions.Clear(); _desk.BattleCheckersPositions.Clear(); if (_desk.Get_selectedCell() != null && _desk.Get_selectedCell().Checker != null) { _desk.Get_selectedCell().GetBattleCells(); if (_desk.BattleCheckersPositions.Count <= 0) { _desk.Get_selectedCell().GetAllowedPositions(); } else { _desk.NeedBeat = true; foreach (var cell in _desk.Get_selectedCell().GetBattleCells()) { _desk.AllowedPositions.Add(cell._position); } } } if (allowRender) { _desk.NotifyOfDeskChanged(); } return; } } if (_desk.CurrentWhiteTurn && Checker.IsWhite || !_desk.CurrentWhiteTurn && !Checker.IsWhite) { _desk.UnselectLastCell(); _desk.SetSelectedCell(this); _desk.CheckIfNeedBeate(); if (_desk.NeedBeat) { var allowedPositionsCells = GetBattleCells(); foreach (var cell in allowedPositionsCells) { _desk.AllowedPositions.Add(cell._position); } } else { _desk.ShowAllowedPosition(this); } _desk.BotTurn(); if (allowRender) { _desk.NotifyOfDeskChanged(); } } } if (allowRender) { _desk.NotifyOfDeskChanged(); } }
public void MoveChecker(Checker checker, int row, int column) { if (Checkers.Find(checkr => checkr.Position.SequenceEqual( new int[] { row, column })) == null) { // jumping if ((Math.Abs(row - checker.Position[0]) == 2 && Math.Abs(column - checker.Position[1]) == 2)) { if (checker.Color == "black" || checker.King) { // up right if (row - checker.Position[0] == -2 && column - checker.Position[1] == 2) { JumpChecker(checker, row + 1, column - 1, row, column); return; } // up left if (row - checker.Position[0] == -2 && column - checker.Position[1] == -2) { JumpChecker(checker, row + 1, column + 1, row, column); return; } else { Console.WriteLine("Invalid move"); } } if (checker.Color == "white" || checker.King) { // down right if (row - checker.Position[0] == 2 && column - checker.Position[1] == 2) { JumpChecker(checker, row - 1, column - 1, row, column); return; } // down left if (row - checker.Position[0] == 2 && column - checker.Position[1] == -2) { JumpChecker(checker, row - 1, column + 1, row, column); return; } else { Console.WriteLine("Invalid move"); } } } // non-jumping else if (Math.Abs(row - checker.Position[0]) == 1 && Math.Abs(column - checker.Position[1]) == 1) { if ((row > checker.Position[0] && checker.Color == "white") || (row < checker.Position[0] && checker.Color == "black") || checker.King) { PlaceChecker(checker, row, column); } else { Console.WriteLine("Invalid move"); } } else { Console.WriteLine("Invalid move"); } } else { Console.WriteLine("Invalid move"); } return; }
private HashSet<Move> Bind(Checker[,] field, Point pos, Color playerColor) { var dx = new int[] { 1, -1, 1, -1 }; var dy = new int[] { -1, -1, 1, 1 }; var x = pos.X; var y = pos.Y; var ans = new HashSet<Move>(); for (var i = 0; i < 4; i++) { var noBlock = true; var enemyFound = false; for (var delta = 1; delta < 8; delta++) if (InField(new Point(x + dx[i] * delta, y + dy[i] * delta))) { if (InField(new Point(x + dx[i] * (delta + 1), y + dy[i] * (delta + 1)))) { if (field[x + dx[i] * delta, y + dy[i] * delta] != null && field[x + dx[i] * (delta + 1), y + dy[i] * (delta + 1)] != null) if (field[x + dx[i] * delta, y + dy[i] * delta].Color != playerColor && field[x + dx[i] * delta, y + dy[i] * delta].Color != Color.Beated && field[x + dx[i] * (delta + 1), y + dy[i] * (delta + 1)].Color != Color.Beated) noBlock = false; if (field[x + dx[i] * delta, y + dy[i] * delta] != null && field[x + dx[i] * delta, y + dy[i] * delta].Color == Color.Beated) noBlock = false; if (field[x + dx[i] * delta, y + dy[i] * delta] != null && field[x + dx[i] * delta, y + dy[i] * delta].Color == playerColor) noBlock = false; } if (field[x + dx[i] * delta, y + dy[i] * delta] != null) if (InField(new Point(x + dx[i] * (delta + 1), y + dy[i] * (delta + 1)))) if (((field[x + dx[i] * delta, y + dy[i] * delta].Color != playerColor && field[x + dx[i] * delta, y + dy[i] * delta].Color != Color.Beated)) && noBlock && field[x + dx[i] * (delta + 1), y + dy[i] * (delta + 1)] == null) { ans.Add(new Move(new Point(x, y), new Point(x + dx[i] * (delta + 1), y + dy[i] * (delta + 1)))); enemyFound = true; } if (enemyFound && field[x + dx[i] * delta, y + dy[i] * delta] == null && noBlock) { ans.Add(new Move(new Point(x, y), new Point(x + dx[i] * (delta), y + dy[i] * (delta)))); } } } return ans; }
public bool CanSelectChecker(Checker checker) { try { var isOwnChecker = (CurrentPlayer.PlaysWhites == checker.IsWhite); if (!isOwnChecker) return false; if (CheckersWithTakes.Count > 0) return CheckersWithTakes.Contains(checker); return !IsCheckerBlocked(checker); } catch (ArgumentOutOfRangeException) { return false; } catch (NullReferenceException) { return false; } }
private bool IsCheckerTurnCorrect(Checker[,] field, Color playerColor, Move turn) { if (field[turn.From.X, turn.From.Y].Color != playerColor) return false; var dx = new int[2]; var dy = new int[2]; if (playerColor == Color.White) { dx = new int[] { 1, -1 }; dy = new int[] { -1, -1 }; } else { dx = new int[] { -1, 1 }; dy = new int[] { 1, 1 }; } for (var i = 0; i < 2; i++) if (InField(new Point(turn.From.X + dx[i], turn.From.Y + dy[i]))) if (field[turn.From.X + dx[i], turn.From.Y + dy[i]] == null && turn.From.X + dx[i] == turn.To.X && turn.From.Y + dy[i] == turn.To.Y) return true;//ламповая проверка на возожность хода dx = new int[] { 2, -2, 2, -2 }; dy = new int[] { -2, -2, 2, 2 }; for (var i = 0; i < 4; i++) if (InField(new Point(turn.From.X + dx[i], turn.From.Y + dy[i]))) if (field[turn.From.X + dx[i], turn.From.Y + dy[i]] == null) { var decr = GetNextFreePlace(dx[i], dy[i]); if (field[turn.From.X + decr.X, turn.From.Y + decr.Y] != null && field[turn.From.X + decr.X, turn.From.Y + decr.Y].Color != playerColor) return true; } return false; }
public void CheckerBecomesQueen(Checker checker) { if ((checker.IsWhite || checker.Coordinate.X != 7) && (!checker.IsWhite || checker.Coordinate.X != 0)) return; checker.IsQueen = true; checker.GetQueenSymbol(); }
private bool IsRightQueenMove(Move move, Checker[,] field, Color playerColor) { var dx = new int[] { 1, -1, 1, -1 }; var dy = new int[] { -1, -1, 1, 1 }; var x = move.From.X; var y = move.From.Y; for (var i = 0; i < 4; i++) { var enemyFound = false; for (var delta = 1; delta < 8; delta++) if (!enemyFound) if (InField(new Point(x + dx[i] * delta, y + dy[i] * delta))) { if (field[x + dx[i] * delta, y + dy[i] * delta] != null) { enemyFound = true; continue; } if (move.To.X == x + dx[i] * delta && move.To.Y == y + dy[i] * delta) return true; } } return false; }
public void FindPossibleTakes(Checker currentChecker) { int[][] directionSign = { new [] {-1, -1}, //up left new [] {-1, 1}, //up right new [] {1, -1}, //down left new [] {1, 1} //down right }; var currentCoordinate = new Coordinate(currentChecker.Coordinate.X, currentChecker.Coordinate.Y); EnemiesCoordinates = new List<Coordinate>(); var emptyCellsBehindEnemy = new List<Coordinate>(); var end = 1; if (currentChecker.IsQueen) { end = 7; } for (var i = 0; i < 4; i++) { for (var depth = 1; depth <= end; depth++) { var coordinateToCheck = new Coordinate(currentCoordinate.X + depth * directionSign[i][0], currentCoordinate.Y + depth * directionSign[i][1]); if (!Board.CellExists(coordinateToCheck) || IsCellEmpty(coordinateToCheck)) continue; var checkerToCheck = GetChecker(coordinateToCheck); if (currentChecker.IsWhite == checkerToCheck.IsWhite) break; EnemiesCoordinates.Add(coordinateToCheck); for (var landingDepth = 1; landingDepth <= end; landingDepth++) { var nextCoordinate = new Coordinate( coordinateToCheck.X + landingDepth * directionSign[i][0], coordinateToCheck.Y + landingDepth * directionSign[i][1]); var isNextCellEmpty = IsCellEmpty(nextCoordinate); if (!isNextCellEmpty) { depth = end; break; } if (Board.CellExists(nextCoordinate)) { emptyCellsBehindEnemy.Add(nextCoordinate); } } } } if (EnemiesCoordinates.Count > 0 && !PossibleTakes.ContainsKey(currentChecker) && emptyCellsBehindEnemy.Count > 0) { PossibleTakes.Add(currentChecker, emptyCellsBehindEnemy); } }
public void IsCorrectMove(List<Move> moves, Checker[,] field, Color playerColor) { if (moves == null || (moves != null && moves.Count == 0)) { Logs.AddToLog("Не сходил вообще"); Logs.Done(); throw new NotImplementedException("Player lost"); } var firstMove = true; var result = true; var start = new Point(-1,-1); var mv = GetBindingMoves(field, playerColor); var attack = mv.Count != 0; foreach (var turn in moves) if (result && InField(new Point(turn.From.X, turn.From.Y)) && InField(new Point(turn.To.X, turn.To.Y)) && field[turn.From.X, turn.From.Y] != null) { if (start.X == -1 && start.Y == -1) start = turn.From; if (start != turn.From) { Logs.AddToLog("Пытался сходить не той пешкой, которой ходил вначале"); Logs.Done(); throw new NotImplementedException("Пытался сходить не той пешкой, которой ходил вначале"); } var bindingMoves = GetBindingMoves(field, playerColor); if (bindingMoves.Count == 0 && !firstMove) { Logs.AddToLog("Попытка двойных ходов"); Logs.Done(); throw new NotImplementedException("Попытка двойных ходов"); } if (bindingMoves.Count != 0 && !bindingMoves.Contains(turn)) { Logs.AddToLog("Были обязательные ходы, но ход не был сделан"); Logs.Done(); throw new NotImplementedException("Были обязательные ходы, но ход не был сделан"); } if (!field[turn.From.X, turn.From.Y].IsQueen) result &= IsCheckerTurnCorrect(field, playerColor, turn); else result &= IsQuennTurnCorrect(field, playerColor, turn); if (result) { MakeMove(field, turn); firstMove = false; start = turn.To; } } else result = false; if (!result) { Logs.AddToLog("Некорректные ходы"); Logs.Done(); throw new NotImplementedException("Некорректные ходы"); } var finalTest = GetBindingMoves(field, playerColor); if (IsInHashSet(finalTest, start) && attack) { Logs.AddToLog("Атака была не завершена"); Logs.Done(); throw new NotImplementedException("Атака была не завершена"); } foreach (var e in checkersTODelete) field[e.X, e.Y] = null; checkersTODelete.Clear(); return; }
public bool IsCheckerBlocked(Checker checker) { int[][] directions = { new [] {-1, -1}, //up left new [] {-1, 1}, //up right new [] {1, -1}, //down left new [] {1, 1} // down right }; var isDirectionBlocked = new bool[4]; var x = checker.Coordinate.X; var y = checker.Coordinate.Y; for (var i = 0; i < directions.Length; i++) { var twoEnemiesInARow = false; var friendlyChecker = false; var reverseMove = false; var outOfBoard = false; var firstX = x + directions[i][0]; var firstY = y + directions[i][1]; var secondX = x + 2 * directions[i][0]; var secondY = y + 2 * directions[i][1]; var currentCoordinate = new Coordinate(x, y); var firstCoordinate = new Coordinate(firstX, firstY); var firstChecker = GetChecker(firstCoordinate); var secondCoordinate = new Coordinate(secondX, secondY); var secondChecker = GetChecker(secondCoordinate); if (Board.CellExists(firstCoordinate)) { var isFirstCellEmpty = (firstChecker == null); var isSecondCellEmpty = (secondChecker == null); if (!isFirstCellEmpty) { if (firstChecker.IsWhite == CurrentPlayer.PlaysWhites) { friendlyChecker = true; } else if (Board.CellExists(secondCoordinate) && !isSecondCellEmpty && (secondChecker.IsWhite != CurrentPlayer.PlaysWhites)) { twoEnemiesInARow = true; } } } else { outOfBoard = true; } if (!checker.IsQueen && !IsMoveForward(currentCoordinate, firstCoordinate)) { reverseMove = true; } isDirectionBlocked[i] = twoEnemiesInARow || friendlyChecker || reverseMove || outOfBoard; } return isDirectionBlocked.All(value => value.Equals(true)); }
protected bool Equals(Checker other) { return IsWhite.Equals(other.IsWhite) && IsQueen.Equals(other.IsQueen) && Coordinate.Equals(other.Coordinate) && symbol == other.symbol; }
public void FindPossibleTakes(Checker currentChecker) { int[][] directionSign = { new [] { -1, -1 }, //up left new [] { -1, 1 }, //up right new [] { 1, -1 }, //down left new [] { 1, 1 } //down right }; var currentCoordinate = new Coordinate(currentChecker.Coordinate.X, currentChecker.Coordinate.Y); EnemiesCoordinates = new List <Coordinate>(); var emptyCellsBehindEnemy = new List <Coordinate>(); var end = 1; if (currentChecker.IsQueen) { end = 7; } for (var i = 0; i < 4; i++) { for (var depth = 1; depth <= end; depth++) { var coordinateToCheck = new Coordinate(currentCoordinate.X + depth * directionSign[i][0], currentCoordinate.Y + depth * directionSign[i][1]); if (!Board.CellExists(coordinateToCheck) || IsCellEmpty(coordinateToCheck)) { continue; } var checkerToCheck = GetChecker(coordinateToCheck); if (currentChecker.IsWhite == checkerToCheck.IsWhite) { break; } EnemiesCoordinates.Add(coordinateToCheck); for (var landingDepth = 1; landingDepth <= end; landingDepth++) { var nextCoordinate = new Coordinate( coordinateToCheck.X + landingDepth * directionSign[i][0], coordinateToCheck.Y + landingDepth * directionSign[i][1]); var isNextCellEmpty = IsCellEmpty(nextCoordinate); if (!isNextCellEmpty) { depth = end; break; } if (Board.CellExists(nextCoordinate)) { emptyCellsBehindEnemy.Add(nextCoordinate); } } } } if (EnemiesCoordinates.Count > 0 && !PossibleTakes.ContainsKey(currentChecker) && emptyCellsBehindEnemy.Count > 0) { PossibleTakes.Add(currentChecker, emptyCellsBehindEnemy); } }
public bool IsCheckerBlocked(Checker checker) { int[][] directions = { new [] { -1, -1 }, //up left new [] { -1, 1 }, //up right new [] { 1, -1 }, //down left new [] { 1, 1 } // down right }; var isDirectionBlocked = new bool[4]; var x = checker.Coordinate.X; var y = checker.Coordinate.Y; for (var i = 0; i < directions.Length; i++) { var twoEnemiesInARow = false; var friendlyChecker = false; var reverseMove = false; var outOfBoard = false; var firstX = x + directions[i][0]; var firstY = y + directions[i][1]; var secondX = x + 2 * directions[i][0]; var secondY = y + 2 * directions[i][1]; var currentCoordinate = new Coordinate(x, y); var firstCoordinate = new Coordinate(firstX, firstY); var firstChecker = GetChecker(firstCoordinate); var secondCoordinate = new Coordinate(secondX, secondY); var secondChecker = GetChecker(secondCoordinate); if (Board.CellExists(firstCoordinate)) { var isFirstCellEmpty = (firstChecker == null); var isSecondCellEmpty = (secondChecker == null); if (!isFirstCellEmpty) { if (firstChecker.IsWhite == CurrentPlayer.PlaysWhites) { friendlyChecker = true; } else if (Board.CellExists(secondCoordinate) && !isSecondCellEmpty && (secondChecker.IsWhite != CurrentPlayer.PlaysWhites)) { twoEnemiesInARow = true; } } } else { outOfBoard = true; } if (!checker.IsQueen && !IsMoveForward(currentCoordinate, firstCoordinate)) { reverseMove = true; } isDirectionBlocked[i] = twoEnemiesInARow || friendlyChecker || reverseMove || outOfBoard; } return(isDirectionBlocked.All(value => value.Equals(true))); }
public void ProcessInput() { bool isValid1 = false; bool isValid2 = false; Position from = new Position(0, 0); Position to = new Position(0, 0); do { Console.WriteLine($"It is {Program.playerTurn}'s turn"); Console.WriteLine("Select a row and column. (row,col)"); string[] src = Console.ReadLine().Split(","); int srcCount = src.Count(); if (srcCount == 2) { try { from = new Position(int.Parse(src[0]), int.Parse(src[1])); isValid1 = true; } catch { throw new ApplicationException("Please enter 2 numbers seperated by a comma: 0,0"); } } else { Console.WriteLine("Please enter 2 numbers seperated by a comma: 0,0"); } Console.WriteLine("Select a row and column to move the checker to. (row,col)"); string[] dest = Console.ReadLine().Split(","); int destCount = dest.Count(); if (destCount == 2) { try { to = new Position(int.Parse(dest[0]), int.Parse(dest[1])); isValid2 = true; } catch { throw new ApplicationException("Please enter 2 numbers seperated by a comma: 0,0"); } } else { Console.WriteLine("Please enter 2 numbers seperated by a comma: 0,0"); } } while (!isValid1 && !isValid2); Checker srcChecker = board.GetChecker(from); if (srcChecker == null) { Console.WriteLine("Invalid Choice. There is no checker at the chosen spot."); } else { if (IsLegalMove(srcChecker.Team, from, to)) { if (IsCapture(from, to)) { Checker JumpChecker = GetCaptureChecker(from, to); board.RemoveChecker(JumpChecker); board.MoveChecker(srcChecker, to); } else { board.MoveChecker(srcChecker, to); } } } Console.Clear(); DrawBoard(); if (Program.playerTurn == Color.White) { Program.playerTurn = Color.Black; } else { Program.playerTurn = Color.White; } }