Week 9 2015 – Scratch Beginners – Piano

Hello everyone,

Thank you all for coming yesterday on such a lovely day.

Thank you to Sean Shanley for demoing a 2D plotter that is controlled by Arduino, with 3D printed parts, and programmed with a Scratch variant called mblock.

The Arduino kits are available to buy on Amazon and the website where you can get all the ideas and instructions is called Instructables.

This week we did a simple Piano.

piano

We only had to draw two keys, and then could duplicate these and change the names. The same applied to the code. The code is the same for each key apart from one small change so the note is the appropriate for the key.

Piano2

Piano3

See you all next week, our last session before we have a one week break for the bank holiday and then we will be back working on individual projects, getting ready for our final day and the day we will award the belts.

belts

 

Here are notes from this week in PDF CDA-S4-Challenge-PrepareForBelts and Piano.pdf

Martha

ScriptCraft – An Exploding Chickens Mod

A few weeks ago we were lucky enough to have a visit from YouTuber and professional Minecraft modder (for the HyPixel server) codename_B (a.k.a. VladToBeHere, a.k.a. Ben).

Ben (left) addresses CoderDojo Athenry. ,Also pictured: Auburn, Ben's girlfriend, and our own Michael Madden

Ben (left) addresses CoderDojo Athenry. Also pictured: Auburn, Ben’s girlfriend, and our own Michael Madden

Ben is an extraordinary programmer who just breathes code. On his YouTube channel he regularly creates a complete MineCraft plugin in only sixty seconds!

After addressing the entire Dojo, Ben showed our modder group and a few other more advanced coders how to make a quick plugin which causes chickens to explode when a player kills them.

Ben’s mod was written in Java and used the Bukkit API to interface with MineCraft.

Porting the Plugin to ScriptCraft

ScriptCraft is built on top of Bukkit. Because of this, almost all the Bukkit API is available for use in ScriptCraft. I believe there are a few Java-only bits in Bukkit, but I haven’t encountered them.

I realized that, in theory at least, it should be possible to port Ben’s plugin to ScriptCraft. In practice, it proved to be more straightforward than I could have hoped. If you don’t already know Java, ScriptCraft is a great place to start if you want to create MineCraft mods.

ScriptCraft and Bukkit References

When writing something new, you’ll need to be able to look-up things that you are not familiar with. Two references I used for this script, apart from Ben’s original code, were:

  1. ScriptCraft API
  2. Bukkit API (from Spigot)

Browsing these resources is also a good way to see what can be done and to thereby generate new ideas.

Anatomy of the Plugin

The plugin is composed of four parts:

  1. Two variables to represent the Bukkit types which represent chickens and players respectively
  2. A loading function which we will run when the plugin loads
  3. An event handling function which will be called whenever one entity damages another
  4. A call to the loading function, at the bottom of the file, to make it run as soon as ScriptCraft reads it

Let’s talk about each of these parts in turn.

Variables to Represent Bukkit Types

After a require(‘events’) line (to make sure we can reference the events object), there are two lines as follows:

var bkPlayer = org.bukkit.entity.Player;
var bkChicken = org.bukkit.entity.Chicken;

These are ‘types’ which represent an entity of type Player and an entity of type Chicken respectively. We’ll use them in a bit to determine, when we’re told one entity has damaged another, that it was a Player entity causing damage to a Chicken entity.

The Loading Function

The next part of the script is the loading function. It’s short and really only does two things:

  1. Announces that the plugin has loaded by printing a message to the console
  2. Tells Bukkit that we’d like a function of our own to be run each time that a particular event occurs. In this case it’s the event that fires every time one entity damages another.

Here’s the code:

// The function which will run when we load this module
var _loadMod = function()
{
  // Announce ourselves to the console
  console.log("Exploding Chickens: [Loading ScriptCraft Mod]");

  // Tie our code into the event that fires every time one entity damages another
  events.entityDamageByEntity(_entityDamageByEntity);
}

We’re passing events.entityDamageByEntity() the name of our function we’d like to have run. That function (_entityDamageByEntity) and this function (_loadMod) both have underscores at the start of their names. It’s a JavaScript convention which indicates that we’re never be calling these functions by name from outside this file. They’re private or internal functions.

The Event Handling Function

This is the most complex part of the module, but not terribly so. Here’s the code:

// The code that we want to run each time one entity damages another
var _entityDamageByEntity = function(event)
{
  // Find out, from the event, who's getting damaged and who did the damage
  var damagedEntity = event.getEntity();
  var damagingEntity = event.getDamager();
  
  // If it's a chicken getting damaged by a player, game on...
  if (damagedEntity instanceof bkChicken && damagingEntity instanceof bkPlayer)
  {
    // Announce in the console that we've detected a player damaging a chicken
    console.log("Exploding Chickens: [A player damaged a chicken]");
    
    // Schedule a task to run in five seconds.
    server.scheduler.scheduleSyncDelayedTask(__plugin, function() 
    {
      // Check to see if the damage brings the chicken's health
      // down to, or below, zero. If so, it's dead...
      if (damagedEntity.getHealth() - event.getDamage() <= 0)
      {
        // Get the chicken's location
        var loc = damagedEntity.location;

        // Create an explosion at the chicken's location. 
        // A big one...
        loc.world.createExplosion(loc, 10.0);
      }
    }, 20 * 5);
  }
}

What does it do?

  1. Gets the entity that caused the damage and the entity that was damaged and check to see if they’re a player and a chicken respectively
  2. If they are a player and a chicken, Schedule a task to run in aprox. five seconds. This task can result in an explosion, so it’s nice to have a little “getting away” time.
  3. When our task runs, see if the amount of damage inflicted was enough to bring the chicken’s health down to zero (or below) and if it was, make a massive explosion where the chicken was.

The Bukkit function scheduler.scheduleSyncDelayedTask() needs a reference to the plugin which is asking for the task to be scheduled. In this case it’s ScriptCraft and there is a special automatic variable, __plugin, which ScriptCraft can use to refer to itself when it needs to.

And that’s pretty much it!

Getting it All Going

The last line in the file is just a call to our _loadMod() function. This will get run immediately by ScriptCraft when it read it, setting the mod into action:

// Run this script as soon as the file's loaded
_loadMod();

Finally

Here’s the mod in action:

Sorry chickens*.

The script file can be downloaded from here. I hope this inspires you to create your own server mods using ScriptCraft.

 

 

* The author is a vegetarian and general soft touch who even tends to feel bad about exploding virtual animals…

 

Week 8 – 2015 Scratch Beginners

Hi everyone,

We completed our Mario game this week. We coded Mario so that he always floated down on to the wall. We added a fraction of a second of a wait so that it appears that he floats as he comes down. This also allows time for you to navigate left or right as needed.

CDA-S3-Challenge09-Scrolling

We also introduced a more advanced concept, the Parallax effect, whereby objects further away appear to move slower than objects nearer. We coded mountains and a Sun to demonstrate this.

 

You will a full version of the my notes in pdf form here. CDA-S4-Challenge09-Scrolling.pdf

Have a great Easter!

Martha

PiDojo : Programming the Raspberry Pi

Over the last couple of sessions we’ve been using Python to write some programs for the Raspberry Pi.

Last week we wrote some easy Hello World type programs and today we finally started to use the Raspberry Pi GPIO pins.

We learned how to set up pins as outputs or inputs and how to use these pins to light up a LED or sound a buzzer and how to read from an input pin.

The group then used what we learned to make a simple traffic light.

Our breadboard with LEDS, buzzers and a switch

Our breadboard with LEDS, buzzers and a switch

Here are my slides from the last two sessions Raspberry Pi programs

ModderDojo Countries Mod Week 1: Making a start on a large group project mod

CountriesModV1

In the ModderDojo group, we have started to work on a large group project to develop a mod with different aspects to it.

Following on from brainstorming session in recent weeks, we have decided to build a Countries Mod: there will be multiple different countries, each with different terrains, buildings and items such as food, clothing and weapons. We hope to have portals and an airplane to move between countries. Some parts will be implemented in Java and others in JavaScript. It should be exciting to work together and produce something impressive!

To plan the project and track our progress, we will use a project dashboard as shown above: items planned but not started are in white; items underway are in yellow; items completed are in green; any that we decide to drop will be in grey.

The young people of the ModderDojo group are also arranging a code repository and communications using skype between team members, and are planning to set up a server with  the mod on it and prepare one or more a mod review videos as it gets developed.

I am greatly impressed with the group’s ideas, enthusiasm, and capabilities!

Below are my slides from when we kicked off the project, the first couple of which referred back to when we started the stream in September.

Slide1

Slide2Slide3Slide4

Week 7 – 2015 Scratch Beginners – Scrolling Backrounds

Hi everyone,

Thank you all for coming Saturday on such a nice day and such a busy day of sport as well!
We started our Mario game, where we will use scrolling of objects in the background to achieve movement rather than making Mario move.
scrolling

It can be a difficult concept to grasp for the younger ones, but we will go through it again next week before we continue on with the game.

scrolling2

Rather than putting up the notes from this week, I will wait until we have the game finished before putting up the completed notes.
I have however, put the game (as far as we did today) on the Scratch Website http://www.scratch.mit.edu. Login with the User name coderdojodathenry and password xxxxxxx123 and you will be able to download the game if you weren’t here this week or have a look at the code to get your own game work working.

MarioGame

See you all next week, when we will make Shrink and add some more scrolling sprites!

Martha

Automatically Generated ScriptCraft to Draw An Image

image_process

Having done tagger.js, I thought “wouldn’t it be nice not to have to specify the design by hand?”

I started thinking about how cool it would be to have a way to take an image file and use that to define the design that tagger.js was going to spray.

The first thing that I determined was that, as far as I can see, there isn’t any built-in support for the various image formats (GIF, JPEG, PNG, etc.) in ScriptCraft. OK, so what then? Well, web browsers are great at handling images in all kinds of different formats. The HTML5 canvas element is good for playing around with bitmaps and on top of all that, JavaScript is supported for the coding part!

So, with very little previous experience and plenty of Googling, I decided to make a web page which would allow the user to enter a file’s name, press a few buttons and a ScriptCraft script would appear, as if by magic. Development was pretty smooth, baring one significant road-bump which I’ll describe. I’m not going to go into details about how the HTML file was made, but it should be clear enough if you want to read it. I will however describe the process of colour mapping.

HTML5 and a Tale of Tainted Canvases

Say what? An odd problem I quickly hit was that I couldn’t just specify an image file from just anywhere (using HTTP:). In fact, even worse, when I directly loaded my HTML page in my browser (using FILE:), I couldn’t even load up an image file which was in the same directory as the HTML page.

More Googling followed. Turns out that the browser was trying to protect me from “cross-origin data”, which is a security risk. Luckily there was an easy solution. I downloaded a small web server application and used that to serve my HTML page, which eliminated the issue. The web-server I chose was Mongoose, because it’s a single application, light and fast, but you can use another web-server if you prefer.

Testing in Chrome

I used Google Chrome as my browser for developing and testing this webpage. Chrome has a JavaScript console, which greatly simplifies debugging scripts. It can be found from the menu to the right of the address bar, at More Tools > JavaScript Console. Among other features, It allows you to set breakpoints and watch the value of variables as the script executes. It will also show you errors in your code, where it finds them.

Colour Mapping

The most important part of this script is mapping the colour of each pixel in the original image to an equivalent block in MineCraft. For this example, I have restricted myself to the 16 wool colours. So, for every pixel in the original image, I have to choose the MineCraft wool block that’s the closest in colour.

MineCraft Wool Palette

MineCraft Wool Palette

The colours we are going to match against are above. If you’re curious, here’s how I generated this MineCraft palette, I laid all 16 MineCraft wool blocks in order, from white to black, and then took a screenshot. This screenshot was, of course, influenced by the lighting in MineCraft at the time I took the screenshot and each block had the wool texture applied to (i.e. they weren’t just one flat colour). I did some further image manipulation to improve the palette. I applied a strong blur effect to downplay the effect of the texture and then I used my image editors Histogram Stretch functionality to make sure that the whitest and blackest colours were pushed towards true white and true black. Finally I sampled one point on each block and that became my representative colour.

These colours, in RGB format, became an array in the JavaScript inside my webpage:

var paletteRGB = [[255, 255, 255], 
                  [222, 146, 79],
                  [177, 98, 186],
                  [115, 152, 197],
                  [178, 185, 60],
                  [76, 179, 67],
                  [213, 151, 159],
                  [51, 51, 51],
                  [164, 180, 170],
                  [44, 109, 122],
                  [116, 68, 167],
                  [30, 50, 113],
                  [59, 43, 14],
                  [35, 62, 15],
                  [132, 53, 40],
                  [0, 0, 0]];

RGB (Red/Green/Blue) is a common way to represent colour. Its three numerical values, each of which can range between 0 and 255, represent the relative strengths of the Red, Green and Blue channels. We can think of this as a co-ordinate system, with the R, G and B values as axes.

RGB Colour Space Imagined as a Cube

Description: RGB Colour Space Imagined as a Cube. Author: SharkD. Source: http://commons.wikimedia.org/wiki/File:RGB_color_solid_cube.png

The image above shows what this looks like. Pure white is on the corner nearest to us. The opposite corner, which we can’t see, is pure black. Colours aren’t just on the surface of this cube either, If we were to cut through it at any plane, we would see all the colours on the inside as well.

Therefore, the difference between two colours can be thought of as the distance between two points in RGB space. It’s Pythagoras’ Theorem again, as we saw in the rainbowk.js project, but in 3D. All we have to do is take the colour of each pixel in the input image, calculate how far is is from each MineCraft wool colour and pick the wool colour which is the closest in distance; that will be the most similar.

Easy right? Well, almost. Turns out, our eyes don’t quite work that way. We’re not as sensitive to changes in some colours as we are in others. We’re most sensitive to changes in shades of blue, and least sensitive to changes in shades of green. If asked to pick by eye, we might make a different choice for the “closest” colour than then one given by mathematics alone. Luckily, scientists have worked out factors which account for this. If you look in the final script you’ll see that there are factors which are used to weight (make more important) the difference in some colours than others. You don’t need to understand how these numbers were arrived at, just understand why they are there.

