# Creators – Random Dungeon

This week we took a look at a technique for generating random dungeons. Although never mentioned on the day, this technique is often called “marching squares”. It looks at the four corners of a space at a time, some of which are open and some of which are closed, and picks a shape that blocks off the closed corners.

There are sixteen possible combinations of corners on and off. All of these can be covered with these five shapes (or a rotation of them) to represent the closed off areas:

Generating the Dungeon

We generated a 2D array (a list of lists) to store our dungeon layout. At each point we used a 2D Perlin noise value (using the noise() function) to calculate a value. The point was deemed to be either open or closed based on whether this value was higher or lower than a threshold value we specified. Varying this threshold value can make the dungeon more open, or more closed in.

Drawing the Dungeon

To draw these shapes we first defined each of them as a list of x, y points defining the shape.

We then used beginShape()vertex(), and endShape() functions to draw them at the correct size, location and orientation by scale(), transform() and rotate().

Once we were able to draw the shapes, we just needed to loop over our grid, inspecting each set of four adjacent corners in turn and drawing the appropriate shape.

Here’s a screenshot of one random dungeon. Dots (green for open, red for closed) are drawn to show the grid and the lines between the individual shapes are also shown for clarity:

and here is is without these overlays:

The files for this week can be found on our GitHub repository.

# Creators – Quiz and Hacking

This week we had a quiz. There were three rounds on Technology, Creators 2019 and Pop Culture. There was a very high proportion of correct answers on all questions. The quizes can be found here, for anyone that wants them:

Creators 2019

Pop Culture

Technology

After that we set everyone a programming challenge: make an animated scene. People got busy and there was some good progress. We will continue with that next week. Mark and I (Kieran) got in on the action figuring out how to draw clouds. My attempt is shown in the image at the top of this post. The code can be found, as always, on the CoderDojo Athenry Creators 2018 GitHub.

# Creators – Flying Over Dynamic Terrain

This week we creating a game where a tiny plane flies over dynamically generated terrain picking up as many boxes as possible. The player scores a point for every box, but that also makes the plane fly faster, making the game more challenging.

Perlin Noise

Normal random-number generators produce values that jump around all over the place. Perlin noise is different. It is also random, but it varies smoothly. This makes it great for mimicking the sort of randomness we see in nature.

1D Perlin Noise Landscape

Our smooth and changing landscape is generated using a one-dimensional Perlin noise value generated by the P5.js function noise(xoff).

We start with a loop that goes across from 0 -> width across the screen. We’re looking to generate a set of [xy] points that define our shape.

We use these values:

1. xstart: A starting value for xoff
2. xinc: An amount to increment xoff by for every new location
3. ymin: The smallest y value we want for our landscape – something a little below the top of the screen
4. ymax: The largest y value we want for our landscape – something a little above the bottom of the screen

Each call to noise() generates a single value in the range 0-1. We use the P5.js function map() to change this value in the range 0-1 into a value in the range ymin-ymax.

Changing the size of xinc controls how choppy or smooth the landscape is. We tune it to a value that gives approximately two peaks and two valleys across the screen, and looks right for our game.

Moving the Landscape

Moving the landscape is achieved by changing the starting value of xoff (aka. xstart) each time we update the screen. By making it a little larger each time, the effect is that the landscape seems to scroll from right to left.

Other Parts of the Game

The other parts of the game are very standard. We define a simple plane shape (drawn using rect() calls)  that can move up or down in response to the arrow keys.

We define “cargo” containers that are randomly generated on the surface of the landscape and move right-to-left at the same speed.

The cargo containers have an active property that is false if they move beyond the left-edge of the screen or get sufficiently close to the plane to be “picked up”.

We added a function to the landscape class (Ground.js) that checks for a given [x, y] location to see if that point us under the ground by checking what the height of the landscape is at that x value. If the plane is below the ground we consider it crashed.

We added a simple scoring mechanism that tracks how many boxes were collected and makes the plane move faster (really – the ground scroll faster) every time a box is collected.

The files for this week can be found on our GitHub repository.

# Creators: Shootah Part 6 – Enemy Shooting Back

