Grasshopper Custom Functions

Grasshopper uses a few custom functions to make using code for the first time easier. The information below will likely be a bit confusing, or overwhelming, if you are just starting your coding journey. Don’t worry if you don’t understand everything (or anything), this is just to provide some additional information.

print()
Definition: This function takes the argument, the part inside the parentheses, and prints it out, then moves the cursor (the Grasshopper) to a new line. It accepts strings, numbers, or variables that are holding strings or numbers.

Example:
Code: print('Hello world')
Output: Hello world

How to replicate outside Grasshopper: console.log() is a JavaScript feature that creates similar behavior to the print() function. You’ll need to open up your web browser’s console in order to see the output of console.log().

pickRandom()
Definition: This function takes arrays or numbers, or variables holding numbers or arrays, and selects a random element. pickRandom() doesn’t do very much on its own, but can be useful when combined with other functions.

Example:
Code: pickRandom(5)
Output: (selects a random number between 1 and 5)

Code: pickRandom(['hopper', 'hipper'])
Output: (randomly selects ‘hopper’ or ‘hipper’)

How to replicate outside Grasshopper: A function definition for pickRandom() could look something like the below. Don’t worry if you don’t understand all the code below, we don’t teach a lot of it yet.

function pickRandom(argument) {
  if (typeof argument === 'number') {
    return Math.floor(Math.random() * Math.floor(argument)) + 1;
  }
  if (Array.isArray(argument)) {
    return argument[Math.floor(Math.random() * argument.length)];
  }
}

drawBox()
Definition: This function takes colors and turns them into boxes (SVG rectangles). It can take strings that are colors, or variables holding strings that are colors.

Example:
Code: drawBox('red')
Output: a red box

How to replicate outside Grasshopper: This function requires an SVG environment in order to create shapes. We’ve created an example environment in the Animations Playground. You can learn how to re-create this function by looking at the drawSquare and Rainbow Hopper puzzles.

drawBoxes()
Definition: This function is very similar to drawBox(), but rather than colors it takes any string and turns each letter into a colored box. It can take strings, or variables holding strings.

Example:
Code: drawBoxes('red')
Output: a red box, then an ebony box, then a dandelion-colored box.

How to replicate outside Grasshopper: This function also requires an SVG environment. We’ve created an example environment in the Animations Playground. It’s easiest to reference the drawBox() function inside of the drawBoxes() definition. The code might look something like:

function drawBoxes(aString) {
  let colorObject = {a : 'amber', b : 'blue', c : 'cyan', ...}
  for (let element of aString) {
    drawBox(colorObject[element]);
  }
}

newLine()
Definition: Moves the Grasshopper cursor to a new line. It doesn’t take any argument.

How to replicate outside Grasshopper: This function is pretty specialized to Grasshopper. The idea of a ‘cursor’ in the output is something we added to help illustrate how code runs. To replicate this you’d need an SVG environment (like the Animations Playground), a cursor to move, and a position to move the cursor to that keeps track of its current ‘line’.

