We can use the
color function to save colors as variables. It takes the same input parameters as
Here are some examples:
var crimson = color(200, 0, 0) // this will be a dark red fill(crimson) ellipse(250, 250, 100, 100) // this will put a dark red circle in the middle of the canvas var cyan = color(0, 255, 255) //bright aqua blue background(cyan) //will make this bright aqua the background color var purple = color(175, 0, 175) // make a purply magenta color stroke(purple) line(0, 0, 500, 500) // will make a purple diagonal line across the canvas
Programs are very good at picking random numbers for us. We can use random numbers to make unexpected and changing aspects to our games.
In the pJS library that we use, you can do this with the
Here are some examples:
var myNumber = random(1, 10) // will pick a random decimal number between 1 and 10 var mySmallNumber = random() // this picks a decimal between 0 and 1 var myLargeNumber = random(100, 1000) // picks a decimal number between 100 and 1000
As we have seen before, the random function always gives us a number with decimals. In programming, we often call this a float number, short for "floating point decimal".
This is fine for color values, but often times it doesn't make sense to have a decimal, and you need only whole numbers instead, called integers.
For example. it wouldn't make sense to have 0.58 people, would it?
To turn a float into an integer, we need to round it, which just means to find the whole number that it is closest to. In pJS, we can use the handy
Change the test code in your
draw function to round the randomly generated number, and check out the number it gives you in the console.
Your apple will now be in a random scene. You will need to run around the different scene to find which one it was placed in. It will be different each time you run your code.
Declare a variable called
applesCollected and assign it to
0 in the setup function.
Then, declare a variable called
applesTotal and assign it to
1 in the setup function.
Give the apple a new property called
collected which starts out as
Find your apple and press "Enter" while overlapping it to collect it again. This time it should disappear!
Now that your apple starts in a random scene, we need to make it show up in a random place in that scene.
apple object's X property from 300 to a random number between 0 and 500, using the