This week we did our last iteration on Shootah and added a Bomb to be dropped by the enemy to try to hit the player.

Bomb Class

We copied the existing Bullet class and called it Bomb instead. The main changes we had to make were:

1. Changing the speed to a negative number so that it moved down instead of moving up (as the Bullet does)
2. Changed the check for the top of the screen to one for the bottom of the screen instead (to account for the fact it moves down)
3. Changed the check in its hit() function so that the Bomb doesn’t interact with the Enemy when it’s dropped, but will be marked as inactive it if hits anything else.
4. Changed the colour of the bomb to red

Manages Bombs

It happened that the code we had already written to manage bullets was already perfect for managing bombs as well.

We used Visual Studio Code’s built-in capability to automatically rename symbols to:

1. Rename the bullets array to projectiles
2. Rename the manageBullets() function to manageProjectiles()

This was enough to have bombs move, draw and be removed when it becomes inactive.

Dropping Bombs

We added a new function to Ememy called shoot(). In that function we generated a random number from one to two hundred. We then dropped a bomb every time that number was less than five (we tuned this small number to get a good rate of bomb drops). This meant that the enemy dropped a bomb at random intervals, to make it impossible for the player to anticipate.

The files for this week can be found on our GitHub repository.

# Creators – Pattern

This week we looked at two important concepts, loops and lists.

Loops

Start by imagining we wanted to draw four circles next to each other. We could write four calls the ellipse function, like this:

```let size = 50;

ellipse(25, 25, size, size);
ellipse(75, 25, size, size);
ellipse(125, 25, size, size);
ellipse(175, 25, size, size);```

Pretty easy. What if we had variables for the positions? We’d get this:

```let size = 50;
let x = size / 2;
ley y = size / 2;

ellipse(x, y, size, size);
x = x + size;
ellipse(x, y, size, size);
x = x + size;
ellipse(x, y, size, size);
x = x + size;
ellipse(x, y, size, size);
x = x + size;```

It’s longer than before, but notice how the same two lines now keep repeating. If we had a way to say “do these two lines four times” then this would get much shorter, and we do. We use the for statement:

```let size = 50;
let x = size / 2;
ley y = size / 2;

for (let i = 0; i < 4; i++){
ellipse(x, y, size, size);
x = x + size;
}```

The for statement is a bit complicated, so let’s break it down:

```for (do first; check to see if we keep going; do every time 2) {
do every time 1
}```

Note the curly brackets (braces) containing the stuff we want repeated.

So in our case we:

1. First create a new variable called i and give it the value 0
2. Check to make sure that i is less than 4
3. Draw our ellipse and make x bigger
4. Increase i by 1
5. Go back to step 2 and check if we can keep going, otherwise stop

This means that i will have the values 0, 1, 2 and 3 and our two lines will be run four times in total. Result! Our code can draw a row of circles. If we increase the value in the check, we can have as many as we like. We choose to have 8.

Nested Loops

Nesting a loop means putting one loop inside another. What’s the point of that? Well in our case we have a loop that can draw a single row of circles. If we put all of that inside another loop we could draw several rows. The row outside has a different variable j and also runs eight times. After we draw our row we do two things:

1. We make y bigger move down the screen
2. We move x back to the left to its starting position for the next row

The code now looks like this:

```let size = 50;
let x = size / 2;
let y = size / 2;

for (let j = 0; j < 8; j++){
for (let i = 0; i < 8; i++){
ellipse(x, y, size, size);
x = x + size;
}
y = y + size; // Move down and
x = size / 2; // Back to the left
}```

We now have 8 x 8 = 64 circles in a grid.

Changing the Colour of Some Circles Based on a Check

We then added code just before our call to ellipse() to change the colour based on some check:

```if( /* some check here */ ){
fill("red");
}
else {
fill("white");
}```

We experimented with some different checks to see what might happen. This check turns the upper-left of the grid red:

```if (i + j < 8 ){
:  :  :```

This check, using the modulus operator, turns every third circle of the grid red:

```if ((i + j) % 3 == 0){
:  :  :```

This check paints a red cross through the centre of the grid:

```if (i == 3 || i == 4 || j == 3 || j == 4){
:  :  :```

