Script Recycling!
Goals:
- Store reusable parts of your programs in separate files that you can easily import and run in any program whenever you need it
Coding Snippets:
CoffeeScript.load
reads, compiles, and executes CoffeeScript code stored in a separate file named with a.coffee
extension.CoffeeScript.load
executes the code in a nested scope. To make values from that nested scope available in the current scope, assign them to properties of thewindow
object, as illustrated here with the customprint
function.
Math and Computer Concepts:
- Code reuse is central to efficient coding. Recall that functions facilitate code reuse by allowing us to reuse a block of code through a simple function call. Such code reuse reduces the potential for bugs and simplifies code maintenance. This lesson shows how to take this code-recycling to the next level, by making useful functions (and/or other code) readily available to any program we write.
- A file of pre-written code such as
CrazyLetters.coffee
is called a module. By defining modules based on specific tasks, use of modules can help us keep our code organized as well.
Activities:
Save each of the following in a folder called ScriptRecycling.
- Pencil Code creator David Bau wrote a module that contains code which modifies the behavior of the
rt
andlt
functions, so that the default turtle annotates each turn that it makes. A copy of this code is located at Load the script and instruct your default sprite to create an AnnotatedShape, such as a polygon or a star. - CrazyLetters: The coding snippet in this lesson illustrates solving the CrazyLetters activity using a modular approach. Copy the snippet (creating two files) and make sure it works. Then add a second function to the module,
jiggle
, which makes all the crazy letters move randomly around their initial positions. Hint: use the jQuery class selector for theturtlelabel
class to identify the labels, and usespeed Infinity
to avoid animation queue problems. - Write a program that shares several of your finest drawing programs as an ArtShow. Load and execute the scripts, one after the other, in the same window. Begin by creating an array that contains the URLs of the files . Recall, however, that to execute scripts using
CoffeeScript.load
, the file name needs to end with.coffee
. Accomplish this programmatically, using theload
function to read the source code andsave
to immediately save it as a temporary file with the required filename extension. Then pass that file toCoffeeScript.load
.