public void Update(Turtle t) { using (Graphics g = Graphics.FromImage(frame)) { float newX = TurtleToScreenX(t.X); float newY = TurtleToScreenY(t.Y); if (t.PenDrawing) { g.DrawLine(t.Pen, lastX, lastY, newX, newY); } lastX = newX; lastY = newY; } if(final != null) final.Dispose(); final = (Bitmap)frame.Clone(); if(t.Visible) { // TODO: Image of turtle /*using(Graphics g = Graphics.FromImage(overlay)) { g.DrawImage() }*/ } if(ScreenUpdate != null && !t.Fast) { ScreenUpdate(final); } }
public void TestLeft() { Turtle t = new Turtle(); t.Left(10); Assert.AreEqual(10, t.Angle); }
public void TestRight() { Turtle t = new Turtle(); t.Right(10); Assert.AreEqual(350, t.Angle); }
public static void Main() { Turtle turtle = new Turtle(); Console.WriteLine(turtle); Console.WriteLine("The {0} can go {1} km/h ", turtle.GetName(), turtle.Speed); Console.WriteLine(); Cheetah cheetah = new Cheetah(); Console.WriteLine(cheetah); Console.WriteLine("The {0} can go {1} km/h ", cheetah.GetName(), cheetah.Speed); Console.WriteLine(); Tomcat tomcat = new Tomcat(); Console.WriteLine(tomcat); Console.WriteLine("The {0} can go {1} km/h ", tomcat.GetName(), tomcat.Speed); tomcat.SayMyaau(); Console.WriteLine(); Kitten kitten = new Kitten(); Console.WriteLine(kitten); Console.WriteLine("The {0} can go {1} km/h ", kitten.GetName(), kitten.Speed); kitten.SayMyaau(); // This will not compile (Cat is abstract -> cannot be instantiated) //Cat cat = new Cat(); }
public void TestBackward() { Turtle t = new Turtle(); t.Backward(10f); Assert.AreEqual(-10f, t.X); Assert.AreEqual(0f, t.Y); }
private void Apply(Turtle t, float distance) { float xDiff = (float)Math.Cos(t.Radians) * distance; float yDiff = (float)Math.Sin(t.Radians) * distance; t.X += xDiff; t.Y += yDiff; }
public TurtleTranslate(Turtle t, float x, float y) { float offsetX = x - t.X; float offsetY = y - t.Y; this.x = offsetX; this.y = offsetY; }
public void TestForward() { Turtle t = new Turtle(); t.Forward(10f); Assert.AreEqual(10f, t.X); Assert.AreEqual(0f, t.Y); }
private void TurtleActions() { Turtle t = new Turtle(new SharpTurtle.Screen(turtleViewer1.Size.Width, turtleViewer1.Size.Height)); turtleViewer1.Screen = t.Screen; FractalGuide fg = new FractalGuide(ref t); fg.Guide(); }
static void Main() { Turtle turtle = new Turtle(); Console.WriteLine("The {0} can go {1} km/h ", turtle.GetName(), turtle.Speed); Cheetah cheetah = new Cheetah(); Console.WriteLine("The {0} can go {1} km/h ", cheetah.GetName(), cheetah.Speed); System.Collections.Generic.List<int> l; System.DateTime dt; }
public static void Main(string[] args) { // Create the turtle before using Turtle t = picoturtle.Turtle.CreateTurtle(args); if (t != null) { // Your code goes here t.penup(); t.pencolour(0, 255, 255); t.sety(0); t.setx(0); t.right(90); t.font("12pt Courier"); t.filltext("random turtle"); t.home(); t.pendown(); t.penwidth(4); var r = new Random(); for (int i = 0; i < 100; i++) { t.pencolour(r.Next(0, 255), r.Next(0, 255), r.Next(0, 255)); t.forward(r.Next(0, 20)); t.right(r.Next(-90, 90)); } // Your code ends here // Always stop the turtle t.stop(); } else { Console.Error.WriteLine("Error: Unable to create a turtle."); Environment.Exit(-1); } }
protected Turtle MoveTurtle(Turtle turtle, Vector3 dir, float dis) { Vector3 lineStart, lineEnd; lineStart = turtle.p; turtle.Go(dir, dis); lineEnd = turtle.p; // draw (GL) //if ((bool)myUI.parameters["showLineIsOn"][0]) //{ // GL.PushMatrix(); // lineMat.SetPass(0); // GL.LoadIdentity(); // //GL.MultMatrix(Camera.main.worldToCameraMatrix); // GL.Begin(GL.LINES); // GL.Color(Color.red); // GL.Vertex(Vector3.zero); // GL.Vertex(Vector3.one); // GL.End(); // GL.PopMatrix(); // //Debug.Log("start = " + lineStart.ToString("G4")); // //Debug.Log("end = " + lineEnd.ToString("G4")); //} // draw (line renderer) //LineRenderer newLine = new GameObject().AddComponent<LineRenderer>(); //newLine.material = lineMat; // draw line (Debug) //if ((bool)myUI.parameters["showLineIsOn"][0]) linePoints.Add(new List <Vector3>() { lineStart, lineEnd }); return(turtle); }
public void StartGame(MineField mineField, Turtle turtle, string[] commandArgs) { foreach (var commandArg in commandArgs) { _ = Enum.TryParse(commandArg, out Command command); switch (command) { case Command.M: turtle.Move(); break; case Command.L: turtle.Rotate(Command.L); break; case Command.R: turtle.Rotate(Command.R); break; case Command.I: throw new InvalidCommandException("GameService() Invalid command"); } var coordinate = new Coordinate(turtle.Point.X, turtle.Point.Y); Status = mineField.CheckCoordinatesStatus(coordinate); if (Status == Status.MineHit) { Console.WriteLine($"Turtle hits a Mine at {coordinate}."); return; } else if (Status == Status.Success) { Console.WriteLine($"The turtle reached Exit at {coordinate}."); return; } mineField.ValidateCoordinates(coordinate); } }
private void buttonHexagon_Click(object sender, EventArgs e) { Turtle.PenColor = Color.Teal; Turtle.Delay = 100; Turtle.Rotate(60); Turtle.Forward(100); Turtle.Rotate(60); Turtle.Forward(100); Turtle.Rotate(60); Turtle.Forward(100); Turtle.Rotate(60); Turtle.Forward(100); Turtle.Rotate(60); Turtle.Forward(100); Turtle.Rotate(60); Turtle.Forward(100); Turtle.Rotate(120); }
//animates the step by step drawing of the mesh public IEnumerator AnimateMesh(int objNum, View view) { var ruleSet = _rulesets[objNum]; LSystem ls = new LSystem(ruleSet._axiom, _iterationCount, ruleSet); string lSystemOutput = ls.Generate(); //use turtle to create mesh of L system Turtle turtle = new Turtle(ruleSet._angle); turtle.Decode(lSystemOutput); for (int i = 0; i < turtle._meshes.Count; i++) { turtle.PartialMesh(i); //view.InstructionsRewrite(turtle._partialInstructions); //writes the turtle instructions to screen (used in video) view.MeshRedraw(turtle._partialMesh); //redraws the partial mesh yield return(new WaitForSeconds(0.01f)); } }
public int Day2016_2(string input) { var t = new Turtle(trackvisit: true); t.Revisit += () => false; foreach (var step in input.Split(',').Select(s => s.Trim())) { switch (step[0]) { case 'R': t.Right(); break; case 'L': t.Left(); break; } if (!t.Move(int.Parse(step.Substring(1)))) { break; } } return(t.Manhattan((0, 0))); }
private void button_Click(object sender, RoutedEventArgs e) { Tess.SetAppearance(new LineGeometry(new Point(0, 0), new Point(20, 0)), Brushes.Pink, Brushes.Pink); Tess.Reset(); Tess.WarpTo(200, 200); for (int i = 0; i < 5; i++) // A five-sided regular polygon is called a pentagon. { bug = new Turtle(playground, Tess.Position.X, Tess.Position.Y); Tess.Forward(100); Tess.Left(360 / 5); } }
List <Vertex> SwordRing(Turtle turtle, float sectionWidth, float sectionThick, float edgeRatio) { List <Vertex> ring = new List <Vertex>(); Turtle branchTurtle = new Turtle(turtle); branchTurtle = MoveTurtle(branchTurtle, branchTurtle.r, sectionWidth); ring.Add(CreateVertex(branchTurtle.p)); branchTurtle = new Turtle(turtle); branchTurtle = MoveTurtle(branchTurtle, -branchTurtle.u, sectionThick); ring.Add(CreateVertex(branchTurtle.p)); branchTurtle = new Turtle(turtle); branchTurtle = MoveTurtle(branchTurtle, -branchTurtle.r, sectionWidth); ring.Add(CreateVertex(branchTurtle.p)); branchTurtle = new Turtle(turtle); branchTurtle = MoveTurtle(branchTurtle, branchTurtle.u, sectionThick); ring.Add(CreateVertex(branchTurtle.p)); return(ring); }
public void PushingAndPoppingStateRestoresState() { var t = new Turtle(new TestContext { IncreasingXMultiplier = 1, IncreasingYMultiplier = 1 }); t.Move(5).TurnRight(90).Move(6); Assert.Equal(5, t.CurrentX, 1); Assert.Equal(-6, t.CurrentY, 1); Assert.Equal(-90, t.Direction360, 1); t.PushState(); t.TurnRight(90).Move(10).TurnRight(90).Move(3); Assert.Equal(-5, t.CurrentX, 1); Assert.Equal(-3, t.CurrentY, 1); Assert.Equal(-270, t.Direction360, 1); t.PopState(); Assert.Equal(5, t.CurrentX, 1); Assert.Equal(-6, t.CurrentY, 1); Assert.Equal(-90, t.Direction360, 1); }
static void House(int len) { Turtle.Turn(90); Square(len); // Рисуем крышу Turtle.Turn(-60); Turtle.Move(len); Turtle.Turn(120); Turtle.Move(len); Turtle.Turn(30); // Рисуем окошко Turtle.PenUp(); Turtle.Move(2 * len / 3); Turtle.Turn(90); Turtle.Move(len / 3); Turtle.PenDown(); Square(len / 3); }
static void Main(string[] args) { Dog dog = new Dog("Bao"); Console.WriteLine(dog.ToString()); dog.CelebrateBirthday(); Console.WriteLine(dog.ToString()); Cat cat = new Cat("Miao", 23); Console.WriteLine(cat.ToString()); cat.CelebrateBirthday(); Console.WriteLine(cat.ToString()); Turtle turtle = new Turtle("Turlo", 2); Console.WriteLine(turtle.ToString()); turtle.CelebrateBirthday(); Console.WriteLine(turtle.ToString()); }
public static void Main(string[] args) { //Console.WriteLine("Hello World!"); var babyTurtle = new Turtle("Jim"); Turtle turtle = new Turtle("Mertle", 72); Console.WriteLine(turtle.Description); turtle.Eat(); turtle.Eat("Lettuce"); turtle.ShowTime("bar-mitzvah"); turtle.ShowTime("birthday"); babyTurtle.ShowTime("birthday"); Scorpion scorpion = new Scorpion("Steven"); scorpion.Attack(); //Console.WriteLine($"{turtle1.Name} is {turtle1.Age } years old. {turtle1.Size}"); Console.ReadLine(); }
private void Stvorec_Click(object sender, EventArgs e) { try { float strana = float.Parse(Input.Text); Turtle.ShowTurtle = false; Turtle.PenSize = 1; for (int i = 0; i < 4; i++) { Turtle.Forward(strana); Turtle.Rotate(90); } } catch { MessageBox.Show("Ďalej to už nepôjde, formát: strana(float)"); } }
static void printExample1() { int i = 0; while (i < 4) { for (int j = 0; j < 2; j++) { Turtle.Move(30); Turtle.TurnRight(); } for (int k = 0; k < 2; k++) { Turtle.Move(30); Turtle.TurnLeft(); } i++; } }
/// <summary> /// Before moving the <see cref="Turtle"/> it would be attractive to know if such a move is possible in the /// first place. This method checks if the current <see cref="Turtle"/> <see cref="Coordinates"/> and /// <see cref="Direction"/> allow the <see cref="Turtle"/> to move. /// </summary> /// <param name="turtle">The <see cref="Turtle"/> object to check if it can move on the board</param> /// <returns>true if <see cref="Turtle"/> can move and false if it cannot</returns> /// <exception cref="ArgumentOutOfRangeException">Default Exception if case does not match</exception> public static bool ValidateTurtleMove(Turtle turtle) { switch (turtle.Direction) { case Direction.N: return(turtle.Coordinates.CoordinateY != 0); case Direction.E: return(turtle.Coordinates.CoordinateX != BoardWidth); case Direction.S: return(turtle.Coordinates.CoordinateY != BoardLength); case Direction.W: return(turtle.Coordinates.CoordinateX != 0); default: throw new ArgumentOutOfRangeException(); } }
void koch(Turtle t, int order, double size) { // Make turtle t draw a Koch fractal of 'order' and 'size'. // Leave the turtle facing the same direction. if (order == 0) { // The base case is just a straight line t.Forward(size); } else { koch(t, order - 1, size / 3); // Go 1/3 of the way t.Left(60); koch(t, order - 1, size / 3); t.Right(120); koch(t, order - 1, size / 3); t.Left(60); koch(t, order - 1, size / 3); } }
private void button4_Click(object sender, EventArgs e) { // Assign a delay to visualize the drawing process Turtle.Delay = 200; // Change color Turtle.PenColor = Color.Green; // Draw a Star Turtle.Forward(200); Turtle.Rotate(144); Turtle.Forward(200); Turtle.Rotate(144); Turtle.Forward(200); Turtle.Rotate(144); Turtle.Forward(200); Turtle.Rotate(144); Turtle.Forward(200); Turtle.Rotate(144); }
void AddJoint(Turtle turtle, float min, float max, Vector3 axis, float frequency) { if (turtle.state.previousPivot == null) { return; } var jointAffector = turtle.state.pivot.gameObject.AddComponent<LSystemJoint>(); jointAffector.Frequency = frequency * 0.3f; jointAffector.Axis = axis; var joint = turtle.state.pivot.gameObject.AddComponent<HingeJoint>(); joint.connectedBody = turtle.state.previousPivot.GetComponent<Rigidbody>(); joint.autoConfigureConnectedAnchor = false; joint.connectedAnchor = turtle.state.previousPivot.InverseTransformPoint(turtle.state.head.position); joint.useLimits = true; joint.limits = new JointLimits {min = min, max = max}; joint.axis = axis; }
static void Main(string[] args) { GraphicsWindow.KeyDown += GraphicsWindow_KeyDown; Turtle.PenUp(); GraphicsWindow.BrushColor = "#3CF665"; var eat = Shapes.AddRectangle(20, 20); Random rand = new Random(); int eatX = rand.Next() % 600; int eatY = rand.Next() % 420; Shapes.Move(eat, eatX, eatY); for (;;) { if (Turtle.X >= eatX && Turtle.X <= eatX + 20 && Turtle.Y >= eatY && Turtle.Y <= eatY + 20) { Random rand1 = new Random(); eatX = rand1.Next() % 600; eatY = rand1.Next() % 420; Shapes.Move(eat, eatX, eatY); Turtle.Speed += 1; } Turtle.Move(10); if (Turtle.X < 0) { Turtle.X = 600; } if (Turtle.Y < 0) { Turtle.Y = 420; } if (Turtle.X > 600) { Turtle.X = 0; } if (Turtle.Y > 420) { Turtle.Y = 0; } } }
static void Main(string[] args) { Turtle.Speed = 9; int i = 0; while (i < 4) { Turtle.Move(100); //Turtle.TurnRight(); //Turtle.Turn( 90 ); Turtle.TurnLeft(); i++; } int n = 0; while (n < 4) { Turtle.Move(100); Turtle.TurnRight(); n++; } for (int l = 0; l < 4; l++) { Turtle.Move(25); Turtle.TurnRight(); Turtle.Move(25); Turtle.TurnRight(); Turtle.Move(25); Turtle.TurnLeft(); Turtle.Move(25); Turtle.TurnLeft(); } Turtle.X = 200; Turtle.Y = 200; int size = 60; WriteT(size); }
public bool TryMoveTurtle(Turtle turtle, int maxPositionX, int maxPositionY) { var currentPositionX = turtle.CurrentPositionX; var currentPositionY = turtle.CurrentPositionY; switch (turtle.CurrentDirection) { case DirectionType.N: currentPositionY--; break; case DirectionType.E: currentPositionX++; break; case DirectionType.S: currentPositionY++; break; case DirectionType.W: currentPositionX--; break; default: throw new NotImplementedException(); } if (currentPositionX > maxPositionX || currentPositionX < 0 || currentPositionY > maxPositionY || currentPositionY < 0) { // Turtle keeps hitting a wall untill it changes direction, // otherwise we can introduce a new exception for this case return(false); } else { _turtleFactory.UpdatePosition(turtle, currentPositionX, currentPositionY); return(true); } }
static void Main(string[] args) { var turtle = new Turtle("Bob", new Position(10, 12)); var nameAndX = NameAndX.Run(turtle); var newX = 0; if (nameAndX.Item1 == "Bob" && nameAndX.Item2 < 7) { newX = 99; } else { newX = 13; } var turtle2 = SetPosition(turtle, SetX(GetPosition(turtle), newX)); //Reader<Turtle, X> turtleX = Position.???(X) #region secret1 var turtleX = Position.AndThen(X); #endregion //Reader<Turtle, Tuple<string, int>> nameAndX2 = Name.???( // name => TurtleX.???(x => Tuple.Create(name, x))); #region secret2 Reader <Turtle, Tuple <string, int> > nameAndX2 = Name. SelectMany(name => turtleX.Select( x => Tuple.Create(name, x) ) ); #endregion #region secret3 var nameAndX3 = from name in Name from x in turtleX select Tuple.Create(name, x); #endregion }
public static void Forward(this Turtle turtle) { switch (turtle.Dir.ToLower()) { case "north": turtle.Y--; break; case "east": turtle.X++; break; case "south": turtle.Y++; break; case "west": turtle.X--; break; } }
public MainWindow() { // InitializeComponent() initialises GUI components - part of Window class InitializeComponent(); // A constructor is a special method which bears the same name as the class // When you call a constructor, it creates an instance of the class and returns it on the LHS // The constructor has a retyrn type that corresponds to the class // The Turtle() constructor is overloaded and has two versions // A Turtle is tied to a canvas, so the canvas name is an argument in the constructor // In the below, the Turtle is positioned at the coordinate (200, 200) tess = new Turtle(playground, 200, 200); // In the bottom version, specific coordinates are not given so the turtle defaults to position (20, 200) // tess = new Turtle(playground) // The turtle has properties - these can only be set once you've created an instance // A failure to create an instance, leads to a null exception (runtime error) tess.BrushWidth = 2.0; tess.BrushDown = false; }
public static void Rotate(this Turtle turtle) { switch (turtle.Dir.ToLower()) { case "north": turtle.Dir = "east"; break; case "east": turtle.Dir = "south"; break; case "south": turtle.Dir = "west"; break; case "west": turtle.Dir = "north"; break; } }
/// <summary> /// Gets a Board instance based on a loaded configuration json (dynamic) /// </summary> /// <param name="json">dynamic json with game configuration</param> /// <param name="board">Board to be loaded</param> /// <returns>Loaded Board</returns> private Board GetGameSettings(dynamic json) { Board currentBoard = new Board((int)json.BoardSizeX, (int)json.BoardSizeY, this); Turtle turtle = new Turtle((Direction)json.TurtleDirection, currentBoard); Exit exit = new Exit(); // Add Turtle currentBoard.AddGameObject((int)json.TurtlePosX, (int)json.TurtlePosY, turtle); // Add Exit currentBoard.AddGameObject((int)json.ExitPosX, (int)json.ExitPosY, exit); // Add Mines foreach (var item in json.Mines) { Mine mine = new Mine(); currentBoard.AddGameObject((int)item.MinePosX, (int)item.MinePosY, mine); } return(currentBoard); }
void AddNode(Turtle turtle) { var node = GetObjectAt(turtle, turtle.state.position); if (node) { turtle.state.head = node; return; } var go = GameObject.CreatePrimitive(PrimitiveType.Sphere); go.name = string.Format("Node [{0}]", turtle.state.name); go.GetComponent<MeshRenderer>().material = turtle.nodeMaterial; turtle.state.pivot.GetComponent<Rigidbody>().mass += 1; go.transform.SetParent(turtle.state.pivot); go.transform.position = turtle.state.position; turtle.state.head = go.transform; }
public void PerformanceTest1() { //paste TestData_Performance.txt contents to config.txt before running this test IGameConfiguration configuration = new GameConfiguration(); IBoard board = configuration.BoardConfiguration.GetBoard(); List <ICoordinate> mines = configuration.MinesConfiguration.GetMines(); ICoordinate exit = configuration.ExitConfiguration.GetExitPoint(); IPosition start = configuration.StartConfiguration.GetStartPoint(); List <List <MoveType> > moves = configuration.MoveConfiguration.GetMoves(); ITurtle turtle = new Turtle(start); IGameValidator gameValidator = new GameValidator(board, mines, exit, start, moves, turtle); IGame game = new Game(board, mines, exit, start, moves, turtle, gameValidator); GameResult gameResult = game.Run(); gameResult.ResultList.ForEach(result => { Assert.AreEqual(Status.StillInDanger, result); }); }
static void Main(string[] args) { Console.WriteLine("+-----Design Patterns com C# - Flyweight-----+"); Console.WriteLine(); FlyweightFactory factory = new FlyweightFactory(); string cor = string.Empty; Turtle turtle = null; while (true) { Console.WriteLine("---------------------------------------------------------------"); Console.Write("Which turtle COLOR do you want to show on the screen? "); string color = Console.ReadLine(); turtle = factory.GetTurtle(color); turtle.Show(color); Console.WriteLine(factory.FactorySituation()); } }
/// <summary> /// Moves turtle forward /// </summary> /// <param name="turtle"></param> public void Execute(Turtle turtle) { switch (turtle.Direction) { case TurtleDirection.North: turtle.Y -= 1; break; case TurtleDirection.East: turtle.X += 1; break; case TurtleDirection.South: turtle.Y += 1; break; case TurtleDirection.West: turtle.X -= 1; break; } }
private static void Program1() { Game.ShowSceneAndAddTurtle(); Turtle.MoveTo(0, 0); Turtle.SetPenWeight(1.5); Turtle.SetPenColor(RGBAColors.Cyan.WithAlpha(0x40)); Turtle.TurnOnPen(); var n = 5; while (n < 200) { Turtle.MoveInDirection(n); Turtle.RotateCounterClockwise(89.5); Turtle.ShiftPenColor(10); n++; Turtle.Sleep(50); } }
public static void Main(string[] args) { var turtle = new Turtle(); var commands = new List <ICommand> { new MoveCommand(20), new TurnLeftCommand(90), new MoveCommand(20), new TurnRightCommand(90), new SetColourCommand(ColourEnum.Red), new MoveCommand(20), new TurnRightCommand(90), new PenCommand(PenStateEnum.Up), new MoveCommand(40) }; foreach (var command in commands) { command.ExecuteCommand(turtle); } }
public void TestTurnMove() { Turtle t = new Turtle(); t.Left(45); t.Forward(10); Assert.AreEqual(7.07, t.X, 0.002); Assert.AreEqual(7.07, t.Y, 0.002); t.Undo(); t.Left(45); t.Forward(10); Assert.AreEqual(0, t.X, 0.002); Assert.AreEqual(10, t.Y); t.Undo(); t.Left(45); t.Forward(10); Assert.AreEqual(-7.07, t.X, 0.002); Assert.AreEqual(7.07, t.Y, 0.002); }
void Yaw(Turtle turtle, float value) { turtle.state.direction *= Quaternion.Euler(RotationY * value); }
void Roll(Turtle turtle, float value) { turtle.state.direction *= Quaternion.Euler(RotationZ * value); }
public static void Interpret( int segmentAxisSamples, int segmentRadialSamples, float segmentWidth, float segmentHeight, float leafSize, int leafAxialDensity, int leafRadialDensity, bool useFoliage, bool narrowBranches, Material leafMaterial, Material trunkMaterial, float angle, string moduleString, out GameObject leaves, out GameObject trunk) { leaves = new GameObject("Leaves"); trunk = new GameObject("Trunk"); GameObject leafBillboard = CreateLeafBillboard(leafSize, leafMaterial); int chunkCount = 0; Mesh currentMesh = new Mesh(); Dictionary<int, Mesh> segmentsCache = new Dictionary<int, Mesh>(); Turtle current = new Turtle(Quaternion.identity, Vector3.zero, new Vector3(0, segmentHeight, 0)); Stack<Turtle> stack = new Stack<Turtle>(); for (int i = 0; i < moduleString.Length; i++) { string module = moduleString[i] + ""; if (module == "F") { CreateSegment( segmentAxisSamples, segmentRadialSamples, segmentWidth, segmentHeight, narrowBranches, trunkMaterial, current, stack.Count, ref currentMesh, ref chunkCount, trunk, segmentsCache); current.Forward(); } else if (module == "+") { current.RotateZ(angle); } else if (module == "-") { current.RotateZ(-angle); } else if (module == "&") { current.RotateX(angle); } else if (module == "^") { current.RotateX(-angle); } else if (module == "\\") { current.RotateY(angle); } else if (module == "/") { current.RotateY(-angle); } else if (module == "|") { current.RotateZ(180); } else if (module == "[") { stack.Push(current); current = new Turtle(current); } else if (module == "]") { if (useFoliage) AddFoliageAt( segmentWidth, segmentHeight, leafAxialDensity, leafRadialDensity, current, leafBillboard, leaves); current = stack.Pop(); } } CreateNewChunk(currentMesh, ref chunkCount, trunkMaterial, trunk); GameObject.Destroy(leafBillboard); }
public Turtle(Turtle other) { this.direction = other.direction; this.position = other.position; this.step = other.step; }
static void CreateSegment( int segmentAxisSamples, int segmentRadialSamples, float segmentWidth, float segmentHeight, bool narrowBranches, Material trunkMaterial, Turtle turtle, int nestingLevel, ref Mesh currentMesh, ref int chunkCount, GameObject trunk, Dictionary<int, Mesh> segmentsCache) { Vector3[] newVertices; Vector3[] newNormals; Vector2[] newUVs; int[] newIndices; Mesh segment; if (segmentsCache.ContainsKey(nestingLevel)) segment = segmentsCache[nestingLevel]; else { float thickness = (narrowBranches) ? segmentWidth * (0.5f / (nestingLevel + 1)) : segmentWidth * 0.5f; segment = ProceduralMeshes.CreateCylinder(segmentAxisSamples, segmentRadialSamples, thickness, segmentHeight); segmentsCache[nestingLevel] = segment; } newVertices = segment.vertices; newNormals = segment.normals; newUVs = segment.uv; newIndices = segment.triangles; if (currentMesh.vertices.Length + newVertices.Length > 65000) { CreateNewChunk(currentMesh, ref chunkCount, trunkMaterial, trunk); currentMesh = new Mesh(); } int numVertices = currentMesh.vertices.Length + newVertices.Length; int numTriangles = currentMesh.triangles.Length + newIndices.Length; Vector3[] vertices = new Vector3[numVertices]; Vector3[] normals = new Vector3[numVertices]; int[] indices = new int[numTriangles]; Vector2[] uvs = new Vector2[numVertices]; Array.Copy(currentMesh.vertices, 0, vertices, 0, currentMesh.vertices.Length); Array.Copy(currentMesh.normals, 0, normals, 0, currentMesh.normals.Length); Array.Copy(currentMesh.triangles, 0, indices, 0, currentMesh.triangles.Length); Array.Copy(currentMesh.uv, 0, uvs, 0, currentMesh.uv.Length); int offset = currentMesh.vertices.Length; for (int i = 0; i < newVertices.Length; i++) vertices[offset + i] = turtle.position + (turtle.direction * newVertices[i]); int trianglesOffset = currentMesh.vertices.Length; offset = currentMesh.triangles.Length; for (int i = 0; i < newIndices.Length; i++) indices[offset + i] = (trianglesOffset + newIndices[i]); Array.Copy(newNormals, 0, normals, currentMesh.normals.Length, newNormals.Length); Array.Copy(newUVs, 0, uvs, currentMesh.uv.Length, newUVs.Length); currentMesh.vertices = vertices; currentMesh.normals = normals; currentMesh.triangles = indices; currentMesh.uv = uvs; currentMesh.Optimize(); }
public override void Do(Turtle t) { this.Apply(t, this.distance); }
public abstract void Undo(Turtle t);
void AddPivot(Turtle turtle) { var go = new GameObject(string.Format("Pivot [{0}]", turtle.state.name)); //go.transform.SetParent(turtle.state.pivot ?? creature); go.transform.SetParent(creature); go.transform.position = turtle.state.position; go.transform.localRotation = turtle.state.direction; var rb = go.AddComponent<Rigidbody>(); turtle.state.previousPivot = turtle.state.pivot; turtle.state.previousPivotDirection = turtle.state.direction; turtle.state.pivot = go.transform; }
public void GenerateRooms(Project project, Scene scene) { var turtle = new Turtle { position = IntVector2.zero, direction = Random.Range(0, 4) }; var floor = project.tiles[0]; var wall = project.tiles[1]; for (int i = 0; i < Random.Range(7, 11); ++i) { for (int j = 0; j < Random.Range(4, 9); ++j) { turtle.position += new IntVector2(Mathf.RoundToInt(Mathf.Cos(Mathf.PI * 0.5f * turtle.direction)), Mathf.RoundToInt(Mathf.Sin(Mathf.PI * 0.5f * turtle.direction))); scene.tilemap.SetTileAtPosition(turtle.position, floor); } turtle.direction = (turtle.direction + Random.Range(1, 4)) % 4; int w = Random.Range(1, 3); int h = Random.Range(1, 3); for (int y = -h; y <= h; ++y) { for (int x = -w; x <= w; ++x) { scene.tilemap.SetTileAtPosition(turtle.position + new IntVector2(x, y), floor); } } } int xmin = scene.tilemap.tiles.Keys.Min(cell => cell.x) - 1; int ymin = scene.tilemap.tiles.Keys.Min(cell => cell.y) - 1; int xmax = scene.tilemap.tiles.Keys.Max(cell => cell.x) + 1; int ymax = scene.tilemap.tiles.Keys.Max(cell => cell.y) + 1; Debug.LogFormat("{0}, {1}, {2}, {3}", xmin, ymin, xmax, ymax); for (int y = ymin; y <= ymax; ++y) { for (int x = xmin; x <= xmax; ++x) { var coord = new IntVector2(x, y); if (scene.tilemap.GetTileAtPosition(coord * 32) != null) { continue; } bool neighbour = false; for (int i = 0; i < 8; ++i) { var final = coord + IntVector2.adjacent8[i]; var inst = scene.tilemap.GetTileAtPosition(final * 32); if (inst != null && inst.tile != wall) { neighbour = true; break; } } if (neighbour) { scene.tilemap.SetTileAtPosition(coord, wall); } } } }
public abstract void Do(Turtle t);
void Twist2(Turtle turtle, float value) { AddJoint(turtle, -90, 90, Vector3.up, value); }
public override void Do(Turtle t) { t.X += x; t.Y += y; }
public override void Undo(Turtle t) { t.X -= x; t.Y -= y; }
public override void Undo(Turtle t) { this.Apply(t, -this.distance); }
static void AddFoliageAt( float segmentWidth, float segmentHeight, int leafAxialDensity, int leafRadialDensity, Turtle turtle, GameObject leafBillboard, GameObject leaves) { float xAngleStep = -70 / (float)leafAxialDensity, xAngle = xAngleStep * (leafAxialDensity - 1) - 20, yAngle = 0, yAngleStep = 360 / (float)leafRadialDensity, y = 0, yStep = -segmentHeight / (float)leafAxialDensity; for (int i = 0; i < leafAxialDensity; i++, xAngle -= xAngleStep, y -= yStep) { for (int j = 0; j < leafRadialDensity; j++, yAngle += yAngleStep) { GameObject leaf = (GameObject)GameObject.Instantiate(leafBillboard, Vector3.zero, turtle.direction); leaf.transform.parent = leaves.transform; leaf.transform.position = turtle.position - (turtle.direction * new Vector3(0, y, 0)); leaf.transform.Rotate(new Vector3(xAngle, yAngle, 0)); } } }
private Tile LoadTurtleTile(int x, int y) { GameObjectList enemies = this.Find("enemies") as GameObjectList; TileField tiles = this.Find("tiles") as TileField; Turtle enemy = new Turtle(); enemy.Position = new Vector2(((float)x + 0.5f) * tiles.CellWidth, (y + 1) * tiles.CellHeight + 25.0f); enemies.Add(enemy); return new Tile(); }
public FractalGuide(ref Turtle t) { this.t = t; }