Lists

We then jumped quickly into lists. Also called arrays, lists are like a variable that can store several values. We create them simply like this:

```let a = []; // An empty list
let b = [1, 2, 4, 7]; // A list created with four entries```

To get at the entries in a list you just use the list variable’s name and square brackets containing the number of the entry in the list you want to get out, noting that the first one is zero:

```b[0] = 10; // Set the first entry in the list to ten
b[4] = 301; // Set the fifth entry in the list to three hundred and one```

A list isn’t just for holding numbers though, it can hold anything. It can hold strings for example, or even other lists!

It’s this idea of holding lists that we use to define our pattern.

Defining our Pattern

We make a list with eight entries, each of which is a list also containing eight entries, all zero. We write it so it forms a neat block like this:

```let pattern = [
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0]
];```

Then down in our code, where we’re deciding what colour to make our circles, we change the check to read:

```if (pattern[j][i] == 1){
: : :```

What does this mean? Well, j is a counter that goes from 0 -> 7 as we go down our eight rows. Given that, pattern[j] means get entry from our list for that row. Since pattern[j] is a list too, we need to say which entry we want in. The variable i goes from 0 -> 7 as we go across each row. So, pattern[j][i] gets the list for the row and then picks out the number for that column.

Once it’s set up, we can then change zeros to one in our pattern and have our circles turn red to match (red in the text below to make them stand out):

```let pattern = [
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 1, 0, 0],
[0, 0, 1, 0, 1, 0, 0, 0],
[0, 0, 1, 1, 0, 0, 0, 0],
[0, 0, 1, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 1, 0, 0, 0],
[0, 0, 1, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0]
];```

We have essentially built something that works like an image file! Our pattern is the image data and our program is the code that draws it.

As several smart people already noticed, you’re not limited to one and zero. By using more numbers, and expanding the if statement, you can have as many colours as you like.

The files for this week are on our GitHub, as always.

# Creators – Basic Scripting

This week we were joined by some additional ninjas, welcome! We had to do a little revision of the first week’s content and probably didn’t manage to get quite a much done as I’d hoped.

Let’s review what we did manage to get done.

Embed a simple script in a web-page

The first thing we did was to create our folders for this week and then create a brand new HTML file called index.html. We then embedded a simple script in our html file using the tag, like this:

`window.alarm("I'm alarmed");`

When we opened our page in Chrome, our message popped up as an alert.

Seperate that script into its own file

We then created a new file in our folder called script.js. We cut out everything from in between our and tags and pasted it into this new file:

`window.alarm("I'm alarmed");`

and in our HTML file we gave the tag the name of this file instead, using the src= attribute (short for “source”) :

Our script continued to work as before, as we’d hoped.

The advantage of moving scripts into their own files is that as we get more scripts and these scripts get more complex, keeping them all within the HTML file gets messy and difficult to work with.

Developer Tools

The developer tools build into Chrome, and some other browsers, help us see what is happening with our pages and scripts and helps us to fix them when they’re not working correctly.

To open the developer tools, open the menu in Chrome (the three dots in the upper-right of the program) and select More Tools | Developer Tools.

The console, part of the developer tools, is a place for us, as programmers, to write out things that will help us check if our script is doing what we want it to do. Ordinary users never see what developers write to the console.

To write to the console, we changed our script.js to read:

`console.log("I'm alarmed");`

The message box stopped appearing and this message could only be seen by looking at the console.

Basic Script Concepts

The most important basic concept in programming is that of a variable. A variable is just a place to store something and a name to refer to it by. We can make a new variable, in this case called a, like this:

`let a;`

The first word, let, is known as a keyword and tells JavaScript “we’re going to make a new variable”. The name of the variable, in this case a, comes next and finally a semi-colon (;) to show that this line is finished. The semi-colon is how we mark the end of a command in JavaScript and it’s an easy thing to forget.

We quickly made this example more complex:

```let a = 4;
let b = 5;
let c = a + b;

console.log("c");
console.log(c);```

In this extended example we defined three variables called a, b, and c respectively. Not only do we define them, we also assign them a value (using the operator =) at the same time. The first two are just given a simple value, but c has a value calculated from adding a and together.

