Yeah, I know, it took a while… But then again, what did I get? Two tweets from good friends! Thanks guys, actually, thanks girls!
So that was me complaining and making excuses, on to code - click here and try this code:
Wow, that’s magic! Our lives just got simpler if we can live with a bit of monotomy. You might recognize the first part from lesson 2, but if you look carefully you will spot the magic:
Lets play a little! Go ahead and replace
counter < 10 with another number like
5. Try changing
var counter = 0 to
var counter = 4. And what about changing
counter = counter+2 or
counter += 2. Try adjusting the other variables like we did last time and see what the effects are.
for thingy is called a loop and it allows you to do something multiple times - like drawing lots of buildings!
The first part,
var counter = 1, is where we define the variable that we are going to use to keep count of where we are.
The second part,
counter < 10, is the condition that we use to specify when to stop the loop.
counter < 10 will stop the loop when
counter is bigger than or equal to 10.
The third part,
counter++, is where you define how
counter should be modified every time the loop executes.
counter++ is shorthand for writing
counter = counter + 1.
The last part is between the
} and this is the part you want to repeat multiple times - in this instance drawing a building!
Ok, ok, “but it is boring!!” you say. I agree, but lets mix in a little more magic -
Math.random(). This will give you a random value between 0 and 1! Change the body of your loop as follows:
Tweak and enjoy your infinite number of unique cities! The skyline at the top of this page is generated using similar code, refresh the page to see a new city at the top! Go forth and share your creations on twitter with the tag #learn2code.
Until next time!!