35 Likes
Practise What You Learn
Will I also learn actual js coding from grasshopper?
Grasshopper's playground functions
Question on code functions in JavaScript
The ready functiond
Lock Box explainer
Decodificador de imagen explainer
Hombre invisible explainer
Greater or Lesser es-419 Explainer
Más operadores numéricos explainer
Oportunidad de operador explainer
Caja fuerte explainer
Mayor o menor explainer
Arcoíris más largo explainer
Describe los números explainer
Arcoíris más corto explainer
Arcoíris aún más corto explainer
Recuento con ciclos
Cruzado con capa explainer
Feliz Año Nuevo explainer
Recuento doble explainer
Monedas de 5 y 10 centavos explainer
Generador de nombres de bandas explainer
Gabonese Flag explainer
Portada de color explainer
Más nombres de bandas explainer
Gabonese Flag explainer
En solitario explainer
Open The Lock pt-br Explainer
Colores personalizados explainer
No exactamente blanco explainer
Azul 222 explainer
¿Qué grado de azul puedes lograr? explainer
Sé verde explainer
Prepara tu bolso explainer
Invéntate un nombre explainer
Defina su meta explainer
Obtenga más provisiones explainer
Actualiza tu avance explainer
Mochila equivocada explainer
El ascenso final explainer
Take a Trip explainer
Let's Take a Trip explainer
Console Logging explainer
Console Log Party explainer
One Step at a Time explainer
Console Loggin explainer
Feet Don't Fail Me Now explainer
How Many explainer
Indonesian Flag Fixer es-419 Explainer
Danish Flag Fixer es-419 Explainer
Color Keeper es-419 Explainer
Take a Trip es-419 Explainer
Heads or Tails es-419 Explainer
Simpler Math es-419 Explainer
Apples and Oranges es-419 Explainer
Gabonese Flag Shortcuts explainer
Incremented Decremented es-419 Explainer
Winter Is Coming es-419 Explainer
Room for Growth es-419 Explainer
Console Log Party es-419 Explainer
Consolation Puzzle es-419 Explainer
Console Logging es-419 Explainer
Complete The Picture es-419 Explainer
In The Middle es-419 Explainer
Comfort Food es-419 Explainer
Bolt Out Of The Blue es-419 Explainer
One Step at a Time es-419 Explainer
Tablero de ajedrez Explainer
Accesos directos a la bandera gabonesa explainer
Accesos directos a bandera armenia explainer
Accesos directos a la bandera estonia explainer
Checkerboard Helper explainer
Checkerboard explainer
Gabonese Flag-pt-br-explainer
Gabonese Flag pt-br Explainer
Pack Your Bag pt-br Explainer
Magic Answers Explainer
Complete The Picture pt-br Explainer
In The Middle pt-br Explainer
Comfort Food pt-br Explainer
Bolt Out Of The Blue pt-br Explainer
Magic Answers es-419 Explainer
Post Climb Postcard pt-br Explainer
Animal Groups pt-br Explainer
Animal Noises pt-br Explainer
Chat Bot pt-br Explainer
One Day Away pt-br Explainer
Indonesian Flag Fixer pt-br Explainer
Danish Flag Fixer pt-br Explainer
Color Keeper pt-br Explainer
More Or Less pt-br Explainer
Roads Or Rails pt-br Explainer
Heads Or Tails pt-br Explainer
A Thing Or Two pt-br Explainer
Simpler Math pt-br Explainer
Apples And Oranges pt-br Explainer
Incremented Decremented pt-br Explainer
Winter Is Coming pt-br Explainer
Room For Growth pt-br Explainer
Consolation Puzzle pt-br Explainer
Roads or Rails es 419 explainer
One Day Away es-419
Color Keeper explainer
More Or Less es-419 Explainer
Simply Math es-419 Explainer
Console Loggin es-419 Explainer
How Many es-419 Explainer
More Or Less es-419 Explainer
Get More Supplies pt-br Explainer
How Many Explainer
Roads Or Rails es-419 Explainer
Gabonese Flag explainer
French Flag explainer
List of names and meanings
Crossword Helper explainer
Poland to San Marino explainer
Simply More Math explainer
Lanza una moneda explainer
Lanza una moneda nuevamente explainer
Uno u otro explainer
Juego de adivinanzas explainer
Tripleta explainer
Paleta de colores explainer
Ramificación binaria explainer
Matemáticas modificadoras explainer
Suma y resta explainer
Simplemente más matemáticas explainer
Abre el candado explainer
Día lluvioso explainer

To avoid potential confusion later on, can I suggest replacing print(), etc., with gh.print(), etc.? That will make it clear that these are not JavaScript built-in functions.

–Scott.

5 Likes

Hey @Scott_McNay,

