public bool CanGoTo(Square square, Owner owner, bool simulatePowerCard, bool drawErrors) { if ((simulatePowerCard || withPowerCard) && square.owner != owner && square.owner != Owner.NONE) return true; bool squareIsAvailable = square.owner == Owner.NONE && GameMaster.Instance.availableTokens > 0; if (drawErrors ) { Debug.Log("Cannot move to square because already occupied"); if ( square.owner == owner ) { PlayerTextHUD.Instance.StartFeedback(owner, "Can't move", "You already own this square."); } else if (square.owner != Owner.NONE) { if (GameMaster.Instance.GetHandHUDFor(owner).powerCardsCount > 0 ) PlayerTextHUD.Instance.StartFeedback(owner, "Square occupied", "You need a Power Card."); else PlayerTextHUD.Instance.StartFeedback(owner, "Can't move", "No Power Cards left."); } else if (GameMaster.Instance.availableTokens <= 0) { PlayerTextHUD.Instance.StartFeedback(owner, "Can't move", "No tokens available."); } } return squareIsAvailable; }
// readonly indexer - write is done through the interface methods public SquareContent this[Square square] { get { return board[square]; } }
public override bool IsLegalMove(Square origin, Square destination) { if (origin.Color == destination.Color) return false; if (origin.AlongFileOrRank(destination)) return true; return origin.DiagonallyTo(destination); }
/** * This class is intended to hold templates for any animations that need * to be created. * This was first created to allow easy creation of storyboards to be able * to highlight the board to show the ranks and files of the board seperately. */ /// <summary> /// Highlights a square with a given colour. The square flashes this given colour /// </summary> public static Storyboard NewHighlighter(Square s, Brush brush, int delay) { int beginFadeIn = 0; int beginFadeOut = beginFadeIn + 300; Duration duration = new Duration(TimeSpan.FromMilliseconds(200)); ColorAnimation fadeIn = new ColorAnimation() { From = ((SolidColorBrush)(s.rectangle.Fill)).Color, To = (brush as SolidColorBrush).Color, Duration = duration, BeginTime = TimeSpan.FromMilliseconds(beginFadeIn) }; ColorAnimation fadeOut = new ColorAnimation() { From = (brush as SolidColorBrush).Color, To = (s.rectangle.Fill as SolidColorBrush).Color, Duration = duration, BeginTime = TimeSpan.FromMilliseconds(beginFadeOut) }; Storyboard.SetTarget(fadeIn, s.rectangle); Storyboard.SetTargetProperty(fadeIn, new PropertyPath("Fill.Color")); Storyboard.SetTarget(fadeOut, s.rectangle); Storyboard.SetTargetProperty(fadeOut, new PropertyPath("Fill.Color")); Storyboard highlight = new Storyboard(); highlight.Children.Add(fadeIn); highlight.Children.Add(fadeOut); return highlight; }
public SquareGrid(int[,] map, float squareSize) { int nodeCountX = map.GetLength(0); int nodeCountY = map.GetLength(1); float mapWidth = nodeCountX * squareSize; float mapHeight = nodeCountY * squareSize; ControlNode[,] controlNodes = new ControlNode[nodeCountX, nodeCountY]; for (int x = 0; x < nodeCountX; x++) { for (int y = 0; y < nodeCountY; y++) { Vector3 pos = new Vector3(-mapWidth / 2 + x * squareSize + squareSize / 2, 0, -mapHeight / 2 + y * squareSize + squareSize / 2); controlNodes[x, y] = new ControlNode(pos, map[x, y] == 1, squareSize); } } Squares = new Square[nodeCountX - 1, nodeCountY - 1]; for (int x = 0; x < nodeCountX - 1; x++) { for (int y = 0; y < nodeCountY - 1; y++) { Squares[x, y] = new Square(controlNodes[x, y + 1], controlNodes[x + 1, y + 1], controlNodes[x + 1, y], controlNodes[x, y]); } } }
//nsew public Dictionary<string, int> calculateIndexOfNeighbors(Square square) { int index = square.getIndex(); Dictionary<string, int> neighborIndexes = new Dictionary<string,int>(); Dictionary<string, bool> neighboorBools = square.getNeighborInformation(); if(neighboorBools["north"] == true) { neighborIndexes.Add("n", index - width); } if (neighboorBools["south"] == true) { neighborIndexes.Add("s", index + width); } if (neighboorBools["east"] == true) { neighborIndexes.Add("e", index + 1); } if (neighboorBools["west"] == true) { neighborIndexes.Add("w", index - 1); } return neighborIndexes; }
void TriangulateSquare(Square square) { switch (square.configuration) { case 0: break; // 1 points: case 1: MeshFromPoints(square.centreBottom, square.bottomLeft, square.centreLeft); break; case 2: MeshFromPoints(square.centreRight, square.bottomRight, square.centreBottom); break; case 4: MeshFromPoints(square.centreTop, square.topRight, square.centreRight); break; case 8: MeshFromPoints(square.topLeft, square.centreTop, square.centreLeft); break; // 2 points: case 3: MeshFromPoints(square.centreRight, square.bottomRight, square.bottomLeft, square.centreLeft); break; case 6: MeshFromPoints(square.centreTop, square.topRight, square.bottomRight, square.centreBottom); break; case 9: MeshFromPoints(square.topLeft, square.centreTop, square.centreBottom, square.bottomLeft); break; case 12: MeshFromPoints(square.topLeft, square.topRight, square.centreRight, square.centreLeft); break; case 5: MeshFromPoints(square.centreTop, square.topRight, square.centreRight, square.centreBottom, square.bottomLeft, square.centreLeft); break; case 10: MeshFromPoints(square.topLeft, square.centreTop, square.centreRight, square.bottomRight, square.centreBottom, square.centreLeft); break; // 3 point: case 7: MeshFromPoints(square.centreTop, square.topRight, square.bottomRight, square.bottomLeft, square.centreLeft); break; case 11: MeshFromPoints(square.topLeft, square.centreTop, square.centreRight, square.bottomRight, square.bottomLeft); break; case 13: MeshFromPoints(square.topLeft, square.topRight, square.centreRight, square.centreBottom, square.bottomLeft); break; case 14: MeshFromPoints(square.topLeft, square.topRight, square.bottomRight, square.centreBottom, square.centreLeft); break; // 4 point: case 15: MeshFromPoints(square.topLeft, square.topRight, square.bottomRight, square.bottomLeft); break; } }
public static SquareList createSquareList(SquareList simpleList) { SquareList newList = new SquareList(); for (int i = simpleList.Count() - 1; i >= 0; i--) { Square cat = simpleList.Get(i); Square square = new Square(SurfaceWindow1.treeArea * cat.Ratio, cat.Name); square.setBackGround(cat.BackGroundColor); if (cat.TextColor == null) square.setTextColor(Colors.Black); else square.setTextColor(cat.TextColor); square.Ratio = cat.Ratio; if (cat.SubFile != null && !cat.SubFile.Equals("")) { square.SubFile = cat.SubFile; } if (cat.Explanation != null && !cat.Explanation.Equals("")) { square.Explanation = cat.Explanation; } if (cat.VideoString != null && !cat.VideoString.Equals("")) { square.VideoString = cat.VideoString; } if(cat.ImageString !=null && !cat.ImageString.Equals("")){ square.ImageString = cat.ImageString; } newList.Add(square); } return newList; }
private bool DestinationIsAttacked(Square destination) { var currentPosition = Board.GetPosition(); return currentPosition.SquaresOccupiedByPiecesWith(Color.GetOppositeColor()) .Any(opponentSquare => opponentSquare.Occupier.Attacks(opponentSquare, destination)); }
private Tuple<MoveNode, double> getChild(Square square) { instances++; MoveNode node = new MoveNode(board, square, evaluator); if (square.number == 2) return Tuple.Create(node, 0.9); else return Tuple.Create(node, 0.1); }
void setupBoard() { colors[0] = Color.Green; colors[1] = Color.Pink; colors[2] = Color.Purple; colors[3] = Color.SpringGreen; colors[4] = Color.Red; colors[5] = Color.Yellow; Random rnd = new Random(); for (int x = 0; x < 14; ++x) { for (int y = 0; y < 14; ++y) { Square s = new Square(); s.c = colors[rnd.Next(0,6)]; s.x = x; s.y = y; s.xPos = x * GridSize + GridPosX; s.yPos = y * GridSize + GridPosY; board[x, y] = s; } } root = board[0, 0]; root.root = true; root.rank = 99; for (int x = 0; x < 14; ++x) { for (int y = 0; y < 14; ++y) { Square s = board[x, y]; if (x > 0) s.left = board[x - 1, y]; if (x < 13) s.right = board[x + 1, y]; if (y > 0) s.up = board[x, y - 1]; if (y < 13) s.down = board[x, y + 1]; } } }
public Square SquareAt(int x, int y) { switch (Orientation) { case Orientation.North: return Piece.SquareAt(x, y); case Orientation.South: { var square = Piece.SquareAt(Width - x - 1, Height - y - 1); if (square != null) square = new Square(x, y, square.Colour); return square; } case Orientation.East: { var square = Piece.SquareAt(Height - y - 1, x); if (square != null) square = new Square(x, y, square.Colour); return square; } case Orientation.West: { var square = Piece.SquareAt(y, Width - x - 1); if (square != null) square = new Square(x, y, square.Colour); return square; } default: return null; } }
public override bool moveTo(Square s) { if (s != null) { if (s.isWalkable()) { if (s.mayContainBarricade()) { if (s.isOccupied()) { return false; } else { s.Piece = this; Square = s; Player.Baricade = null; Player = null; return true; } } } } return false; }
// tag::render[] /// <summary> /// Renders a single square on the given graphics context on the specified /// rectangle. /// /// <param name="square">The square to render.</param> /// <param name="g">The graphics context to draw on.</param> /// <param name="x">The x position to start drawing.</param> /// <param name="y">The y position to start drawing.</param> /// <param name="w">The width of this square (in pixels.)</param> /// <param name="h">The height of this square (in pixels.)</param> private void render(Square square, Graphics g, int x, int y, int w, int h) { square.Sprite.draw(g, x, y, w, h); foreach (Unit unit in square.Occupants) { unit.Sprite.draw(g, x, y, w, h); } }
public override void Move(Square origin, Square destination) { base.Move(origin, destination); HandleKingsideCastling(origin, destination); HandleQueensideCastling(origin, destination); }
private bool Attacking(Square origin, Square destination) { return (origin.Color != destination.Color && destination.Color != PieceColor.Empty && origin.DistanceOfRanksIsOneTo(destination) && origin.DiagonallyForwardTo(destination)); }
public int calculateIndexOfNeighbor(Square square, String orientation) { int index = square.getIndex(); Dictionary<string, bool> neighboorBools = square.getNeighborInformation(); if (orientation == "north") { return (index - width); } else if (orientation == "south") { return (index + width); } else if (orientation == "east") { return (index + 1); } else if (orientation == "west") { return (index - 1); } return index; }
public override void OnUpdate(long msec) { var tanks = from node in World.Downwards where node.Name == "MyTank" || node.Name == "EnemyTank" select node; foreach (var cmp in points.Components) { points.Detach (cmp); } foreach (var tank in tanks) { var spr = new Sprite (2, 2); spr.Color = Color.Black; spr.Offset = new Vector2 (tank.Translation.X / 10f, tank.Translation.Y / 10f); points.Attach (spr); } var cam = World.ActiveCamera; var frame = new Square (80, 60, 2); frame.Offset = new Vector3 (cam.Position.X / 10f, cam.Position.Y / 10f, cam.Position.Z / 10f); points.Attach (frame); }
public void ClickSquare(Square square) { if (this.Board == null || !this.Board.IsActive) return; var currentPiece = this.SelectedPiece; var targetPiece = this.Board[square]; if (currentPiece == targetPiece && targetPiece != null) { DrawSquare(SelectedPiece.Square, false); this.SelectedPiece = null; } else if (currentPiece != null) { DrawSquare(SelectedPiece.Square, false); this.SelectedPiece = null; if (this.Board.Move(currentPiece.Square, square, square.IsPromotionSquare() ? typeof(Pieces.Queen) : null)) this.Cursor = Cursors.Arrow; } else if (targetPiece != null && targetPiece.Player == this.Board.Turn) { if (this.PiecePicked != null) PiecePicked(square); this.SelectedPiece = targetPiece; DrawSquare(square, true); } }
public Square(int x, int y) { X = x; Y = y; Visited = false; Next = null; }
public void AttackedFrom_WhteRookE1KnightC3C4BlackRookA4TargetE4_ReturnsBitboardC3E1() { // arrange var white = new Side( "G1", new PieceSet<Queen>(), new PieceSet<Bishop>(), new PieceSet<Knight>(Bitboard.With.C3.C4), new PieceSet<Rook>(Bitboard.With.E1), new WhitePawns() ); var black = new Side( "G8", new PieceSet<Queen>(), new PieceSet<Bishop>(), new PieceSet<Knight>(), new PieceSet<Rook>(Bitboard.With.A4), new BlackPawns() ); var target = new Square("E4"); var expected = Bitboard.With.C3.E1.Build(); // act var result = target.AttackedFrom(white, black); // assert result.Should().Be(expected); }
public static int[,,] gen(VoxelTheme voxelTheme, IntVector3 size) { int [,,] mapData = new int[size.x, size.y, size.z]; int maxPercent = 30; int engineCount = 0; int percent = Random.Range (0, maxPercent); int iSquare = size.x * percent / 100; int kSquare = size.z * (maxPercent - percent - 1) / 100; Square baseSquare = new Square (iSquare, kSquare, size.x - 2 * iSquare, size.z - 2 * kSquare); mapData = MDController.combine (mapData, genPlatformBase (voxelTheme, size.x, size.z, baseSquare), 0, 0, 0); mapData = MDController.combine (mapData, genPlatformPlate (voxelTheme, baseSquare.width, baseSquare.height), baseSquare.x, 1, baseSquare.y); int minFractalSpacing = 1; foreach (Square square in ZTools.getFractalSquares(new Square( 0,0,baseSquare.width ,baseSquare.height),minFractalSpacing)) { int i = square.x + baseSquare.x; int k = square.y + baseSquare.y; int j = 1 + MDView.getMapHeight (mapData, i + square.width / 2, k + square.height / 2); mapData = MDController.combine (mapData, GreebleGenerator.gen (voxelTheme, square.width, size.y - j, square.height), i, j, k); if (Random.Range (0, engineCount / 3 + 1) == 0) { if (mapData.GetLength (1) > j) mapData [i + square.width / 2, j, k + square.height / 2] = voxelTheme.getCode ("engine"); engineCount++; } } return mapData; }
public void MovePiece(Square startingSquare, Square destinationSquare) { if (IsOutOfBounds(startingSquare, destinationSquare)) { PlayerMessage = "Illegal Move"; return; } var piece = _pieceLocations[startingSquare]; var otherPiece = _pieceLocations[destinationSquare]; if (otherPiece != null && !IsCapture(piece,otherPiece)) { PlayerMessage = "Illegal Move"; return; } if (piece.IsValidMove(startingSquare, destinationSquare, IsCapture(piece, otherPiece))) { _pieceLocations[startingSquare] = null; this.PlayerMessage = string.Format("{0} to {1}", piece.Name, destinationSquare); if(IsCapture(piece, otherPiece)) this.PlayerMessage += string.Format(". {0} takes {1}", piece.Name, otherPiece.Name); _pieceLocations[destinationSquare] = piece; } else PlayerMessage = "Illegal Move"; }
/// <summary> /// 駒の種類にかかわりなく、指定の位置に着手可能な指し手をすべて列挙します。 /// </summary> public IEnumerable<BoardMove> ListupMoves(BWType bwType, Square dstSquare) { // 打てる駒をすべて列挙します。 foreach (var pieceType in EnumEx.GetValues<PieceType>()) { if (GetCapturedPieceCount(pieceType, bwType) <= 0) { continue; } var move = new BoardMove() { DstSquare = dstSquare, DropPieceType = pieceType, BWType = bwType, }; // 駒打ちが可能なら、それも該当手となります。 if (CanMove(move, MoveFlags.CheckOnly)) { yield return move; } } // 移動による指し手をすべて列挙します。 foreach (var srcSquare in Board.AllSquares()) { var moves = GetAvailableMove(bwType, srcSquare, dstSquare); foreach (var move in moves) { yield return move; } } }
/// <summary> /// Renders a single square on the given graphics context on the specified /// rectangle. /// /// <param name="square">The square to render.</param> /// <param name="g">The graphics context to draw on.</param> /// <param name="r">The position and dimension for rendering the square.</param> // tag::render[] private void Render(Square square, Graphics g, Rectangle r) { Point position = r.Position; square.Sprite.Draw(g, r); foreach (Unit unit in square.Occupants) { unit.Sprite.Draw(g, r); } }
//TODO: fixup display of numbers to match .net static void Main() { // Input the side: System.Console.Write("Enter the side: "); double side = 5;//double.Parse(System.Console.ReadLine()); // Compute the areas: Square s = new Square(side); Cube c = new Cube(side); // Display the results: System.Console.Write("Area of the square ="); System.Console.WriteLine(s.Area); System.Console.Write("Area of the cube ="); System.Console.WriteLine(c.Area); // System.Console.WriteLine(); // Input the area: System.Console.Write("Enter the area: "); double area = 125; //double.Parse(System.Console.ReadLine()); // Compute the sides: s.Area = area; c.Area = area * 6; // Display the results: System.Console.Write("Side of the square = "); System.Console.WriteLine((int)s.side); System.Console.Write("Side of the cube = "); System.Console.WriteLine((int)c.side); }
public static void Main() { Square square = new Square(0, 0, 10); Rectangle rect = new Rectangle(0, 0, 10, 12); Circle circle = new Circle(0, 0, 5); if (square is IShape) { Console.WriteLine("{0} is IShape", square.GetType()); } if (rect is IResizable) { Console.WriteLine("{0} is IResizable", rect.GetType()); } if (circle is IResizable) { Console.WriteLine("{0} is IResizable", circle.GetType()); } IShape[] shapes = { square, rect, circle }; foreach (IShape shape in shapes) { shape.SetPosition(5, 5); Console.WriteLine( "Type: {0}; surface: {1}", shape.GetType(), shape.CalculateSurface()); } }
/// <summary> /// <paramref name="srcSquare"/>の駒を<paramref name="dstSquare"/> /// に動かすことが可能な指し手をすべて列挙します。 /// </summary> private IEnumerable<BoardMove> GetAvailableMove(BWType bwType, Square srcSquare, Square dstSquare) { var piece = this[srcSquare]; if (piece == null || piece.BWType != bwType) { yield break; } var move = new BoardMove() { DstSquare = dstSquare, SrcSquare = srcSquare, MovePiece = piece.Piece, BWType = bwType, }; // 成り駒でなければ、成る可能性があります。 if (!piece.IsPromoted) { move.IsPromote = true; if (CanMove(move, MoveFlags.CheckOnly)) { // yield returnなのでCloneしないとまずい。 yield return move.Clone(); } } move.IsPromote = false; if (CanMove(move, MoveFlags.CheckOnly)) { yield return move; } }
public MainForm() { InitializeComponent(); controller = new Controller(this); int panelWidth = this.MainBoard.Width; int squareMargin = 10; int width = panelWidth / 4; int size = 150; blocks = new Square[4, 4]; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { Square block = new Square(); blocks[i, j] = block; block.Left = j * size; block.Top = i * size; block.Width = size; block.Height = size; block.Visible = true; block.BackColor = Color.FromArgb(0, 100, 100, 100); block.Margin = new Padding(squareMargin); MainBoard.Controls.Add(block); } } }
/** * Set piece to move to specified square * TODO: make it an arc instead of teleport */ public override void moveToDest(Square s) { tile.Occupant = null; s.Occupant = this; this.tile = s; ((Transform)this.GetComponent (typeof(Transform))).localPosition = s.Position; }
public Rook(Color color, Square square) : base(color, square) { Type = Type.Rook; }
public override Piece Clone(Square square) => new Rook(Color, square);
public IEnumerator CalcularPossibleAttacks() { BoardSpec boardSpec = BoardSpec.getInstance(); foreach (GameObject gameObject in gameObjects) { Player target = gameObject.GetComponent <Player>(); if (target != null && target.status.isDead) { continue; } Square mainSquare = boardSpec.SquareFromWorldPoint(main.transform.position); Square targetSquare = boardSpec.SquareFromWorldPoint(target.transform.position); int distanciaEstimadaInimigo = BoardSpec.GetSquareDistance(mainSquare, targetSquare); //Ataque Basico if (target.isAliado) { CheckPossibleAttack(target, null, distanciaEstimadaInimigo); } List <Habilidade> habilidades = main.action.Habilidades.habilidades; foreach (Habilidade habilidade in habilidades) { if (habilidade.custoPontoAcao > pontosDeAcao || habilidade.IsOfensiva && !target.isAliado || habilidade.custoSp > main.status.mana) { continue; } if (habilidade.minDistancia == 0 && habilidade.maxDistancia == 0 && target.name != main.name) { continue; } CheckPossibleAttack(target, habilidade, distanciaEstimadaInimigo); } yield return(null); } Pathfinding pathfinding = null; List <Vector2> moves = null; bool apenasMovimenta = true; if (possibleAttacks.Count > 0) { apenasMovimenta = false; Player target = null; int cont = 0; int totalCost = 0; MyDictionary dict = new MyDictionary(); PossibleAttack greatestAttack = null; foreach (PossibleAttack possibleAttack in possibleAttacks) { if (target == null || target.name != possibleAttack.targetName || possibleAttack.isRanged) { target = possibleAttack.Target; pathfinding = new Pathfinding(); Vector2 pos = new Vector2(); if (possibleAttack.isRangedInDanger) { pos = RunAndGun(target, possibleAttack.minDist); } else if (possibleAttack.isRanged) { pos = LongShot(target, possibleAttack.maxDist, possibleAttack.minDist); } else { pos = target.transform.position; } pathfinding.FindPath(main.transform.position, pos); yield return(new WaitUntil(() => pathfinding.ready)); moves = pathfinding.getMoveInstructions(); yield return(null); } // verificar se distancia no pathfinder é diferente que distanciaEstimada - 1, pois não conta o quadrado do alvo if ((possibleAttack.distanciaEstimada - 1) != moves.Count) { possibleAttack.distanciaEstimada = pathfinding.minSize; possibleAttack.CalcularCustoPontoAcaoEstimado(); if (possibleAttack.actionPointCost <= pontosDeAcao) { possibleAttack.CalcularCusto(dificuldade); } else { cont++; continue; } } possibleAttack.moves = moves; dict.Add(cont, totalCost + 1, totalCost + possibleAttack.cost, possibleAttack, possibleAttack.cost); totalCost += possibleAttack.cost; cont++; if (greatestAttack == null || greatestAttack.cost < possibleAttack.cost) { greatestAttack = possibleAttack; } } if (dict.Count != 0 && totalCost > 0) { yield return(null); if (dificuldade.Equals(Dificuldade.MEDIO)) { bool continueLoop = true; int cost = 60; while (continueLoop) { var listPossibleAttack = dict.Where(myval => myval.Value.cost >= cost); if (listPossibleAttack != null && listPossibleAttack.Count() > 0) { continueLoop = false; dict = new MyDictionary(); cont = 0; int newTotalCost = 0; foreach (KeyValuePair <int, MyValue> item in listPossibleAttack.ToList()) { dict.Add(cont, newTotalCost + 1, newTotalCost + item.Value.cost, item.Value.possibleAttack, item.Value.cost); newTotalCost = item.Value.cost; cont++; } totalCost = newTotalCost; } else { cost -= 10; } } } if (!dificuldade.Equals(Dificuldade.DIFICIL)) { int random = Random.Range(1, totalCost); try { // Pega lista IEnumerable <KeyValuePair <int, MyValue> > asd = dict.Where(myval => myval.Value.pos1 <= random && myval.Value.pos2 >= random); var itens = asd.ToList(); // Pega primeiro item da lista, pois a lista possui apenas 1 item ataqueEscolhido = itens[0].Value.possibleAttack; } catch (Exception e) { Debug.Log(e); Debug.Log(e.Message); Debug.Log(e.Data); yield break; } } else { ataqueEscolhido = greatestAttack; } if (ataqueEscolhido == null) { apenasMovimenta = true; } else { foreach (Vector2 position in ataqueEscolhido.moves) { main.move.NpcMove((int)position.x, (int)position.y); } main.move.Move(); yield return(null); if (ataqueEscolhido.isBasicAttack) { main.action.Attack(ataqueEscolhido.targetName); } else { main.action.Ability(ataqueEscolhido.habilidade.nome, ataqueEscolhido.targetName); } yield return(null); } } else { apenasMovimenta = true; } } if (apenasMovimenta) { int qtyMoves = -1; foreach (GameObject gameObject in gameObjects) { Player target = gameObject.GetComponent <Player>(); if (target != null && (target.status.isDead || !target.isAliado)) { continue; } pathfinding = new Pathfinding(); pathfinding.FindPath(main.transform.position, target.transform.position); yield return(new WaitUntil(() => pathfinding.ready)); if (qtyMoves == -1 || qtyMoves > pathfinding.minSize) { qtyMoves = pathfinding.minSize; moves = pathfinding.getMoveInstructions(); } yield return(null); } if (moves != null) { foreach (Vector2 position in moves) { main.move.NpcMove((int)position.x, (int)position.y); } main.move.Move(); } } yield break; }
public Square GetRight(Square sq) { return(squares [sq.col - 'A' + 1, sq.row - '1']); }
private void RenderCanvas() { var side = 485; // Back _backSquare = new Square { Side = 600, Fill = Colors.LightSteelBlue, Height = Canvas.Height, Width = Canvas.Width, CenterPointX = 500, CenterPointY = 500, RotationCenterX = 500, RotationCenterY = 500 }; Canvas.Children.Add(_backSquare); // Front var square = new Square { Side = side, Fill = Colors.LightSlateGray, Height = Canvas.Height, Width = Canvas.Width, CenterPointX = side / 2, CenterPointY = side / 2 }; Canvas.Children.Add(square); square = new Square { Side = side, Fill = Colors.LightSlateGray, Height = Canvas.Height, Width = Canvas.Width, CenterPointX = 1000 - side / 2, CenterPointY = side / 2 }; Canvas.Children.Add(square); square = new Square { Side = side, Fill = Colors.LightSlateGray, Height = Canvas.Height, Width = Canvas.Width, CenterPointX = side / 2, CenterPointY = 1000 - side / 2 }; Canvas.Children.Add(square); square = new Square { Side = side, Fill = Colors.LightSlateGray, Height = Canvas.Height, Width = Canvas.Width, CenterPointX = 1000 - side / 2, CenterPointY = 1000 - side / 2 }; Canvas.Children.Add(square); }
public Square GetLowerRight(Square sq) { return(squares [sq.col - 'A' + 1, sq.row - '1' - 1]); }
///For each square, determine which configuration case it is out of the 16 kinds void ConfigureTriangles(Square s) { switch (s.configuration) { case 0: break; case 1: ConnectMesh(s.cn_bottomLeft, s.n_midLeft, s.n_midBottom); //TODO case 1,2,4,8: to show [inner outline triangles] correctly, these outline vertex needs to be in order, outline vertex order is initially defined in here //I think, when find next outline vertex, function loop through triangle vertex, and return the first one, so this order here decides the loop order break; case 2: ConnectMesh(s.cn_bottomRight, s.n_midBottom, s.n_midRight); break; case 3: ConnectMesh(s.n_midRight, s.cn_bottomRight, s.cn_bottomLeft, s.n_midLeft); break; case 4: ConnectMesh(s.cn_topRight, s.n_midRight, s.n_midTop); break; case 5: ConnectMesh(s.n_midTop, s.cn_topRight, s.n_midRight, s.n_midBottom, s.cn_bottomLeft, s.n_midLeft); break; case 6: ConnectMesh(s.n_midTop, s.cn_topRight, s.cn_bottomRight, s.n_midBottom); break; case 7: ConnectMesh(s.n_midTop, s.cn_topRight, s.cn_bottomRight, s.cn_bottomLeft, s.n_midLeft); break; case 8: ConnectMesh(s.cn_topLeft, s.n_midTop, s.n_midLeft); break; case 9: ConnectMesh(s.cn_topLeft, s.n_midTop, s.n_midBottom, s.cn_bottomLeft); break; case 10: ConnectMesh(s.cn_topLeft, s.n_midTop, s.n_midRight, s.cn_bottomRight, s.n_midBottom, s.n_midLeft); break; case 11: ConnectMesh(s.cn_topLeft, s.n_midTop, s.n_midRight, s.cn_bottomRight, s.cn_bottomLeft); break; case 12: ConnectMesh(s.cn_topLeft, s.cn_topRight, s.n_midRight, s.n_midLeft); break; case 13: ConnectMesh(s.cn_topLeft, s.cn_topRight, s.n_midRight, s.n_midBottom, s.cn_bottomLeft); break; case 14: ConnectMesh(s.cn_topLeft, s.cn_topRight, s.cn_bottomRight, s.n_midBottom, s.n_midLeft); break; case 15: ConnectMesh(s.cn_topLeft, s.cn_topRight, s.cn_bottomRight, s.cn_bottomLeft); //these vertex cannot be outline vertex, this is an optimization checkedVertices.Add(s.cn_topLeft.id); checkedVertices.Add(s.cn_topRight.id); checkedVertices.Add(s.cn_bottomLeft.id); checkedVertices.Add(s.cn_bottomRight.id); break; default: break; } }
public Player(Square square, string name, Shapes shape) : base(square, name, shape) { Points = 0; ToGatherItemsList = new List <IGatherable>(); }
public static void Main(String[] args) { // Basic rules of type dynamic { dynamic d1 = 34; int i1 = d1 * 2; // OK: cast (int)(d1*2) at run-time int i2 = (int)d1 * 2; // OK: cast (int)d1 at run-time // bool b1 = d1; // Compiles OK; cast (bool)d1 throws at run-time d1 = true; // OK bool b2 = d1; // OK: cast (bool)d1 succeeds at run-time dynamic p1 = new Phone("Kasper", 5170); String s1 = p1.name; // Field access checked at run-time // int n1 = p1.age; // Compiles OK; field access throws at run-time dynamic p2 = new { name = "Kasper", phone = 5170 }; String s2 = p2.name; // Field access checked at run-time // int n2 = p2.age; // Compiles OK; fields access throws at run-time } // Dynamic operator resolution; run-time type determines meaning of "+" in Plus2() { Console.WriteLine(Plus2(int.MaxValue-1)); // -2147483648, due to int overflow Console.WriteLine(Plus2((long)(int.MaxValue-1))); // 2147483648, no long overflow Console.WriteLine(Plus2(11.5)); // 13.5 Console.WriteLine(Plus2("Spar")); // Spar2 // Console.WriteLine(Plus2(false)); // Compiles OK; throws RuntimeBinderException } // Dynamic receiver; run-time type determines whether to call Length on array or String { dynamic v; if (args.Length==0) v = new int[] { 2, 3, 5, 7 }; else v = "abc"; int res = v.Length; Console.WriteLine(res); } // Dynamic overload resolution; run-time type of v determines which Process called at (**) { dynamic v; if (args.Length==0) v = 5; else if (args[0] == "1") v = "abc"; else v = (Func<int,int>)(x => x*3); dynamic r = Process(v); // (**) if (args.Length==0 || args[0] == "1") Console.WriteLine(r); else Console.WriteLine(r(11)); dynamic s = "abc"; Console.WriteLine(Process(s).StartsWith("abca")); } // Run-time type tests { Console.WriteLine(Square(5)); Console.WriteLine(Square("abc")); Func<int,int> f = x => x*3; Console.WriteLine(Square(f)(11)); } { // Types dynamic[], List<dynamic>, IEnumerable<dynamic> dynamic[] arr = new dynamic[] { 19, "Electric", (Func<int,int>)(n => n+2), 3.2, false }; int number = arr[0] * 5; String street = arr[1].ToUpper(); int result = arr[2](number); Console.WriteLine(number + " " + street); double sum = 0; List<dynamic> list = new List<dynamic>(arr); IEnumerable<dynamic> xs = list; foreach (dynamic x in xs) if (x is int || x is double) sum += x; Console.WriteLine(sum); // 22.2 } // Dynamic and anonymous object expressions { dynamic v = new { x = 34, y = false }; Console.WriteLine(v.x); } }
static void Main(string[] args) { #region Rectangle Console.WriteLine("------------------ Task 1 ------------------\n"); Rectangle rectangle = new Rectangle(); Console.Write("Please, enter upper left point X coordinate: "); rectangle.upperLeftX = Convert.ToInt32(Console.ReadLine()); Console.Write("Please, enter upper left point Y coordinate: "); rectangle.upperLeftY = Convert.ToInt32(Console.ReadLine()); Console.Write("Please, enter down right point X coordinate: "); rectangle.downRightX = Convert.ToInt32(Console.ReadLine()); Console.Write("Please, enter down right point Y coordinate: "); rectangle.downRightY = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Square is: " + rectangle.Square()); Console.WriteLine("Perimeter is: " + rectangle.Perimeter()); #endregion #region Circle Circle circle = new Circle(); Console.Write("Please, enter the radius of the circle: "); circle.radius = Convert.ToDouble(Console.ReadLine()); circle.CircleLenght(); circle.CircleSquare(); #endregion #region Complex Number Console.Write("Please, enter first real part: "); double real1 = Convert.ToDouble(Console.ReadLine()); Console.Write("Please, enter first imaginary part: "); double imaginary1 = Convert.ToDouble(Console.ReadLine()); Console.Write("Please, enter second real part: "); double real2 = Convert.ToDouble(Console.ReadLine()); Console.Write("Please, enter second imaginary part: "); double imaginary2 = Convert.ToDouble(Console.ReadLine()); ComplexNumber firstComplex = new ComplexNumber(real1, imaginary1); ComplexNumber secondComplex = new ComplexNumber(real2, imaginary2); ComplexNumber multiplying = firstComplex * secondComplex; Console.WriteLine($"Multipling of complex numbers = {multiplying.Real} + {multiplying.Imiginary}i"); ComplexNumber dividing = firstComplex / secondComplex; Console.WriteLine($"Dividing of complex numbers = {dividing.Real} + {dividing.Imiginary}i"); #endregion #region Draw Console.WriteLine("\n------------------ Task 2 ------------------\n"); Rectangle_2 r = new Rectangle_2(); r.Draw(); Square s = new Square(); s.Draw(); #endregion #region Collections Console.WriteLine("\n------------------ Task 3 ------------------\n"); Console.WriteLine("Display name and age of each created person:\n"); var people = new List <Person> { new Person { Name = "Emma", Age = 18, PhoneNumbers = new List <string>() { "+ Kyivstar", "+ Life", "+ Vodafone" } }, new Person { Name = "Olivia", Age = 19, PhoneNumbers = new List <string>() { "+ Kyivstar", "+ Life", "+ Vodafone" } }, new Person { Name = "Ava", Age = 20, PhoneNumbers = new List <string>() { "+ Kyivstar", "+ Life", "+ Vodafone" } }, new Person { Name = "Isabella", Age = 21, PhoneNumbers = new List <string>() { "+ Kyivstar", "+ Life", "+ Vodafone" } }, new Person { Name = "Sophia", Age = 22, PhoneNumbers = new List <string>() { "+ Kyivstar", "+ Life", "+ Vodafone" } }, new Person { Name = "Charlotte", Age = 23, PhoneNumbers = new List <string>() { "+ Kyivstar", "+ Life", "+ Vodafone" } }, }; foreach (var person in people) { Console.WriteLine("Name: {0}, Age: {1}", person.Name, person.Age); } Console.WriteLine("\nPhone numbers of all created persons:\n"); people.AddRange(new List <Person> { new Person { Name = "Mia", Age = 24, PhoneNumbers = new List <string>() { "+ Kyivstar", "+ Life", "+ Vodafone" } }, new Person { Name = "Amelia", Age = 25, PhoneNumbers = new List <string>() { "+ Kyivstar", "+ Life", "+ Vodafone" } } }); foreach (var person in people) { Console.WriteLine("Name: {0}", person.Name); foreach (var number in person.PhoneNumbers) { Console.WriteLine($"{number}"); } } Console.WriteLine("\nList of randomly generated elements:\n"); RandomString random = new RandomString(); random.ElementsNumber(); random.DisplayPage(); #endregion Console.ReadKey(); }
void OnCollisionEnter(Collision col) { Signal collision = new Square(collisionFreq) * new ASR(0.05, 0.05, 0.05); syntacts.session.Play(collisionChannel, collision); }
public void ToString_() { Square square = new Square(0, 0, 1, new Color("Red")); Assert.That(square.ToString(), Is.EqualTo("Square: (0:0) edgeLength=1 color=#FF0000")); }
public void SquaredTest() { Assert.AreEqual(81, Square.Squared(a)); }
internal Board Move(Square from, Square to) => Move(this, from, to);
public void SquaredTest1() { Assert.AreEqual(1.2100000000000002, Square.Squared(b)); }
public Square GetLowerLeft(Square sq) { return(squares [sq.col - 'A' - 1, sq.row - '1' - 1]); }
public King(Square square, Board board, PieceColor color) : base(square, board, color) { }
public PlayElement(Square square, string name, Shapes shape) { CurrentSquare = square; Name = name; Shape = shape; }
internal bool IsCheck(ChessGame game, Square kingSquare) => CanCaptureKing(game, kingSquare);
static void Main(string[] args) { // assign the body of the delegate as a lambda expression // 'x' in this example, represents the input value of the function Square squareDelegate = x => (int)Math.Pow(x, 2); // invoke our delegate var result = squareDelegate(10); // print the result Console.WriteLine($"The result is: {result}"); Func <int, bool> isEvenFunc = x => x % 2 == 0; Expression <Func <int, bool> > isEvenExpression = x => x % 2 == 0; var funcResult = isEvenFunc(5); // isEvenExpression(5); var compiledExpression = isEvenExpression.Compile(); var expressionResult = compiledExpression.Invoke(10); Console.WriteLine($"The funcResult is: {funcResult}"); Console.WriteLine($"The expressionResult is: {expressionResult}"); // x - is the 'temp' variable that // represents the input variable to the function // '=>' lambda operator // the 'left' side of the lambda operator is at least one or more // input variables to the function // the 'right' side of the lambda operator is the actual body // of the function to execute Expression <Func <double, bool> > isOddExpression = x => x % 2 != 0; // this expression has 2 parameters // the first in an integer // the second is an integer // the return type is bool // the return type of a Func<..> is always the type of the last listed parameter Expression <Func <int, int, bool> > multiInputExpression = (x, y) => x > 5 && y > 5; // this is a no input expression // the return type the first type of the list of parameters Expression <Func <bool> > noInputExpression = () => true; // using the var keyword allows us to infer the type // without the explicit declaration var myString = "test"; // the following line will result in an error because // it's impossible for the compiler to determine the type of // our variable 'unknownData' //var unknownData = null; // an async lambda cannot be an Expression // because the value of the func, must be re-evaluated each time // the function is run Func <Task <bool> > asyncLambda = async() => { await Task.Delay(2000); //Console.WriteLine("after 2 seconds of delay"); return(true); }; }
public PropertySquare(string _name, Square _nextSquare) { this.name = _name; this.nextSquare = null; }
public async Task ReadAsync(TProtocol iprot, CancellationToken cancellationToken) { iprot.IncrementRecursionDepth(); try { TField field; await iprot.ReadStructBeginAsync(cancellationToken); while (true) { field = await iprot.ReadFieldBeginAsync(cancellationToken); if (field.Type == TType.Stop) { break; } switch (field.ID) { case 1: if (field.Type == TType.Struct) { Square = new Square(); await Square.ReadAsync(iprot, cancellationToken); } else { await TProtocolUtil.SkipAsync(iprot, field.Type, cancellationToken); } break; case 2: if (field.Type == TType.Struct) { Creator = new SquareMember(); await Creator.ReadAsync(iprot, cancellationToken); } else { await TProtocolUtil.SkipAsync(iprot, field.Type, cancellationToken); } break; case 3: if (field.Type == TType.Struct) { Authority = new SquareAuthority(); await Authority.ReadAsync(iprot, cancellationToken); } else { await TProtocolUtil.SkipAsync(iprot, field.Type, cancellationToken); } break; case 4: if (field.Type == TType.Struct) { Status = new SquareStatus(); await Status.ReadAsync(iprot, cancellationToken); } else { await TProtocolUtil.SkipAsync(iprot, field.Type, cancellationToken); } break; default: await TProtocolUtil.SkipAsync(iprot, field.Type, cancellationToken); break; } await iprot.ReadFieldEndAsync(cancellationToken); } await iprot.ReadStructEndAsync(cancellationToken); } finally { iprot.DecrementRecursionDepth(); } }
/// <summary> /// Converts image data transfer object to an entity /// </summary> /// <returns>Entity object</returns> private ComplexShape ConvertDTOToComponent(CreateComplexShapeRequestDTO complexShapeDto) { var complexShape = new ComplexShape(); complexShape.Id = complexShapeDto.Id; complexShape.Name = complexShapeDto.Name; if (complexShape.Effects != null) { foreach (var effect in complexShapeDto.Effects) { complexShape.Effects.Add(effect); } } foreach (var shape in complexShapeDto.Shapes) { BaseObject component = null; switch (shape.Type) { case "Square": { component = new Square() { Effects = shape.Effects, PositionX = shape.StartPositionX, PositionY = shape.StartPositionY, Width = shape.Width }; break; } case "Circle": { component = new Circle() { Effects = shape.Effects, PositionX = shape.StartPositionX, PositionY = shape.StartPositionY, Radius = shape.Width }; break; } case "Line": { component = new Line() { Effects = shape.Effects, PositionX = shape.StartPositionX, PositionY = shape.StartPositionY, EndPositionX = shape.EndPositionX, EndPositionY = shape.EndPositionY }; break; } default: break; } if (component != null) { complexShape.AddShape(component); } } return(complexShape); }
public Square GetUpper(Square sq) { return(squares [sq.col - 'A', sq.row - '1' + 1]); }
public void Execute() { int w = 4; IShape square = new Square(w); }
public async Task WriteAsync(TProtocol oprot, CancellationToken cancellationToken) { oprot.IncrementRecursionDepth(); try { var struc = new TStruct("CreateSquareResponse"); await oprot.WriteStructBeginAsync(struc, cancellationToken); var field = new TField(); if (Square != null && __isset.square) { field.Name = "square"; field.Type = TType.Struct; field.ID = 1; await oprot.WriteFieldBeginAsync(field, cancellationToken); await Square.WriteAsync(oprot, cancellationToken); await oprot.WriteFieldEndAsync(cancellationToken); } if (Creator != null && __isset.creator) { field.Name = "creator"; field.Type = TType.Struct; field.ID = 2; await oprot.WriteFieldBeginAsync(field, cancellationToken); await Creator.WriteAsync(oprot, cancellationToken); await oprot.WriteFieldEndAsync(cancellationToken); } if (Authority != null && __isset.authority) { field.Name = "authority"; field.Type = TType.Struct; field.ID = 3; await oprot.WriteFieldBeginAsync(field, cancellationToken); await Authority.WriteAsync(oprot, cancellationToken); await oprot.WriteFieldEndAsync(cancellationToken); } if (Status != null && __isset.status) { field.Name = "status"; field.Type = TType.Struct; field.ID = 4; await oprot.WriteFieldBeginAsync(field, cancellationToken); await Status.WriteAsync(oprot, cancellationToken); await oprot.WriteFieldEndAsync(cancellationToken); } await oprot.WriteFieldStopAsync(cancellationToken); await oprot.WriteStructEndAsync(cancellationToken); } finally { oprot.DecrementRecursionDepth(); } }
public static void show(Square square) { Debug.Log(" x: " + square.x + " y: " + square.y + " width: " + square.width + " height: " + square.height); }
void TriangulateSquare(Square square) { switch (square.configuration) { case 0: break; //1point case 1: MeshFromPoints(square.centerLeft, square.centerBottom, square.bottomLeft); break; case 2: MeshFromPoints(square.bottomRight, square.centerBottom, square.centerRight); break; case 4: MeshFromPoints(square.topRight, square.centerRight, square.centerTop); break; case 8: MeshFromPoints(square.topLeft, square.centerTop, square.centerLeft); break; //2points case 3: MeshFromPoints(square.centerRight, square.bottomRight, square.bottomLeft, square.centerLeft); break; case 6: MeshFromPoints(square.centerTop, square.topRight, square.bottomRight, square.centerBottom); break; case 9: MeshFromPoints(square.topLeft, square.centerTop, square.centerBottom, square.bottomLeft); break; case 12: MeshFromPoints(square.topLeft, square.topRight, square.centerRight, square.centerLeft); break; case 5: MeshFromPoints(square.centerTop, square.topRight, square.centerRight, square.centerBottom, square.bottomLeft, square.centerLeft); break; case 10: MeshFromPoints(square.topLeft, square.centerTop, square.centerRight, square.bottomRight, square.centerBottom, square.centerLeft); break; //3points case 7: MeshFromPoints(square.centerTop, square.topRight, square.bottomRight, square.bottomLeft, square.centerLeft); break; case 11: MeshFromPoints(square.topLeft, square.centerTop, square.centerRight, square.bottomRight, square.bottomLeft); break; case 13: MeshFromPoints(square.topLeft, square.topRight, square.centerRight, square.centerBottom, square.bottomLeft); break; case 14: MeshFromPoints(square.topLeft, square.topRight, square.bottomRight, square.centerBottom, square.centerLeft); break; //4point case 15: MeshFromPoints(square.topLeft, square.topRight, square.bottomRight, square.bottomLeft); checkedVertices.Add(square.topLeft.vertexIndex); checkedVertices.Add(square.topRight.vertexIndex); checkedVertices.Add(square.bottomRight.vertexIndex); checkedVertices.Add(square.bottomLeft.vertexIndex); break; } }
public void CalculateArea() { Square square = new Square(0, 0, 2); Assert.That(square.Calculate(), Is.EqualTo(4)); }
public IActionResult Catalog(CatalogViewModel catalogViewModel) { if ((ModelState.IsValid) & (catalogViewModel.Sidelength == 0)) { Random random = new Random(); catalogViewModel.Sidelength = random.Next(0, 1000); } if ((ModelState.IsValid) & (catalogViewModel.Sidelength > 0)) { List <Shape> TheList = context.Shapes.ToList(); if (catalogViewModel.Shapetype == "Random") { Random random = new Random(); int Shapetyp = random.Next(0, 3); if (Shapetyp == 0) { catalogViewModel.Shapetype = "Segment"; } if (Shapetyp == 1) { catalogViewModel.Shapetype = "Square"; } if (Shapetyp == 2) { catalogViewModel.Shapetype = "Cube"; } } if (catalogViewModel.Shapetype == "Cube") { Cube Cube = new Cube("Cube", catalogViewModel.Sidelength); context.Shapes.Add(Cube); TheList.Add(Cube); } if (catalogViewModel.Shapetype == "Square") { Square Square = new Square("Square", catalogViewModel.Sidelength); context.Shapes.Add(Square); TheList.Add(Square); } if (catalogViewModel.Shapetype == "Segment") { Segment Segment = new Segment("Segment", catalogViewModel.Sidelength); context.Shapes.Add(Segment); TheList.Add(Segment); } context.SaveChanges(); catalogViewModel.TheList = TheList; return(View(catalogViewModel)); } return(Redirect("/Home/Error")); }