The two console.log() line are to show the difference between actually writing the letter c to the console (as in the first line) and writing the value of the variable called c to the console (as in the second line).

Strings

Strings are how we hold a piece of text in a program. Strings are surrounded by quotations marks:

`"This is a string"`

I didn’t mention the last day, although I mean to, that JavaScript also allows strings with single quotes, which many other programming languages do not:

`'This is also a string'`

We experimented with changing our script so that instead of numbers we set our variable to strings:

```let a = "4";
let b = "5";
let c = a + b;

console.log("c");
console.log(c);```

and in the console saw the perhaps surprising result:

```c
45```

We determined that when we have two number variables the operator + does normal addition but when one or both are strings it makes a new string with the two stuck together (this is often called “concatenation”).

We introduced the following four mathematical operators:

• + : Plus does addition
• – : Minus does subtraction
• * : Asterix does multiplication
• / : Forward-slash does division  (don’t confuse with back-slash \)

Conditions

We looked at a simple condition. This allows us to choose between two options based on whether a check was true or not:

```if (c < 1){
console.log("c is less than one")
}
else {
console.log("c is greater than one")
}```

The keyword if  starts this check. The thing we’re testing is then inside roundy brackets (). Here we’re checking “is c less than one?”. After this we get a block of code (contained in the curly brackets {}) to do if it is true. Here we’ve also added (which is optional, you don’t have to have this if you don’t need it) the keyword else and another block of code to do if it is not true.

Basic Functions

Functions perform an action. They contain a bunch of commands to run together.

They’re great where we’re doing the same thing repeatedly but from different places and they help to logically break-up and organise our scripts.

Here’s a basic function that just writes to the console:

```function SayHi(){
console.log("Hi");
}```

The keyword function indicates that we’re going to define a function. Next comes the function name, SayHi in this case, followed by roundy brackets (), followed by a block of code surrounded by curly brackets {}. Inside the curly brackets are the commands that make up this function.

To make this function actually run we need this in our script:

`SayHi();`

Without this the function would never run. Functions only run when we “call” them.

Function Arguments

Sometimes it’s nice to be able to give a function more information about what we want to do. A function can take several values as input, these are called arguments.

Let’s imagine we don’t want our function to log the same thing to the console every time. We want to tell it what to write. Let’s see what that looks like:

```function MyFunction(what){
console.log(what);
}

MyFunction("Testing the function");```

Here our function is defined as before, but we have a name, what, inside the roundy brackets. Firstly, this means that when you call the function, you’re expected to provide a value. Secontly, inside MyFunction(), we have a new variable, here called what, containing the supplied value and usable like any normal variable.

Finally here’s a more complex example with two arguments:

```function Divide(m, n){
return m / n;
}```

There’s a new keyword here, return. This means “send back this value to the place that called me”. Let’s see how we might use it:

```let a = 4;
let b = 5;
let c = Divide(a, b);```

The third line here both calls the Divide() function and stores the value sent back.

P5.js

We had the briefest of introductions to P5.js and a flying visit to the new P5.js web editor. We’ll follow up properly on these next week.

Files from this week can be found on our GitHub page.

# Creators: Snake

This week we looked at creating a user-steerable snake in the style of the classic phone game.

Image from James Hamilton-Martin, Flickr

Things we need

The snakes head moves and the rest of the snake’s body is made up of places the head’s already been, up to a certain point. For this we use a JavaScript array (we’ve also called it a list at times).

We don’t want the snake’s length to grow indefinitely, so we have a maximum length. Once the list of stored locations gets larger than this, we use the JavaScript splice() command to remove the first (oldest) element from the list.

Direction and turning

We assign numbers to represent directions on the screen. Zero is right, one is up, two is left and three is down. Note then that if the snake is heading right (in the screen sense) and turns left it goes to up (in the screen sense); direction goes from zero to one. Similarly, if going up (in the screen sense) and it turns left then it goes to left (in the screen sense).

Generally then we note that turning to the left makes the direction number get bigger while turning to the right makes it get smaller. This rule hold until we get to a number bigger than three or smaller than zero; these make no sense. If direction is at zero and the snake goes right, we set direction to three. Similarly, if direction is at three and we turn left, we set direction to zero.