// It's Pythagoras' theorem again, but weighted.
function weightedDistanceSquaredRgb(r0, g0, b0, r1, g1, b1)
{
  // These weights are used to convert RGB -> YUV and are useful here
  // to enhance the perceived closeness of two colours
  var weightR = 0.299;
  var weightG = 0.587;
  var weightB = 0.114;
  
  // Distance between two points in space: sqrt(x^2 + y^2 + z^2)
  return distanceSquared(r0 * weightR, g0 * weightG, b0 * weightB,
                         r1 * weightR, g1 * weightG, b1 * weightB);
}

By the way, notice that we’re returning the distance squared here. It’s a common programming shortcut if we’re just checking for the nearest thing. If something has the closest distance, it will also have the smallest distance squared. Doing the square root calculation isn’t worth it – so we don’t.

Downloading and Running

The ZIP file containing this HTML file (image_process.html) and a few sample images can be downloaded from here. Remember, you’ll have to use a web-server to view this webpage and have it be able to process the images. Feel free to try your own images, just copy them into the same directory as the HTML file first, and remember to keep them small as every pixel becomes a MineCraft block. My sample images are all around 40px wide.

What’s Next?

Next week we’ll extend this little application to add optional transparency to the output and merge it with tagger.js so our image is sprayed onto the environment.

PiDojo : Connecting to the Raspberry Pi from your laptop

As it would be awkward to bring televisions and keyboards and all the other equipment required to operate the Raspberry Pi into CoderDojo we will connect to them from our laptops. We had a go at this today and we made some progress but we had problems with a couple of computers hopefully, I may have found a fix for them.

We were able to connect most of the laptops using Internet Connection Sharing but on the ones we couldn’t connect to, I think creating a Network Bridge might work. Instructions are available here. Here are my slides from today Raspberry Pi Headless Operation.pptx

Scriptcraft – A Little Friendly Vandalism

For this week’s sample script, building on the ideas developed the week before, I decided to pander to the crowd a little and show a script called tagger.js which allows you to ‘spray’ a design, in a block type of your choice onto the environment. It can be downloaded from here.

Description: Graffiti near Moganshan Road in Shanghai. Photographer: Jakub Hałun. Artist: Unknown. Source: Wikimedia Commons

Defining Our Design

The script contains an array of strings used to defined our design. In the array each string represents a row. Each character in those strings represents a block. Spaces are treated as blanks, anything else is a part of our design. Take a look at this specification which represents a peace sign:

var tag = ["   ***   ",
           " ** * ** ",
           " *  *  * ",
           "*   *   *",
           "*  ***  *",
           "* * * * *",
           " *  *  * ",
           " ** * ** ",
           "   ***   "];

It may be a little hard to make out at first, because characters are much narrower than lines are tall and the whole thing is stretched. Comparing to this drawing should help:

Peace Sign

Peace sign design for tagger.js

I’ve used asterisks in my strings just because it fills the space, but any non-space character will work just as well.

Spraying Onto What’s Already There

The fun thing about tagger.js is that it places the design on whatever is already in the world. It’s not restricted to flat surfaces!

The script looks at the area the player is facing and moves forwards, within a sensible limit, until it encounters a solid block (not air). If it finds one, it changes the block to the requested type. These diagrams show the operation.

Tagger_before

Tagger_after

If no block is found within the search depth, as has happened several times in the diagram above, that part of the design is left out.

In Action

Below is a screenshot of tagger in action: a big stone sphere with a love heart, made of red wool, and a partial smiley, made of gold blocks, sprayed onto it (partial because I was too far away when I called the script and some blocks were beyond the default depth).

tagger

Not Only … But Also

The script also has a few other little interesting features. In common with many of the standard Scriptcraft functions, this one shows how to check for parameters being left out and how to provide default values when that happens. It also shows how to retrieve a part of an existing string, used here to get a single character at a time. Take a look at the script yourself to see how this happens.

Week 5 – 2015 – Scratch Beginners

Hello everyone.

Good to see everyone there on Saturday. We made a game called Wipeout similar to on old game called Breakout.

wipeout

We used a number of important coding concepts again this week, loops and decisions, Variables, broadcasting, etc.

concepts

Yesterday during class, we didn’t have time to add the Lives and the Scores but I am hoping everyone will try it themselves at home. We have done it many times now and I am sure you are well able to do it. Try it first on your own but I have put my game up on the scratch website so you can take a look at it if you get stuck. Here is a link Wipeout Game

No Coderdojo Athenry for the next two weeks but I hope to see you all back on the 7th of March.

Enjoy the break

Martha