Thanks for the suggestion! We agree we need to make it a bit clearer that these are custom Grasshopper functions within the app (we’re working on that). Part of the aim is to make it very simple for new coders to start seeing their outputs as quickly as possible, hence the very intuitively named functions.

H :slight_smile:

14 Likes

BTW, I’m not convinced that pickRandom(2) works as expected; see below for what appears to be typical results:

4 Likes

Hey @Scott_McNay,

Is the issue the dominance of 1’s selected? That’s expected for the small sample size, I’ve gotten a bunch of 2’s with the same code:

Or is the issue missing 0’s? pickRandom() starts at 1, rather than 0, so it’s expected for there not to be any 0’s.

H :slight_smile:

3 Likes

Hi @Grasshopper_Heather,

Maybe the issue is runs – seems like unusually long runs of the same digits. It just doesn’t ‘feel’ random. Or maybe I’m just deceived by only two values.

It turns out to be REALLY hard to make a random number generator which generates numbers that really are random, much less pass all of the formal tests of randomness. This is how hard: https://www.google.com/amp/s/www.sciencealert.com/gamers-massive-experiment-shows-einstein-got-reality-wrong/amp

3 Likes

I don’t understand how pickRandom() is generating numbers in In the Middle; they are all separated by what appears to be 30 units. When I use position directly to place circles, it acts like the value is 0, but pickRandom(0) always gives a result of 1.

–Scott.

2 Likes

To make a number that the output is 0 or 1, you need to make variables like me (x and Random),
use for loops to set random and use random - 1 to print what you want. Use pickRandom(any number) to set Random to any number from 0 to that number - 1.
If you don’t understand, I have a picture for you:


-Yusril

2 Likes

So, i were practicing JS (outside Grasshopper’s playground since, y’know) and i noticed many functions i got used to weren’t natural from JS, so, where could i find code examples for such functions like pickrandom and drawbox(es)?

2 Likes

I’ve moved your post to this thread. Check out Heather’s post at the very top.

There’s some code you can use to make your own pickRandom() function. As for drawBox, there are some lessons in the Animations course that get you most of the way there: drawSquare and Rainbow Hopper.

–Frankie

3 Likes

Shouldn’t you add definition of math,Array(that can be added with .isArray()), and etc to the app Grasshopper?

2 Likes

hey guys,
well I tried to use for example the drawBox in Explorer, but I didnt identify it as a Command, so its a ready Funktion , then what benefit should I get when functions used here arent identified in the real language ?

4 Likes

I’ve moved your post to this thread. Check out Heather’s post at the very top. There, she lists a number of custom functions that we use in Grasshopper, including drawBox().

The custom functions we use are tools for teaching concepts. For example, drawBox() is used to illustrate how a function is called with an argument, and how the function will do different things depending on which argument is passed into it. For example, drawBox(red) will draw a red box, and drawBox(blue) will draw a blue box.

In Fundamentals I, when beginning your journey in programming, learning these concepts is more important than learning JavaScript’s built-in functions. In Fundamentals II and later courses, you will learn more about these.

I’m really happy to hear that you’re experimenting and using JavaScript outside of the lessons! If you’d like a place to freely explore Grasshopper’s custom functions, I recommend checking out our Code Playground, which you can access from the main menu button at the top-left of the screen.

Good luck on your journey!
Ben

4 Likes

i am struck at last 4 percent

1 Like

I am on the app doing call back functions and stuck on something called just in timechanges names now my assistant has various names and i just cant get the function part to work. is there something similar on the non app that can help me?

2 Likes

The pickRandom() function works pretty honestly.
I ran this code a dozen of times and results was always nearly 50/50

4 Likes

What do you use in place of the drawbox( ) function in the code playground

3 Likes

Hey there, Heather. To avoid potential confusion, can I suggest replace print(), etc. with gh.print(), etc.?

P :grinning:

1 Like

I really love the Grasshopper app. Its amazing!

2 Likes

Hey there, thanks for good comment!! I glad you liked Grasshopper App. :blush:

P :grinning: