Building Your Own Turtle Functions For making really cool pictures! 1 5 Cool Things… 1. 2. 3. 4. 5. Variables and Arithmetic Branches for variety Using Functions Building your own Functions (Today) Loops to repeat (Next week) 2 Review: 1) Variables and Arithmetic var n = 4; var y = 2; var x = n + y; y = n * 2; document.write(“x=” + x + “, y=” + y); 3 2) Using Functions Identify the Function calls and the arguments Math Functions: x = Math.sqrt(81); y = Math.sqrt(x); document.write(“x=” + x + “, y=” + y); Turtle Functions: forward(20); left(90); forward(20); right(135); backward(40); 4 Which command(s) uses “relative” positioning, and which “absolute” forward -- move turtle forward some number of pixels left – turn left some number of degrees moveTo -- move to an x,y coordinate turnTo – turn to a particular degree heading home – send turtle back to center of screen, facing up 5 Today—3) Building your own functions Lets you “abstract” a collection of moves For example, these lines make a square: forward(20); forward(20); forward(20); forward(20); right(90); right(90); right(90); right(90); 6 If you want to draw a lot of squares, put this at the top of your script… function square( ) { forward(40); right(90); forward(40); right(90); forward(40); right(90); forward(40); right(90); } This is a Function Definition 7 Now you can ‘call’ your square function square(); -------------------left(30); square(); left(180); square(); moveTo(-300, -100); left(30); square(); left(180); square(); 8 Functions help manage complexity You can do interesting patterns without a lot of repetition of code They save time and effort Functions can use other functions 9 What if you want different sizes of squares? n is called a parameter function square( n ) { forward(n); right(90); forward(n); right(90); forward(n); right(90); forward(n); right(90); } It’s a variable that receives the size of the square (given as the argument in the function call) 10 Now when you call the square function, just say how big you want it to be square(100); square(50); square(25); 11 You can generate random sized squares… var size, angle; size=rand(50,100); square(size); angle=rand(0,180); turnTo(angle); size=rand(50,100); square(size); rand(low, high) gives random number between low and high 12 Every time you run the code from last slide, it gives a different result It’s interesting to observe the variations and similarities 13 Capture your images in a “screen shot” Press Alt and PrtScr at same time Open Paint Edit/Paste You can chop out image using select tool Dotted line box Then paste into Microsoft Word Or save as a .jpg file (project 2) 14 That’s it! Have fun in lab Next week…branches and loops 15