Creators – Pattern

washer-machine-porous-mechanical-83852

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]
];

Screenshot 2018-10-15 at 18.14.34

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.

Download

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

Explorers Week 5 – Help Bo Peep find her sheep

Hi everyone,

Thanks for coming Saturday even though the weather was dreadful.

This week, I helped Bo Peep found her sheep! Some of you did the same and some used ideas like Minecraft Steve finding Iron Ore and Diamonds, Knights finding dragons or a Princess finding flowers.

Before we even started our game this week we talked a little bit about File Management and about the importance of keeping your files somewhere you can access them quickly and giving them a meaningful name.

So to this end, we all created a folder where we will be keeping our files in the future and within that we had a sub folder for this weeks files.

We started our game by drawing our background on our stage:

Unfortunately, due to internet problems we could not search the internet for images for our Sprites, but we could still use the sprites from the Scratch Library.

This week, we decided to move our main sprite using the arrow keys. For this we had to learn a small bit about the X and Y axis and I gave you a little tip on how to remember which is which!

Hope you all enjoyed this week, aee you next week when we will be starting a new game!

Here are the notes for this weeks session in PDF CDA-S7-Week_05-BoBeep.pdf

Martha

Julie, Ruaidhrí and Eoin

 

Week 5 2018 Explorers – How fast can you type?

Hi everyone,

Thank you all for coming on Saturday. I hope you liked the short video of the SpaceX Falcon Heavy Test Launch and the Intel Light Drones from the opening Ceremony of the Winter Olympics.

This week we did a new game, How fast can you Type? Last week we used Sprites as backgrounds and this week we used Backgrounds as Sprites. Just to mix it up!

We used a variable as our Timer, our first time doing this, don’t forget if you want the time to start when you press the first letter rather than when the green flag is clicked then you are going to have to add another broadcast.

We are off for the next two weeks, to cover the school mid term break and also as Confirmation for all the Athenry Schools takes place on the 24th of February and there will be many families attending this from Coderdojo Athenry. Best wishes to any of our Ninjas and families who are being confirmed.

Hope you all have a great break and hope to see you all back on the 3rd of March

Explorers – Week 5 – Guessing Game

Hi everyone,

Well! didn’t we have a very studious bunch of Ninjas last week, all very focused on our new game. Last Saturday we did a slightly different game to usual., There was no movement, no sensing when something happened. It was a Maths Game, a guessing game where the computer picks a random number and we had to guess the number.

We had to first make sure that a random number was picked using an Operator. Previously we have used a Variable to store a Score or Lives, but this time it was storing the random number and our guesses. Leaving them on screen as we were testing allowed us to understand more about the variable and what it does…it also made the testing a little easier.

Depending how any guesses we were given we repeated our code that number of times. As well as having to make decisions, i.e If_then, we also had to do a comparison before making the decision, to determine whether the guess was correct, too low or too high.

5guesess

I hope you all enjoyed the difference this week and we are going try something else different next week. We  (You)  are going to create a Animated Halloween Scene. Get your Thinking Hats On!

Here are this weeks notes in PDF: CDA-S6-Week_05-GuessNumbers.pdf

Creators – Getting User Input

This week we worked on getting input from the user and making the game react to it.

InputManager

Unity has a build in system for handling user input. The InputManager can be found under the Edit|Project Settings|Input menu:

Screen Shot 2016-10-17 at 21.21.01.png

The Unity input system is based on the concept of “axes”. The game request if there is input on a specific axis, giving the axis name. What that means in terms of button presses, mouse or controller input depends on the settings in the InputManager. Axes have a value that ranges from -1.0f (full negative, if negative values are allowed) through 0.0f (no input) to 1.0f (full positive).

inputaxes

Pre-defined Input Axes

While the game programmer can define as many input axes themselves as they like, Unity come with many common ones built-in. The first two shown above, called “Horizontal” and “Vertical” are commonly used for movement. The third “Fire1” is usually used for shooting.

We redefined “Fire1” from it’s default key (Left Ctrl) to bind it to the space key instead.

screen-shot-2016-10-17-at-21-36-26

Updating the Code to Detect “Fire1”

We originally had a force applied to our ball in the “PushSphere” script as soon as the game started. We modified the code so that in the Start() method all we did was to retrieve and store the Rigidbody component. In the Update() method (called every time the game draws) we ask if there’s been any input on “Fire1” and only if there has, do we apply a force to the ball:

 using UnityEngine;
 using System.Collections;
 
 public class PushSphere : MonoBehaviour 
 {
   public float PushStrength = 1.0f;
   private Rigidbody rb;
 
   // Use this for initialization
   void Start ()
   {
     rb = GetComponent<Rigidbody> ();
   }
   
   // Update is called once per frame
   void Update () 
   {
     float fire = Input.GetAxis ("Fire1"); 
 
     if (fire > 0.0f)
     {
       rb.AddForce (Vector3.back * PushStrength);
     }
   }
 }

Before proceeding, we ran our game and tested to ensure it  was working correctly.

Moving Our Aimer

The aimer was rotated using input from the horizontal axis. We added a script called AimerController to our Aimer game object. A public property called RotateSpeed gives us a way to tune the speed our our aimer. We don’t need anything in the Start() method, and it’s been removed here for clarity. The Update() method looks for input on the “Horizontal” axis (which maps to the left and right keys) and applies a rotation to the Aimer’s transform using the following logic:

amount to rotate = speed of rotation * user input * time

User input here will either be -1.0f, 0.0f or 0.0f. This equates to rotate in a negative direction (anti-clockwise), don’t rotate or rotate in a positive direction (clockwise).

 using UnityEngine;
 using System.Collections;
 
 public class AimerController : MonoBehaviour {
 
   public float RotateSpeed = 1.0f;
    
   // Update is called once per frame 
   void Update () {
     float horiz = Input.GetAxis("Horizontal");
 
     transform.RotateAround (transform.position, Vector3.up, 
                             RotateSpeed * horiz * Time.deltaTime);
   }
 }

Note that we’re rotating about the vertical axis and the rotation is centred around the aimer’s position.

Linking the Aimer and the Sphere’s Direction of Fire

To link the aimer’s with the sphere’s direction of fire, we needed to provide the sphere with a new public property which could store a reference to the Aimer’s game object:

public GameObject Aimer;

We then simply had to update the AddForce call, in the Update() method, to take the aimer’s direction into account:

 rb.AddForce (Aimer.transform.forward * -1.0f * PushStrength);

Note that we had to also multiply by -1.0f as the ball was initially going opposite to the direction we wanted.

Prefabs

Prefabs are objects, or collections of objects that we want to re-use multiple times. To create a prefab, all we need to do is to drag an object from the Hierarchy to a project folder. We made a prefab of our pin by doing this. Note that prefabs show up blue in the hierarchy to mark them out. When the prefab is changed, all copies of it in the hierarchy are updated as well.

Automatic Creation of Game Objects at Run-Time

Once we created our pin prefab, we worked on adding pins automatically into the game a run-time.

We added a new empty game object and named it PinManager, we then added a component to it of the same name. This script was given a public property, of type GameObject, to store a reference to the prefab. In the Start() method, we use two loops to place nine pins automatically into the scene, using the Instantiate() method:

 using UnityEngine;
 using System.Collections;
 
 public class PinManager : MonoBehaviour 
 {
   public GameObject PinPrefab;
 
   // Use this for initialization
   void Start () 
   {
     for (int x = -1; x <= 1; x++)
     {
       for (int z = -2; z <= 0; z++)
       {
         Vector3 pos = new Vector3(x * 2, 0.5f, z * 2);
 
         Instantiate (PinPrefab, pos, Quaternion.identity);
       }
     }
   }
 }

Note that there are several versions of the Instantiate() method. The version we’re using allows us to specify the position and rotation of the newly created object. A Quaternion is variable type that can store a rotation. Quaternion.identity simply means “no rotation”.

Testing

Project File

The latest project files can be downloaded from here.

Scratch Beginners Week 5 – Paddle Ball Game

We had another week of fantastic attendance at Coder Dojo Athenry Beginners Scratch session. Thanks all for coming. To see the PDF of this weeks notes click here: CDA-S5-Challenge_05_Paddle_Ball. This week we reiterated a lot of the basic programming ideas that we have been working on since September. We planned our game – Paddle Ball – by defining it’s rules and designing it’s look. The coders were invited to use whatever sprites they liked-some had dragons catching swords and others trampolines catching kids! Most stuck to the basic layout seen here:

Season 5 Paddle ball - game design

First, we designed the paddle and made it follow our mouse, but only in the x-direction.

CDA-S5-Challenge_05_Paddle_Ball_move paddle

Secondly, we drew or imported the ball from our library and caused it to fall. We had to set it’s initial position just after the green flag was pressed in order that the game would restart properly each time and we had to set it’s initial direction to down, otherwise the ball might just bounce from side to side instead of up and down!! In order to do this, we placed a ‘point in direction’ block under the ‘go to’ block in the image below and set it to 180 (or down).

CDA-S5-Challenge_05_Paddle_Ball_make ball fall

Now that we have each sprite moving, we must get them to respond to touching each other and get a score variable set up. When the ball hits the paddle, the ball will broadcast a message to the program and the ball will change the score by 1.

CDA-S5-Challenge_05_Paddle_Ball_ball hit paddleCDA-S5-Challenge_05_Paddle_Ball_bc change score

To end our program I decided that when the ball hit a line I drew at the bottom of the STAGE. The command of ‘wait until’ was used with ‘touching colour’ to ‘stop all’. The coders were encouraged to continue the game instead by setting up a ‘lives’ variable and merely subtracting from that variable when the ball touches the line and ending the game when ‘lives = 0’.

CDA-S5-Challenge_05_Paddle_Ball_end gameNext week we will quickly re-make the basic paddle ball game but add a twist to it by making blocks that disappear when hit and add to the user’s score. It is based on the old Breakout game. The following week we will be doing animation. I will be bringing some plasticine to use to make sprites but the coders are welcome to bring miniature figurines such as Polly pockets or lego, etc… All parents should come equipped with a phone/camera and download cables that can take pictures to record the action! This will take several weeks to complete.

Thanks to Martha Fahy for the fantastic game idea and notes!

Julie

 

Week 5 – Unity

UnityLogo

This week we returned to the Roll-A-Ball game that we had shown in the introductory session. Because people were at different levels of completion with this, we started from the beginning again, but we put some detail around things that we’d glossed over the first time around.

Concept of Classes

A class is a programming concept that allows you to define objects which contain both Properties and Methods. Properties are what they sound like; a value associated with object that we can get or set. Methods are actions, in the form of a function, that we can ask the object to perform.

SampleObject

If you think of yourself as a Person object then you could imagine some of the Properties and Methods you might have.

For Properties you might have things like NameAge, HeightWeight, etc. An example of a Method you might have could be SayHi() [notice the round brackets after the name marking this as a method]. That would make you say “Hi!”. A method might have arguments, so it could be SayHiTo(“Dave”) which would make you say “Hi Dave!”.

A method could equally calculate a value. An example might be CalculateBMI() which would calculate your Body Mass Index (BMI) value based on your Height and Weight properties.

Another nice thing about classes are that we can create specialised versions of them. They get all the Properties and Methods of the base class, plus all the new Properties and Methods that we defined for the derived ones. In this example, we might want to declare SchoolChild and Worker as new classes, both based on Person. SchoolChild might have additional properties such as School and Class while Worker would have WorkPlace and JobTitle. They would still share Name/Age/Height/Weight, etc.

Classes in Unity

Unity has a base class called MonoBehaviour and when we define behaviour for a game object, we do this by deriving a specialised class of our own design based on MonoBehaviour.

There are four Methods that MonoBehaviour has that we have looked at so far:

  • Start()
  • Update()
  • FixedUpdate()
  • LateUpdate()

We have provided custom versions of these in our own classes to define the behaviour that we want. This behaviour is also known as “overriding” as we are overriding the base behaviour of these Methods (which is to do nothing).

  • Start() is called when our game object is created. We can so things here that we need to do once when the game object is created.
  • Update() is called every time the scene is drawn. It’s a good place to do any updates that impact how the scene looks. However, it’s not called at a constant rate and that makes it unsuitable for some jobs.
  • FixedUpdate() is called every time the internal game timer for physics calculations fires. This is guaranteed to be at a regular interval. Any physics based calculations where time is a component should therefore should be done within FixedUpdate() rather than Update().
  • LateUpdate() is called after all game objects have had their Update() functions called. Use this when we need to be sure that another object has definitely been updated before we do something based on that object’s Properties.

Vectors & Physics

If I tell you that someone is moving at 5kph and ask you were they’ll be in 10mins, you won’t be able to answer that question. If I tell you that they’re moving 5kph due North, then you will. That combination of a quantity and a direction is called a vector.

vectors_basicA vector in 3D space is usually represented as three numbers, written as (X, Y, Z). Let’s see what the vector (1, 2, 3) looks like.

We’re familiar enough with using vectors like this to indicate a position, but what about representing a velocity or a force? The direction is apparent, but what about the quantity? Well the quantity is simply the length of the vector. This is calculated using Pythagoras’ theorem:

distanceeq3

So we can calculate the quantity or magnitude of the vector (1, 2, 3) as approximately 3.74.

Note too that if our vector (1, 2, 3) represents a force then a vector (2, 4, 6) also representing a force, would be a force in the same direction but twice as strong. You can see that each part of the vector has simply been multiplied by two.

Basic Structure of a C# File

When we derive custom behaviours for our game objects, Unity is kind enough to provide us with a basic file containing a class definition containing empty methods for Start() and Update()monobehaviour

It’s tricky making the transition from a visual language like Scratch to a language like C# where you have to type code. A few simple rules may help:

  • Lines starting in two forward slashes (//) are comment lines. They have no effect on the program; they’re there for you to read. You can delete or change them as you need.
  • Semicolons (a dot over a comma) mark the end of statements. They’re easy to forget at first so you need to be careful.
  • You need spaces and newlines to separate things, but this does not have to be precise. Two spaces are equivalent to one. Because a statement doesn’t end until a semicolon, you can split if across several lines and it will still be fine. Hard to read though.
  • Braces (or curly brackets) enclose things and they must always be in pairs (open/close). In the sample code the braces are such that the methods Start() and Update() are inside of (and belong to) the class NewBehaviourScript because they are inside its braces. Similarly any lines we add inside Start() will belong to that method because they are inside its braces.
  • Neat formatting really helps keep your code readable and helps you quickly find mistakes. Try to mimic how code is formatted in the examples, especially the practice of “indenting” lines; placing spaces at the start of the line to make it clear what it is inside of.

Next Week

Next week we will continue to develop Roll-A-Ball and hopefully get it finished up.

Taster Session Week 4 – Unity 3D

UnityLogo

For our fourth taster session, on next Saturday 17th October, we’ll be giving an introduction to Unity. Unity is a cross-platform game engine which has been used to create many successful games.

In preparation for next week please:

  1. Go to the unity website: www.unity3D.com
  2. Click the “Get Unity 5” button
  3. Download and install the free “Personal Edition”
  4. Run Unity once and register an account – you will need your email address

We will be trying to build as much as possible of the “Roll-a-ball” demo that I showed in our introductory session. Ongoing participation in the Unity group will require a good understanding of advanced programming concepts, but for the taster session, we will try to keep that stuff to a minimum so everyone can follow along and have fun.

unityssample

Python Games – Weeks 5-6: Getting started with Pygame

Last week we relocated to NUIG for a Massive Open Dojo Session. There was lots going on to enjoy and it was great to see such a large turn out. Well done to our own Michael Madden and to Karl Sweeney from CoderDojo Galway City for organizing it all. Thanks also to Martha for the t-shirts.

The ninjas from the Python Games group who attended didn’t do any new coding but they enjoyed personalizing the Bunnies And Badgers game with their own images. We were set a challenge to create a game to highlight the environmental issues facing the oceans. We started working on that today and we will continue with that for a few weeks. Ocean Cleaner

Before we started working on that today we had a look at some basic Python concepts contained in this demo program. Next week we will look at using lists and for loops in Pygame and at collision detection.

Here are my slides from today python session_6

Week 5 – Scratch Beginners – Paddle & Ball

Hello everyone

We had a great crowd again on Saturday and had some new registrations as well. Hope you enjoyed your first week at CoderDojo Athenry.

This week I wanted you to design how your game looked. I kept my game very simple, just a paddle and a ball but you all had great ideas.

paddle

yourgame

I always mention that there is no right way or wrong way to do things. This week we used Broadcasting to send a message when something happened rather than using some of our senseing code to figure out when it happens.

BROADCAST

Here are last weeks notes in PDF CDA-S4-Week_05_Paddle_Ball.pdf

See you next week