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

Scratch Advanced – Week 5 – Cracking the Caesar Cipther

This week we began the task of cracking the following codeed message.

XUFHJ YMJ KNSFQ KWTSYNJW. YMJXJ FWJ YMJ ATDFLJX TK YMJ XYFWXMNU JSYJWUWNXJ. NYX HTSYNSZNSL RNXXNTS YT JCUQTWJ XYWFSLJ SJB BTWQIX, YT XJJP TZY SJB QNKJ FSI SJB HNANQNEFYNTSX, YT GTQIQD LT BMJWJ ST TSJ MFX LTSJ GJKTWJ.

All we know is this message is written in English. To crack this code we will use some common features of the English language.

  1. In the coded mesage look for single letter words. These words probably map to a or I
  2. In the coded message look for the most common three letter words. These words are the, and
  3. in the coded message look at the spelling of any other small word to see if we can figure out their original form.

How to crack Ceasar Cipher

The following link was the hand out provided to everyone. Each person used this handout to work through each stage of the decryption.

Can you decrypt this message (pupils notes)

The teachers handouts is available at the following link. This handout provides detailed steps of how to work through decrypting the message.

Can you decrypt this message (teachers notes)

Scratch Beginners – Week 5. Building on what we learned & adding a pinch of imagination!

In this weeks Session, I tried to continue using everything we have learned so far, and also showed some alternative code for code we have used previously. As I always say, there is always more than one way to do something.

AXISBROADCAST

Today, I also wanted you to create your own game, using the code I would be showing you but each persons game was to look different. As always, your minds are much more artistic and entertaining than mine and I saw some fantastic ideas around the room.

IDEAS

If you get  a chance during your busy week, you should go back over your first couple of games and see can you add some more complexity to them. Add a score or a level, or can you use broadcasting to communicate between the sprites.

But above all…have fun with it!

Here are the full notes in PDF form of todays session. CDA-S3-Challenge05Paddle_Ball.PDF

ModderDojo Week 5: Continuing to Build Complex Structure Mods in Minecraft

2013-11-10_10.45.39

This week, we continued to work on our structure mods in ScriptCraftJS. Our plan is to build a whole set of mods that between them can be used to create a town/city.

Meanwhile, Eli in the group is working on Java-based modding and will help everyone else get started with it when we all move onto that topic later.

Some of the structures people in the group are working on:

  • A block of apartments
  • A street with skyscrapers
  • A castle
  • An iron house
  • A stable
  • A tennis court / soccer pitch
  • A subway
  • A giant face!

The picture with this week’s post shows a Wizard’s Tower built by Conor in the ModderDojo group.

Along the way, we will get practice of:

  • Turning ideas into designs and turning designs into code
  • Debugging programs when the result doesn’t match the design
  • Using variables, calculations, decisions and loops
  • Sharing code for others to download and reuse

Practical notes:

  • During development and testing, you can end up with lots of incomplete structures that slow down your CraftBukkit server. A simple fix is to delete your world:
    • Stop your CraftBukkit server
    • Open the CraftBukkit folder on your computer: in it you will see folders called world and possibly world_nether and world_the_end delete them all
    • While you are at it, edit server.properties in the CraftBukkit folder to make your new world superflat, write level-type=flat and you could also change other properties such as spawn-monsters=false
    • Restart your CraftBukkit folder to create a new, empty world
    • Re-run your scripts to recreate structures that you want
  • Read the ScriptCraftJS API reference to see what commands you can use for your structures: https://github.com/walterhiggins/ScriptCraft/blob/master/docs/api.md

Our Mods:

We have started to post mods here: https://cdathenry.wordpress.com/2013/11/10/modderdojo-athenry-our-scriptcraftjs-minecraft-mods/

We will add more as our modders finish them and make them available for posting. Stay tuned!