Getting this week’s code

As always, all the code from our Creator group can be found on our GitHub repository.

# Creators: Spirograph

This week in the Creators group we looked at emulating the classic toy, the Spirograph.

The Spirograph consists of geared plastic discs. One disc is fixed in place over a sheet of paper and the other, with a pencil tracing the path, is allowed to spin around it. The result is a complex and beautiful design on the paper.

This diagram should help explain in conjunction with the photo. The centre of the black disc spins around the centre of the red disc, which itself doesn’t move. So the centre of the black disc rotates around in a circle. Pretty simple?

Now, the pencil itself rotates around the centre of the black disc. Shouldn’t that make a circle too? Well it would if the black disc wasn’t moving. Thankfully though, it is and that’s what makes this interesting.

Finding the Location of the “Pencil”

So how do we find the location of the pencil? Let’s look at our diagram again, but with things re-labeled a bit:

• Centre: Formerly “centre of red disc”. It’s the fixed centre of our spirograph
• Centre2: Formerly “centre of black disk”
• Point: The point on our curve. This is where the pencil would be in a physical spirograph.
• Radius0: Distance from Centre to Centre2
• Radius1:Distance from Centre2 to Point
• Angle0: The current angle of the line between Centre and Centre2
• Speed0: The amount that angle0 increases every time we draw
• Angle1: The current angle of the line between Centre2 and Point
• Speed1: The amount that angle1 increases each time we draw

So at any time the location of our point is:

Point = Centre + [Centre2 relative to Centre] + [Point relative to Centre2]

So know where Centre is and if we can calculate where Centre2 is relative to Centre and similarly where Point is relative to Centre2, we can just add them all together!

Given an angle and a distance, can we get a location?

The answer to this is a resounding “yes”! Look at the diagram:

given an angle and a radius, we can calculate the X and Y position of any point around a circle. The magic is the COS and SIN (pronounced “kos” and “sign”) functions. These functions exist in almost all programming languages and JavaScript’s no exception.

Using p5.Vector

The last big concept we tackled thus week was using P5js’s built-in vector class to store (x, y) points and make our code tidier. To make a vector we just use createVector(x, y). We can then use functions to add them together, etc. We would get the same result working with the X and Y values separately but the code is a lot neater and shorter.

And in conclusion

This looks pretty cool:

Getting this week’s code

As aways, all the code from our Creator group can be found on our GitHub repository.

# Creators – Arrays and Classes

This week we looked at two very useful concepts in JavaScript, Arrays (we’ve also called them lists) and Classes (we’ve also called them objects). They are both things that allow one variable to store more than one value at at time. This can often be very convenient and has the potential to save us a lot of typing! Who doesn’t like that?

Arrays

A plain variable in JavaScript can store a single value, we’ve seen that loads of times:

```let a = 5;
let b = 7;
let c = a + b; // will be 5 + 7 = 12```

An array variable in JavaScript can store more than one value, just by putting them in square brackets and separating them with commas:

```let a = [5, 7]
let c = a[0] + a[1]; // This is the same as above!```

The code here does the exactly the same thing as the block above it. See that a now has two values in it and we use a[0] to get the first value and a[1] to get the second. This technique isn’t super useful when we only have two values, but the more we have to store, the more useful this gets. Imagine if we had 10 values,  how much shorter would the array version be?

You can also create an empty array and put values in it later:

```let a = [];
a.push(5);
a.push(7);```

In the code above we create an empty array (nothing between the square brackets) and then use the push() function to add two values into it.

Concept of Classes

A class is a programming concept that lets you define objects which contain both Properties and Methods. Properties are values associated with the object. Methods are actions that we can ask the object to perform.

Think of yourself as a Person object and imagine some of the Properties and Methods you might have.

Your Properties might include NameAgeHeightWeight, etc. A simple Method you might have could be SayHi(). That would make you say “Hi, it’s <Name>!”.

A method might have arguments, so it could be SayHiTo(“Dave”) which would make you say “Hi Dave!”.

Classes in JavaScript

