public static void PrintFigure(IFigure figure, ConsoleColor backgroundColor, int top, int left) { if (figure == null) { PrintEmptySquare(backgroundColor, top, left); return; } if (!patterns.ContainsKey(figure.GetType().Name)) { return; } var figurePattern = patterns[figure.GetType().Name]; for (int i = 0; i < figurePattern.GetLength(0); i++) { for (int j = 0; j < figurePattern.GetLength(1); j++) { Console.SetCursorPosition(left + j, top + i); if (figurePattern[i, j]) { Console.BackgroundColor = figure.Color.ToConsoleColor(); } else { Console.BackgroundColor = backgroundColor; } Console.Write(" "); } } }
public void ValidateMove(IFigure figure, IBoard board, Move move) { var from = move.From; var to = move.To; var horizontalMovement = Math.Abs(from.Row - to.Row); var verticalMovement = Math.Abs(from.Col - to.Col); if (horizontalMovement == 0 || verticalMovement == 0) { if (horizontalMovement == 0) { char colIndex = from.Col; char colDirection = (char)(from.Col < to.Col ? 1 : -1); while (true) { colIndex += colDirection; if (to.Col == colIndex) { MovementValidator.CheckForFigureOnTheWay(figure, board, to); return; } var position = Position.FromChessCordinates(move.From.Row, colIndex); MovementValidator.CheckForFigureOnTheWay(figure, board, position); } } else { int rowIndex = from.Row; int rowDirection = from.Row < to.Row ? 1 : -1; while (true) { rowIndex += rowDirection; if (to.Row == rowIndex) { MovementValidator.CheckForFigureOnTheWay(figure, board, to); return; } var position = Position.FromChessCordinates(rowIndex, move.From.Col); MovementValidator.CheckForFigureOnTheWay(figure, board, position); } } } else { if (figure.GetType().Name != "Queen") { throw new InvalidOperationException($"{figure.GetType().Name} cannot move that way!"); } } }
public static string GenerateNewName(this IFigure figure) { // Old Scheme - all figures use same index. //return figure.GetType().Name + FigureBase.ID++; // New Scheme - each class essentially uses its own index. string className = figure.GetType().Name; #if TABULA // Some of the classes in Tabula have prefixes that need to be trimmed. - D.H. if (className[0] == 'T' && className[1] == 'A' && className[2] == 'B') { className = className.TrimStart('T', 'A', 'B'); } #endif for (int i = 1; i < int.MaxValue; i++) { string number = i.ToString(); var candidate = className + number; if (figure.NameAvailable(candidate)) { return(candidate); } } // Report a naming error. if (figure.Drawing != null) { var message = "Error in generating name for figure of class "; figure.Drawing.RaiseError(Application.Current, new Exception(message + figure.GetType().Name)); } return("error_generating_name"); }
public void Start() { while (true) { IFigure figure = null; try { var player = this.GetNextPlayer(); var move = this.input.GetNextPlayerMove(player); var from = move.From; var to = move.To; figure = this.board.GetFigureAtPosition(from); this.CheckIfPlayerOwnsFigure(player, figure, from); this.CheckIfToPositionIsEmpty(figure, to); var availableMovements = figure.Move(this.movementStrategy); this.ValidateMovements(figure, availableMovements, move); this.board.MoveFigureAtPosition(figure, from, to); this.renderer.RenderBoard(this.board); } catch (Exception ex) { this.currentPlayerIndex--; this.renderer.PrintErrorMessage(string.Format(ex.Message, figure.GetType().Name)); } } }
private static void PrintFigure(int left, int top, ConsoleColor backgroundColor, IFigure figure) { var figureColor = figure.Color.ToConsoleColor(); var figurePattern = Patterns[figure.GetType()]; for (var i = 0; i < figurePattern.GetLength(0); i++) { for (var j = 0; j < figurePattern.GetLength(1); j++) { if (figurePattern[i, j]) { Console.BackgroundColor = figureColor; } else { Console.BackgroundColor = backgroundColor; } Console.SetCursorPosition(left + j, top + i); Console.Write(" "); } Console.WriteLine(); } }
protected virtual void AddFoundDependency(IFigure figure) { if (ExpectedDependency.IsAssignableFrom(figure.GetType())) { FoundDependencies.Add(figure); } }
Expression CreatePropertyAccessExpression(Node root) { string figureName = root.Children[0].Token.Text; string propertyName = root.Children[1].Token.Text; IFigure figure = Binder.ResolveFigure(figureName); if (figure == null) { Status.AddUnknownIdentifierError(figureName); return(null); } if (!Binder.IsFigureAllowed(figure)) { Status.AddDependencyCycleError(figureName); return(null); } Type type = figure.GetType(); var property = type.GetProperty(propertyName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance); if (property == null) { Status.AddPropertyNotFoundError(figure, propertyName); return(null); } Status.Dependencies.Add(figure); var figureExpression = Expression.Constant(figure); var propertyExpression = Expression.Property(figureExpression, property); return(propertyExpression); }
public Position GetFigurePostionByTypeAndColor(string type, ChessColor color) { int row = -1; int col = 0; for (int i = 0; i < GlobalConstants.StandardGameTotalBoardRows; i++) { for (int j = 0; j < GlobalConstants.StandardGameTotalBoardCols; j++) { IFigure currentFigure = this.board[i, j]; if (currentFigure != null && currentFigure.GetType().Name == type && currentFigure.Color == color) { row = i; col = j; break; } } } //if (row == -1) //{ // return null; //} return(Position.FromArrayCoordinates(row, col, GlobalConstants.MaximumRowValueOnBoard)); }
public static void PrintFigure(IFigure figure, ConsoleColor backgroundColor, int top, int left) { if (figure == null) { PrintEmptySquare(backgroundColor, top, left); return; } var figurePattern = patterns[figure.GetType().Name]; { }; for (int row = 0; row < figurePattern.GetLength(0); row++) { for (int col = 0; col < figurePattern.GetLength(1); col++) { Console.SetCursorPosition(top + col, left + row); if (figurePattern[row, col]) { Console.BackgroundColor = figure.Color.ToConsoleColor(); } else { Console.BackgroundColor = backgroundColor; } Console.Write(" "); } } }
protected virtual void AddFoundDependency(IFigure figure) { if (figure != null && ExpectedDependency.IsAssignableFrom(figure.GetType())) { FoundDependencies.Add(figure); } }
public InstantFigure(IList <MemberInfo> membersInfo, string typeName, FigureMode modeType = FigureMode.Reference) { TypeName = typeName; Mode = modeType; members = CreateMemberRurics(membersInfo); Rubrics = new MemberRubrics(); Rubrics.KeyRubrics = new MemberRubrics(); foreach (MemberRubric mr in members) { Rubrics.Add(mr); } if (modeType == FigureMode.Reference) { InstantFigureReferenceCompiler rtbld = new InstantFigureReferenceCompiler(this); compiledType = rtbld.CompileFigureType(typeName); } else { InstantFigureValueTypeCompiler rtbld = new InstantFigureValueTypeCompiler(this); compiledType = rtbld.CompileFigureType(typeName); } Figure = (IFigure)compiledType.New(); FigureType = Figure.GetType(); FigureSize = Marshal.SizeOf(FigureType); if (!membersInfo.Where(m => m.Name == "SystemSerialCode").Any()) { members = new MemberRubric[] { new MemberRubric(FigureType.GetProperty("SystemSerialCode")) } }
public void Start() { while (true) { IFigure figure = null; try { var player = this.GetNextPlayer(); var move = this.input.GetNextPlayerMove(player); var from = move.From; var to = move.To; figure = this.board.GetFigureAtPosition(from); this.CheckIfPlayerOwnsFigure(player, figure, from); this.CheckIfToPositionIsEmpty(figure, to); var availableMovements = figure.Move(this.movementStrategy); this.ValidateMovements(figure, availableMovements, move); this.board.MoveFigureAtPosition(figure, from, to); this.renderer.RenderBoard(this.board); // TODO: On every move check if we are in check // TODO: Check pawn on last row // TODO: If not castle - move figure (check castle - check if castle is valid, check pawn for An-pasan) // TODO: If in check - check checkmate // TODO: If not in check - check draw // TODO: Continue } catch (Exception ex) { this.currentPlayerIndex--; this.renderer.PrintErrorMessage(string.Format(ex.Message, figure.GetType().Name)); } } }
/// <summary> /// Конструктор /// </summary> /// <param name="type">Тип фигуры</param> /// <param name="square"></param> public CalculationResultSuggestion(IFigure figure, params double[] parameters) { var type = figure.GetType(); Type = type; Name = type.Name; Square = figure.CalculateFigureSquare(parameters); }
public static void ReCreate() { var type = currentFigure.GetType(); var Thickness = currentFigure.LineThick; var Color = currentFigure.BorderColor; currentFigure = (IFigure)Activator.CreateInstance(type); currentFigure.LineThick = Thickness; currentFigure.BorderColor = Color; }
private void DrawFigure(IFigure figure) { if (figure == null) { return; } Console.WriteLine("Figure: " + figure.GetType().Name + "( " + figure.X + " ," + figure.Y + " )"); Console.WriteLine(); }
private void WriteActsPrevious(IFigure figure, bool isNew) { IFigure previous = null; if (!(figure is null)) { var newFigure = Activator.CreateInstance(Type.GetType(figure.GetType().FullName), figure); previous = (IFigure)newFigure; } _log.GetNew(previous, isNew); }
static void Main(string[] args) { ICreator[] creators = { new TriangleCreator(3, 4, 5), new QuadrateCreator(4), new RectangleCreator(5, 6), new CircleCreator(8) }; foreach (ICreator creator in creators) { IFigure fig = creator.Create(); Console.WriteLine($"Фигура: {fig.GetType().Name}, площадь - {fig.Square:n4}, периметр - {fig.Perimeter:n4} "); } Console.ReadKey(); }
string GetInputType(IFigure input) { Type inputType = input.GetType(); foreach (var commonType in commonTypes) { if (commonType.IsAssignableFrom(inputType)) { return commonType.Name; } } return inputType.Name; }
string GetInputType(IFigure input) { var inputType = input.GetType(); foreach (var commonType in commonTypes) { if (commonType.IsAssignableFrom(inputType)) { return(commonType.Name); } } return(inputType.Name); }
private void Game_MoveFinish(object source, EventArgs eventArgs) { System.Diagnostics.Debug.WriteLine( "MOVE_INFO - " + _figure.GetType() + " " + _figure.Color + " " + _figure.Field.Horizontal + _figure.Field.Vertical); if (_figure.Color == Color.White) { return; } locked = true; VerticalLocation = 8 - (int)_figure.Field.Vertical; HorizontalLocation = (int)_figure.Field.Horizontal - 1; locked = false; }
/// <summary> /// Finds a figure of a given type at the point. Collections are not searched. /// </summary> public IFigure HitTestNoCollections(System.Windows.Point point, Type figureType) { IFigure bestFoundSoFar = null; foreach (var item in Children) { IFigure found = item.HitTest(point); if (found != null && figureType.IsAssignableFrom(found.GetType())) { if (bestFoundSoFar == null || bestFoundSoFar.ZIndex <= found.ZIndex) { bestFoundSoFar = found; } } } return(bestFoundSoFar); }
private static void PrintFigure(IFigure figure) { string whoAmI = figure.WhoAmI(); string typeName = figure.GetType().Name; double area = figure.ComputeArea(); if (whoAmI != typeName) Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine( "WhoAmI = {0,-9} ; Имя класса {1,-9} ; Площадь={2:F2}", whoAmI, typeName, area ); Console.ResetColor(); }
public void CheckEnPassant(IBoard board, IFigure pawn, Position from, Position to, int round) { Position enPassantPosition = new Position(from.Row, (char)(to.Col)); IFigure otherPawn = board.GetFigureAtPosition(enPassantPosition); if (otherPawn != null && otherPawn.GetType().Name == "Pawn") { if (otherPawn.Color != pawn.Color) { if (otherPawn.Color == ChessColor.White) { if (whiteSideThirdRow[to.Col - 'a'] == round - 1) { board.MoveFigureAtPosition(pawn, from, to); board.RemoveFigure(enPassantPosition); } else { throw new InvalidOperationException(ExceptionMessages.InvalidEnPassantMovementException); } } else if (otherPawn.Color == ChessColor.Black) { if (blackSideThirdRow[to.Col - 'a'] == round - 1) { board.MoveFigureAtPosition(pawn, from, to); board.RemoveFigure(enPassantPosition); } else { throw new InvalidOperationException(ExceptionMessages.InvalidEnPassantMovementException); } } } else { throw new InvalidOperationException(ExceptionMessages.InvalidPawnMovementSidewaysException); } } else { throw new InvalidOperationException(ExceptionMessages.InvalidEnPassantMovementException); } }
private void сохранитьКакToolStripMenuItem_Click(object sender, EventArgs e) { CurrentFigure = null; openFileDialog1.CheckFileExists = false; if (openFileDialog1.ShowDialog() != DialogResult.OK) { return; } string path = openFileDialog1.FileName; FileStream F = File.Open(path, FileMode.Create); if (F == null) { MessageBox.Show("Cannot create output file!"); return; } try { StreamWriter st = new StreamWriter(F); JsonSerializerSettings settings = new JsonSerializerSettings(); settings.TypeNameHandling = TypeNameHandling.All; for (int i = FiguresBackBuffer.Count - 1; i >= 0; i--) { IFigure Tmp = FiguresBackBuffer.ElementAt(i); try { Tmp.EndOfCurrentFigure = true; string json = JsonConvert.SerializeObject(Tmp, Tmp.GetType(), settings); st.WriteLine(json); } catch (Exception ex) { MessageBox.Show(ex.Message); break; } } st.Close(); } finally { F.Close(); } }
private static void PrintFigure(IFigure figure) { string whoAmI = figure.WhoAmI(); string typeName = figure.GetType().Name; double area = figure.ComputeArea(); if (whoAmI != typeName) { Console.ForegroundColor = ConsoleColor.Red; } Console.WriteLine( "WhoAmI = {0,-9} ; Имя класса {1,-9} ; Площадь={2:F2}", whoAmI, typeName, area ); Console.ResetColor(); }
public void ValidateMove(IFigure figure, IBoard board, Move move) { var rowDistance = Math.Abs(move.From.Row - move.To.Row); var colDistance = Math.Abs(move.From.Col - move.To.Col); // TODO: extract to method var other = figure.Color == ChessColor.White ? ChessColor.Black : ChessColor.White; if (rowDistance != colDistance) { throw new InvalidOperationException($"{figure.GetType().Name} cannot move this way!"); } var from = move.From; var to = move.To; int rowIndex = from.Row; char colIndex = from.Col; int rowDirection = from.Row < to.Row ? 1 : -1; char colDirection = (char)(from.Col < to.Col ? 1 : -1); while (true) { rowIndex += rowDirection; colIndex += colDirection; if (to.Row == rowIndex && to.Col == colIndex) { MovementValidator.CheckForFigureOnTheWay(figure, board, to); return; } var position = Position.FromChessCordinates(rowIndex, colIndex); MovementValidator.CheckForFigureOnTheWay(figure, board, position); } }
protected virtual string GetTagNameForFigure(IFigure figure) { return(figure.GetType().Name); }
public static void Print(IFigure figure, ConsoleColor backgroundColor, int top, int left) { if (figure == null) { PrintEmptySquare(backgroundColor, top, left); return; } var figurePattern = patterns[figure.GetType().Name]; for (int i = 0; i < figurePattern.GetLength(0); i++) { for (int j = 0; j < figurePattern.GetLength(1); j++) { Console.SetCursorPosition(left + j, top + i); if (figurePattern[i, j]) { Console.BackgroundColor = figure.Color.ToConsoleColor(); } else { Console.BackgroundColor = backgroundColor; } Console.Write(" "); } } }
/// <summary> /// The SqlNetVal. /// </summary> /// <param name="fieldRow">The fieldRow<see cref="IFigure"/>.</param> /// <param name="fieldName">The fieldName<see cref="string"/>.</param> /// <param name="prefix">The prefix<see cref="string"/>.</param> /// <param name="tableName">The tableName<see cref="string"/>.</param> /// <returns>The <see cref="object"/>.</returns> public static object SqlNetVal(IFigure fieldRow, string fieldName, string prefix = "", string tableName = null) { object sqlNetVal = new object(); try { CultureInfo cci = CultureInfo.CurrentCulture; string decRep = (cci.NumberFormat.NumberDecimalSeparator == ".") ? "," : "."; string decSep = cci.NumberFormat.NumberDecimalSeparator, _tableName = ""; if (tableName != null) { _tableName = tableName; } else { _tableName = fieldRow.GetType().BaseType.Name; } if (!DbHand.Schema.DataDbTables.Have(_tableName)) { _tableName = prefix + _tableName; } if (DbHand.Schema.DataDbTables.Have(_tableName)) { Type ft = DbHand.Schema.DataDbTables[_tableName].DataDbColumns[fieldName + "#"].RubricType; if (DBNull.Value != fieldRow[fieldName]) { if (ft == typeof(decimal) || ft == typeof(float) || ft == typeof(double)) { sqlNetVal = Convert.ChangeType(fieldRow[fieldName].ToString().Replace(decRep, decSep), ft); } else if (ft == typeof(string)) { int maxLength = DbHand.Schema.DataDbTables[_tableName].DataDbColumns[fieldName + "#"].MaxLength; if (fieldRow[fieldName].ToString().Length > maxLength) { sqlNetVal = Convert.ChangeType(fieldRow[fieldName].ToString().Substring(0, maxLength), ft); } else { sqlNetVal = Convert.ChangeType(fieldRow[fieldName], ft); } } else if (ft == typeof(long) && fieldRow[fieldName] is Usid) { sqlNetVal = ((Usid)fieldRow[fieldName]).UniqueKey; } else if (ft == typeof(byte[]) && fieldRow[fieldName] is Ussn) { sqlNetVal = ((Ussn)fieldRow[fieldName]).GetBytes(); } else { sqlNetVal = Convert.ChangeType(fieldRow[fieldName], ft); } } else { fieldRow[fieldName] = DbNetTypes.SqlNetDefaults[ft]; sqlNetVal = Convert.ChangeType(fieldRow[fieldName], ft); } } else { sqlNetVal = fieldRow[fieldName]; } } catch (Exception ex) { // throw new Nnvalidnamespace System.Instant.Sqlset.Sq("\n" + ex + " - fieldName - " + fieldName); } return(sqlNetVal); }
private static bool CheckFigure(IFigure figure, string figureType, ChessColor color) { return(figure != null && figure.GetType().Name == figureType && figure.Color == color); }
public static bool IsFieldAttacked(IBoard board, Position position, ChessColor currentPlayerColor) { int startingRow = position.Row; char startingCol = position.Col; var otherPlayerColor = GetOtherPlayerColor(currentPlayerColor); if (currentPlayerColor == ChessColor.White) { Position positionTopLeft = new Position(startingRow + 1, (char)(startingCol - 1)); Position positionTopRight = new Position(startingRow + 1, (char)(startingCol + 1)); var diagonalPossiblePawnPositions = new List <Position>() { positionTopLeft, positionTopRight }; foreach (var possiblePosition in diagonalPossiblePawnPositions) { if (CheckForPawn(board, possiblePosition, otherPlayerColor)) { return(true); } } } if (currentPlayerColor == ChessColor.Black) { Position positionDownLeft = new Position(startingRow - 1, (char)(startingCol - 1)); Position positionDownRight = new Position(startingRow - 1, (char)(startingCol + 1)); var diagonalPossiblePawnPositions = new List <Position>() { positionDownLeft, positionDownRight }; foreach (var possiblePosition in diagonalPossiblePawnPositions) { if (CheckForPawn(board, possiblePosition, otherPlayerColor)) { return(true); } } } List <Position> possibleKnightPositions = GetPossibleKnightPositions(startingRow, startingCol); foreach (var possibleKnightPosition in possibleKnightPositions) { if (Position.CheckIsValid(possibleKnightPosition)) { IFigure figureAtPosition = board.GetFigureAtPosition(possibleKnightPosition); if (CheckFigure(figureAtPosition, "Knight", otherPlayerColor)) { return(true); } } } int row = startingRow; char col = startingCol; while (true) { row++; col++; Position currentPosition = new Position(row, col); if (!Position.CheckIsValid(currentPosition)) { break; } IFigure figure = board.GetFigureAtPosition(currentPosition); if (figure != null && figure.Color == currentPlayerColor) { break; } if (figure != null && figure.Color == otherPlayerColor) { if (figure.GetType().Name == "Bishop" || figure.GetType().Name == "Queen") { return(true); } else { break; } } } row = startingRow; col = startingCol; while (true) { row++; col--; Position currentPosition = new Position(row, col); if (!Position.CheckIsValid(currentPosition)) { break; } IFigure figure = board.GetFigureAtPosition(currentPosition); if (figure != null && figure.Color == currentPlayerColor) { break; } if (figure != null && figure.Color == otherPlayerColor) { if (figure.GetType().Name == "Bishop" || figure.GetType().Name == "Queen") { return(true); } else { break; } } } row = startingRow; col = startingCol; while (true) { row--; col--; Position currentPosition = new Position(row, col); if (!Position.CheckIsValid(currentPosition)) { break; } IFigure figure = board.GetFigureAtPosition(currentPosition); if (figure != null && figure.Color == currentPlayerColor) { break; } if (figure != null && figure.Color == otherPlayerColor) { if (figure.GetType().Name == "Bishop" || figure.GetType().Name == "Queen") { return(true); } else { break; } } } row = startingRow; col = startingCol; while (true) { row--; col++; Position currentPosition = new Position(row, col); if (!Position.CheckIsValid(currentPosition)) { break; } IFigure figure = board.GetFigureAtPosition(currentPosition); if (figure != null && figure.Color == currentPlayerColor) { break; } if (figure != null && figure.Color == otherPlayerColor) { if (figure.GetType().Name == "Bishop" || figure.GetType().Name == "Queen") { return(true); } else { break; } } } for (int i = startingRow + 1; i <= GlobalConstants.StandardGameTotalBoardRows; i++) { Position currentPosition = new Position(i, startingCol); if (!Position.CheckIsValid(currentPosition)) { break; } IFigure figure = board.GetFigureAtPosition(currentPosition); if (figure != null && figure.Color == currentPlayerColor) { break; } if (figure != null && figure.Color == otherPlayerColor) { if (figure.GetType().Name == "Rook" || figure.GetType().Name == "Queen") { return(true); } else { break; } } } for (int i = startingRow - 1; i >= GlobalConstants.MinimumRowValueOnBoard; i--) { Position currentPosition = new Position(i, startingCol); if (!Position.CheckIsValid(currentPosition)) { break; } IFigure figure = board.GetFigureAtPosition(currentPosition); if (figure != null && figure.Color == currentPlayerColor) { break; } if (figure != null && figure.Color == otherPlayerColor) { if (figure.GetType().Name == "Rook" || figure.GetType().Name == "Queen") { return(true); } else { break; } } } for (int i = (int)(startingCol) + 1; i <= GlobalConstants.StandardGameTotalBoardCols + 'a'; i++) { Position currentPosition = new Position(startingRow, (char)i); if (!Position.CheckIsValid(currentPosition)) { break; } IFigure figure = board.GetFigureAtPosition(currentPosition); if (figure != null && figure.Color == currentPlayerColor) { break; } if (figure != null && figure.Color == otherPlayerColor) { if (figure.GetType().Name == "Rook" || figure.GetType().Name == "Queen") { return(true); } else { break; } } } for (int i = startingCol - 1; i >= GlobalConstants.MinimumColumnValueOnBoard; i--) { Position currentPosition = new Position(startingRow, (char)i); if (!Position.CheckIsValid(currentPosition)) { break; } IFigure figure = board.GetFigureAtPosition(currentPosition); if (figure != null && figure.Color == currentPlayerColor) { break; } if (figure != null && figure.Color == otherPlayerColor) { if (figure.GetType().Name == "Rook" || figure.GetType().Name == "Queen") { return(true); } else { break; } } } List <Position> positionsAroundTheKing = GetPossibleKingPostions(startingRow, startingCol); foreach (var currentPosition in positionsAroundTheKing) { if (Position.CheckIsValid(currentPosition)) { IFigure currentFigure = board.GetFigureAtPosition(currentPosition); if (CheckFigure(currentFigure, "King", otherPlayerColor)) { return(true); } } } return(false); }
public IEnumerable <IFigureStyle> GetSupportedStyles(IFigure figure) { return(GetSupportedStyles(figure.GetType())); }
public void ValidateMove(IFigure figure, IBoard board, Move move) { var rowDistance = Math.Abs(move.From.Row - move.To.Row); var colDistance = Math.Abs(move.From.Col - move.To.Col); if (rowDistance != colDistance) { throw new InvalidOperationException(string.Format(GlobalErrorMessages.InvalidMove, figure.GetType().Name)); } var from = move.From; var to = move.To; int rowIndex = from.Row; char collIndex = from.Col; var rowDirection = to.Row > from.Row ? 1 : -1; var colDirection = to.Col > from.Col ? 1 : -1; //top-right while (true) { rowIndex += rowDirection; collIndex += (char)colDirection; // This is the finish position of the movement(TO position) // We already check if the position we want to move is owned by our figure, which means we always can move as there can be only opponent figure or null at this position if (rowIndex == to.Row && collIndex == to.Col) { return; } var position = Position.FromChessCoordinates(rowIndex, collIndex); if (board.CheckIfThereIsFigureAtPosition(position)) { throw new InvalidOperationException("There is a figure on your way!"); } } }
protected virtual string GetTagNameForFigure(IFigure figure) { return figure.GetType().Name; }
public void Run(IFactory stuffFactory) { factory = stuffFactory; bool validChoice = false; while (!validChoice) { string type = (factory.GetType().Name).Replace("Factory", ""); Console.WriteLine("Press 1 for male " + type); Console.WriteLine("Press 2 for female " + type); Console.WriteLine("Press 3 for sport " + type); ConsoleKey key = Console.ReadKey().Key; Console.WriteLine(); switch (key) { case ConsoleKey.D1: myFigure = stuffFactory.createMaleFigure(); validChoice = true; break; case ConsoleKey.D2: myFigure = stuffFactory.createFemaleFigure(); validChoice = true; break; case ConsoleKey.D3: myFigure = stuffFactory.createSportFigure(); validChoice = true; break; default: Console.WriteLine("Try again."); break; } } Random random = new Random(); Console.WriteLine("Press Escape stop game"); while (true) { if (Console.KeyAvailable) { ConsoleKey key = Console.ReadKey(true).Key; if (key == ConsoleKey.Escape) { break; } } if (totalSteps >= maxSteps) { break; } myFigure.jump(); myFigure.sing(); totalSteps += random.Next(0, 150); totalPoints += random.Next(1, 35); if (myFigure.GetType().Name.Contains("Sport")) { totalSteps += random.Next(0, 250); totalPoints += random.Next(1, 25); } Console.WriteLine("Points: " + totalPoints); Console.WriteLine("Progress: " + totalSteps + "/" + maxSteps); Console.WriteLine(); Thread.Sleep(1000); } Stop(); }