Creators: Shootah Part 2 – Sound and Bullets

This week we carried on our “Shootah” space shooting game  by adding some bullets with an appropriate sound effect.  This brings the game to the stage shown below:

Not very snazzy but it’s starting to show some promise!

As with last week, this will only run if served up from a web server, we had a few ninjas in that missed last week and had to install node.js and local-web-server application.

Bullets!

Our Bullets were a pretty simple object that just moves up constantly – this has the following code:

class Bullet {
    constructor(x, y){
        this.x = x;
        this.y = y;        
        this.speed = 10;
    }

    move(){
        this.y = this.y - this.speed;
    }

    show(){
        push();
        fill("yellow");
        ellipse(this.x, this.y, 10, 10);
        pop();
    }
}

We created an array of bullets and added a new one to the array each time the up arrow is pressed.  In addition, we played a “firing” sound which really adds to the feeling:

function preload(){
   playerImage = loadImage("images/spaceship.png");
   bulletSound = loadSound("sound/laser.mp3");
}

function draw() {
  // .... skipping a few lines
  for(let i=0; i< bullets.length; i++){
     bullets[i].move();
     bullets[i].show();
  }
  // .... skipping a few lines
}

function keyPressed(){
   if(keyCode==UP_ARROW){
   bullets.push(new Bullet(player.x, player.y));
   bulletSound.play();
 }
}

 

The sound was done very similarly to the image – we created a folder (sound) and added a sound file we found on the internet to the folder.  In the preload function we loaded the sound from the file into a variable (“bulletSound”).  In the keyPressed function, we check if the pressed key is UP ARROW and if so, we play the sound and add a new bullet to the list.. voila!

Problems to work on!

A great start but a lot left to be sorted with this game!  Here are some of the items:

  • The bullets array grows forever – this really starts to slow down the game as we keep playing it.  We need to add some code to remove a bullet from the array when it is gone off the screen.
  • The player has no edge detection – we need some way to keep it onscreen.
  • We need some enemies!!
  • We need to get the bullets to check when they are hitting the enemies!
  • We need to keep and display a score
  • We need a way to die.. perhaps the enemies can drop bombs?
  • Other ideas:
    • Maybe a background tune in a loop?
    • Maybe a scrolling starfield in the background?
    • Maybe multiple levels?
    • Maybe different types of enemies?
    • Maybe a shield?
    • Perhaps some different weapons or weapons you can pick up?

We have gotten this far so we might as well push forward and make this a fully working game so we’ll get some of the above sorted next week!  The code is as usual up on our github.  https://github.com/coderdojoathenry/creators2018

 

 

 

Hackers – Controlling Motors with an Arduino and H-Bridge

Previously in Hackers we have studied how transistors work, and made a transistor-based circuit to control a motor from an Arduino: Hackers – a Joule Thief and Controlling Motors.

When you write to a pin on the Arduino, it outputs a voltage. However, you can’t use this directly to drive an electric motor, because they require too much current, and it would damage the Arduino. The solution is to use a 6V battery as an external power supply, and connect it to the motor via a transistor circuit. When you apply a signal with small current to the middle leg of the transistor, a much larger current can flow from the battery to the motor.

While this works, a more elaborate circuit is needed if you want to be able to control two motors, and make them go backwards and forwards. This circuit is called a Dual H-Bridge. The Wikipedia page has technical details: https://en.wikipedia.org/wiki/H_bridge

We are using a pre-built integrated circuit for our H-Bridge, as they are low-cost, small, and work well. Here is the one we are using:

h-bridge

It has several connectors:

  • [+] and [-] are where the external battery is connected
  • [IN1] and [IN2] control Motor A (details below)
  • [IN3] and [IN4] control Motor B
  • [Motor A] and [Motor B] each have two pins that are connected directly to motors

To control Motor A, connect [IN1] and [IN2] to two pins of the Arduino, such as 6 and 7:

  • [IN1] HIGH and [IN2] LOW: Motor A goes forward full speed
  • [IN1] LOW and [IN2] HIGH: Motor A goes backward full speed
  • Both LOW: Motor A does not turn (no power, it coasts)
  • Both HIGH: Motor A does not turn (is braked)
  • To control speed, use a value for the pins connected to [IN1] or [IN2] in the range 0-255 (0=LOW, 255=HIGH)

Here is Arduino code to control a motor with a H-Bridge, written by Luke, one of our Hackers:

// Luke Madden, CoderDojo Athenry
// Control motors using a H Bridge

// The H bridge has 4 input pins: in1-in4
#define in1 6
#define in2 7

int fast = 100;// range 1-255
int slow = 50;// slower speed
int hyperspeed = 255;// hits the hyperdrive

void setup() {
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  drive();
}

 void drive() {
  // Test the functions
  Serial.println("move forward");
  forward();
  delay(2000);

  Serial.println("hit the hyperdrive");
  hyperdrive();
  delay(2000);

  Serial.println("go backwards");
  backwards();
  delay(2000);
}

void forward() {
  //makes motor go forwards
  analogWrite(in1, fast);
  analogWrite(in2, 0);
}

void hyperdrive() {
  //hits the hyperdrive
  analogWrite(in1, hyperspeed);
  analogWrite(in2, 0);
}

void backwards() {
  //makes motor go backwards
  analogWrite(in1, 0);
  analogWrite(in2, slow);
}

void stopping(){
  //makes it stop
  analogWrite(in1, 0);
  analogWrite(in2, 0);
}

Hackers – Hide and Seek

We welcomed back Hackers Group members Luke and Sean, who had projects at the Young Scientists Exhibition last week.  Details of their projects are in another post: Congratulations to our members who presented at the BT Young Scientists 2019!

This week we divided the group into two teams to work on our hide-and-seek robots:  One team to build the hider robot, the other to build the seeker robot.

The two robots can use many of the same parts, but the control systems will be different.  The hider robot will be operated by a person with an RC transmitter.  The seeker robot will control itself.

Team Hider started resurrecting a radio-controlled robot that we built last year.  The robot was involved in a battle-bots battle at the end of the year, so it is in pretty poor shape.
Teem Seeker worked on a colour tracking system.  We took the code that we developed on a laptop before Christmas and tried it on two Raspberry Pis.  We found that the original model Raspberry Pi wasn’t fast enough to do the job we needed.  It took 6 seconds to acquire an image from a webcam.  We tried a Model 3 B instead.  This was fast enough for our needs.  We then started work on tuning the colour detection.  There’s some more experimentation to be done to find the best colour range to work with.

Creators: Images and Web Servers

Up to this point in Creators we have been building all of our apps as sketches ourselves using the drawing functions in p5/javascript – ellipse, rect, etc.  This is great but a question we get all the time is “how can I load IMAGES and Sound into my games?”.  This week we got stuck into this, using a project of a very basic shooting game as an example.

However, before we got stuck into writing our game, we needed to install something on our computers called a web server.

What is a web server and why do we need it?

A web server is a program that makes files available on the internet.  Mostly, the files are made available to programs that can understand the Hyper Text Transfer Protocol – or http for short.  “http” probably sounds familiar – this is because you are used to seeing it on your browser before internet links.

Up until this point, we simply opened files on our computer with explorer and if you looked at the browser link you would see something like this:

file:///C:/Users/markdav/code/dojo/creators2018/Week11-shootah/index.html

The “file” at the start means the browser is opening a file on the local computer.  This works great for a lot of things, however if you write a program in javascript which runs on the computer, javascript is not allowed to open files on the local computer.  Why? Because if javascript could open files on the computer of the person opening a website, it would be easy to write a webpage that steals information from people looking at it, without them knowing it.  This would be a BIG security problem!!

Javascript can only open files which are served out by a web server – so in order to load images or sound into a javascript program, we need to make sure that they are served out by a web server.

Installing our Web Server – Node.js

nodejslogo

There are lots and lots of web server programs out there but we decided to install one which is written in javascript – we are javascript nuts after all!  Node.js isn’t actually a web server, but is a set of programs kind of like p5 that make it easy to write or install programs in javascript for your computer – and especially ones like web servers.  Later in the year we will play some more with node.js and write our own programs in it to do some cool stuff.

We installed node.js from the node website here.

Once we installed node.js, we then installed a web server which is written in node.js – we installed one called “local web server”.  To install local web server – we opened a command terminal in the computer and typed the following:

npm install -g local-web-server

npm stands for “Node Package Manager” and it’s a program that makes it easy to install programs written in node on your computer.  Once this was done, we have a new command in our computer – the command is “ws” and what it does is to start a web server that puts the files from the current folder on the internet!

To try it out, we started a new p5 project called “shootah” and right clicked on the folder and selected “open in terminal”.  The command prompt appears directly in Visual Studio Code, which is handy.  We then typed “ws”

markdav@markdav2017 MINGW64 ~/code/dojo/creators2018/Week11-shootah (master)
$ ws
Serving at http://markdav2017:8000, http://192.168.71.1:8000, http://192.168.48.1:8000, http://192.168.1.20:8000, http://127.0.0.1:8000

This started a web server in the folder which serves out the files – to open we used either one of the links given, or actually we kind of preferred to type “http://localhost:8000&#8221; which was another way of putting it.  When we did this, the files just showed in the browser!

Developing Shootah

All this installing took us some time, but we were ready to get stuck into developing our space shooting game.  We go to the stage of getting a Spaceship which we could move left and right – but no bullets, sound or enemies, yet.

First we needed a spaceship picture, and we had a bit of fun rooting around on the internet for one.  Some people created their own images.  I ended up picking this picture (you can right-click this picture and save it if you like it too):

big-spaceship

When we had the spaceship picture, we created a folder to store our pictures.  I created a folder called “images” and put the picture in there and called it big-spaceship.png.  Some others called their folder “assets” which is a term you often see used. To be honest my picture was a bit big – you are better off making the images just the right size, as it saves a little bit on memory for the computer when showing them.

We learned that there is another special function in p5 which is best to use when we are loading files like sounds and images into variables – it’s called “preload” and we wrote the code to load our images in there:

let playerImage;

function preload(){

      playerImage = loadImage("images/big-spaceship.png");

}

Once we had the image loaded, we could draw it using the “image” function.   The show function on our player used this to paint the image:

show(){
    imageMode(CENTER);
    image(this.img, this.x, height-100, 100, 100);
}

Aside from that, the code was pretty similar to other sketches we have done.  We put some basic code in to allow the player to be moved left and right.  This is as far as we’ve gotten – next week we’ll work on it some more and see if we can get some enemies, bullets, sounds, maybe stars, scores, better movement, etc.  Code is on github as usual!

shooter-1

 

Demos and Pizza – Christmas 2018

Here are photos from our Christmas party and Show & Tell day at CoderDojo Athenry on 08 December 2018.

This slideshow requires JavaScript.

It was fantastic to see the things that our young people had created.

We are very grateful to our supporters in the community around Athenry:

  • Clarin College and Principal Ciaran Folan, who are so generous with their space every week
  • Galway & Roscommon Education & Training Board, who provide us with an annual Youth Club Grant
  • HEA (Higher Education Authority) and NUI Galway School of Computer Science, who provide us with funding towards equipment.
  • Medtronic and Declan Fox, who have provided us with a grant linked to Declan’s volunteering
  • Hewlett Packard Enterprise and Mark Davis, who provide us with loaner laptops
  • Boston Scientific and Kevin Madden, who provide us with the loan of 3D printers.
  • Supermacs, who gave us a great deal on the food for the Christmas party

And of course, we are eternally grateful to our wonderful mentors, and to the parents who come along with their children every week. Thank you!

Hackers – Starting with object recognition

This week we looked at two ways to do object recognition.

Kevin went through the steps involved in finding an object with a particular colour in an image.  He started on an image with six circles each of a different colour, and demonstrated finding a green circle in the image.  Then he stepped through the Python code and explained each task.

Here’s the image:

circles_small

OpenCV, the Open Source Computer Vision library, has lots of functions for transforming and processing images.

We started with a standard RGB (red, green, blue) JPEG image, which OpenCV stores in memory as BGR (blue, red, green).  Then we transformed the image to HSV (hue, saturation, value) format.  The HSV colour space has a very useful property:  colours are described by their hue and saturation.  The value represents the intensity of the colour.  This means that we can use H and S to find a colour, without having to worry much about lighting or shadows.

Next we used the known value for the green circle to apply a threshold to the image:  any colours above or below the threshold are converted to black.  Any colour at the threshold is converted to white.  Here’s what the thresholded image looked like:

threshold_small

Then we found the white area in the image.  To do that, we used an OpenCV function that gets the co-ordinates for contours that can be drawn around the boundaries of all the white regions in the image.  We calculated the areas of each contour, and took the largest.  We’ll find out why this is useful later.

To show that we had found the right circle, we calculated the co-ordinates of its centre-point.  Finally, we drew a small cross at that centre-point to mark it, and displayed the full image on screen.  This is what we ended up with:

green_smallSince we had a contour, we also used that contour to draw a line around the perimeter of the circle.

Next, we took a photo of a blue marker, found the HSV value of the blue, and used that value to find the marker in a live image.  We held the marker in front of a laptop webcam, moved the marker around, and watched as the spot moved with it.  Our method for finding a particular colour works for any shape, since we use a contour, not just circles.

Michael introduced us to TensorFlow, a machine learning library.  Once trained, TensorFlow can identify specific objects by name.  It’s a lot more sophisticated than finding something by colour.  We spent some time setting the library up on a Raspberry Pi.  The Pi isn’t powerful enough to train the software, but it is capable of doing the recognition after training models on more powerful computers.

Or final goal is to build an autonomous robot to play a game of hide and seek.  We can use one of our remote-controlled battlebots from last year to hide, and the new robot to do the seeking on its own.  One way to do the seeking would be to go after the biggest thing in the robot’s field of view that has a particular colour – the colour of the hiding robot.  Another way to do the seeking would be to train a TensorFlow model with pictures of the hiding robot, so that the seeker can recognise it from different angles.

It’s going to take us a while to figure out what works best, and then we have to work out how to control our robot.  It should be an interesting new year.

Creators: Introducing Force

Last week in Creators, we looked at Vectors and how they can be used to specify things like position, velocity and acceleration.  This week, we looked at what can actually cause something to accelerate – FORCE!  First we talked and played a bit with force and then we created a simulation of something that we could apply different forces to.  We wanted to think about a scene where we had lots of objects and different forces acting like wind, gravity, friction, etc.

What the heck IS force?

We started off by looking at the laws of motion from Sir Isaac Newton, who was the first guy to think hard about this (or at least to come up with good theories).  Everyone knew about the apple but not many about what it made him think of.  We googled his laws of motion and arrived at a NASA web Page that had a nice short explanation:

newton

Newton’s laws of Motion (NASA)

Like all great ideas, these look obvious when you know the answer, but were huge ideas at the time!  I’ll butcher the above laws by trying to re-word them to capture the interesting thing about them from our point of view!

Continue reading

Creators: Objects and Vectors!

This week in Creators we covered a few very important concepts which we will likely need to run over a few times until we get them solid!

What are Vectors?

First we looked into a concept called Vectors, in particular 2D Vectors.  We saw that at the most basic, a Vector is a simple way of holding an x and a y in one variable.  This is useful for keeping track of the position of an object as you only need to keep one variable e.g. “rocketPosition” rather than two “rocket_x, rocket_y”.

vector-add3

The other thing we talked about is how this X and Y can represent a change in a given direction – i.e. a vector with x=10 and y=5 can mean “change X by 10 and y by 5”.  This way it’s useful for ANYTHING that might be in a given direction – things like velocity and acceleration for example!

The other thing cool about the vector object in p5 is that it has a bunch of functions that allow you to add, subtract, etc them.  This would allow you to e.g. add a velocity vector to a position vector to come up with a new position vector!

This web page has some nice details on the maths behind vectors.

 

Position, Velocity and Acceleration

We saw that position, velocity and acceleration are really common uses of vectors.

Continue reading

Bouncing around in Javascript

This week we looked at animations, and how to make objects move in p5.js.

We covered:

  • How to animate things in p5
  • Some mouse interaction

Animation in javascript (or all programming really!) is basically changing some variables in the draw function before we actually draw the object.  If we change each variable by a little bit, it looks like smooth movements, just like a cartoon!

To save some typing, there is a video below with a quick overview of what we did:

Okay, it’s pretty simple stuff and not exactly the most exciting animation in the world, but you guys did some playing around and came up with several interesting variations and now we know how to do it, the sky is the absolute limit on what we can build  🙂 !

As usual, the code is up on the github to be pulled down and played with or changed to your heart’s content!