Making classes in JavaScript is pretty easy. Let’s look at the Person class we showed above:

```class Person{
constructor(name, age, height, weight){
this.Name = name;
this.Age = age;
this.Height = height;
this.Weight = weight;
}

SayHi(){
Console.Log("Hi, it's " + this.Name + "!");
}

SayHi(who){
Console.Log("Hi " + who + "!" );
}
}```

We say “class“, the name of the class and a pair of curly brackets. Inside these brackets we have three functions (but notice we don’t have to say “function“).

Let’s look at the first of these, called constructor(). This is where we set the class properties. Note that we must put “this.” before properties to distinguish them.

The second two functions, SayHi() and SayHiTo() aren’t too usual, again note that we must use “this.Name” to get the value of the name property.

This week we created a class to represent a bouncing ball and we saw how easy it was, once we’d created the class, to make several of them, all bouncing around simultaneously. This would have taken us a lot more code to do if we hadn’t made a class. As always, the files can be downloaded from our Github page.

# Creators – Being Random

This week we mainly looked at three things:

• How data is organised on your computer
• Creating functions
• Using randomness to make things interesting

Data Organisation

Most of us had heard of a hard-disk before. This is a stack of metal disks inside your computer. Each metal disk has a special coating made of millions of tiny magnets (like you might find stuck to the fridge) that can be turned on and off.

We saw that able to turn something on and off, like a switch, was enough to count from zero to one, but the more switches we added, the higher we could count. Two switches can count from zero to three:

```Switch 1          | Switch 2          | Total (Add)
[Off = 0, On = 1] | [Off = 0, On = 2] |
------------------+-------------------+-----------
Off = 0           | Off = 0           | 0
On  = 1           | Off = 0           | 1
Off = 0           | On  = 2           | 2
On  = 1           | On  = 2           | 3```

With enough of these tiny switches, we can store anything we need. Each of these tiny switches is also known as a ‘bit’ and a 1 terabyte hard disk has a billion of them!

We also saw that the files on your disk are arranged with folders (also known as directories). Folders can contain both files and more folders. This allow us to keep our hard disk organised; without them all our files would be in the same place which would be difficult once we had more than a few. The location of a file is called its “path”. Looking at the highlighted file on the desktop of my Mac we can see the full path would be:

`/Users/kierancoughlan/Desktop/Ball and Bat Sounds.m4a`

This means that, reading backwards, the file called ‘Bat and Ball Sounds.m4a’ is in a folder called ‘Desktop’ which is itself inside a folder called ‘kierancoughlan’ which is, at the highest level, inside a folder called ‘Users’.

Functions

A function is a collection of commands that do a job together. We’ve already encountered them, even if you hadn’t especially noticed:

• Our P5 template already contains two functions called start() and draw()
• All of the P5 commands we have used, such as createCanvas() and rect() are functions themselves

We could add all our code to start() and draw(), in fact, that’s what we’ve done before this week. That’s fine starting out, but it does mean, once there are a lot of commands in those functions, that our code is gets harder to read and understand. Breaking out a few commands into a new function and giving it a name that describes what it is doing, really helps.

Once we’ve written a function, it can be called as many times, and from as many places, we as need.

Functions can do one other thing too: they can give back a value to the place where they were called from. For this we use the special word return. For example, let’s see what a function to pick the largest of two numbers, we’ll call it Max(), might look like:

```function start(){
let a = 4;
let b = 10;
let c = Max(a, b);
}

function Max(n1, n2){
if (n1 > n2)
return n1;
else
return n2;
}```

We give Max() the two numbers we are comparing. If the first one is bigger than the second, it gives back the first. Otherwise, if gives back the second. Note too that the names of the variables in Max() are different to those in start(), and that’s not a problem.

Random

Finally, we looked at the P5 function random(). We used it two different ways:

```random(); // gives a number between 0...1
random(n); // gives a number between 0...n (where n is a number!)```

In the first form, we used it to pick a random colour. In the second, we used it to pick a random position for our squares.

Files

As usual, all the code is on the creators github repository. Head there and download it!! The files for this week contain both the script we wrote (sketch.js) and a longer version that I wrote (sketch2.js). Feel free to take a look at both!