Bite Size C# – Generics

Generics refer to the method of creating classes and methods in a way that defers the specification of the type or types associated with the class or method until it is declared and instantiated.

What this means in plain english is that you can define a single class or method that can be utilised with multiple types, thus resulting in less and tidier code.

So let us have a look at an example. Firstly let us look at some code that is not generic. Here we have a class which consist of a list of integers, it has a default constructor as well as two methods, one to add an integer to the list and the other to return the sum of all the integers in the list.

public class KillerRoboticsIntList
{
   public List<int> IntList { get; set; }

    public KillerRoboticsIntList()
    {
        IntList = new List<int>();
    }

    public void Add(int item)
    {
        IntList.Add(item);
    }

    public int Sum()
   {
	int sum;
	foreach(int i in IntList)
	{
	 sum += i;
	}
	return sum;
   }

}

This is a very basic example and can be utilised as follows:

class Program
        {
            public static void Main()
            {
                KillerRoboticsIntList iList = new KillerRoboticsIntList();
		        iList.Add(1);
		        iList.Add(2);
		        iList.Add(3);
		        iList.Add(4);
		        int sum = iList.Sum();
                Console.WriteLine(“Sum = {0}.", sum);

            }
        }

This is very straight forward, however if I would like to use this class with a data type other than int (for example a float or a double) I would need to define a new class for each data type. This can be overcome by utilising Generics. Below is an example of how this can be implemented:

public class KillerRoboticsGenericList<T>
{
   public List GenList<T> { get; set; }

    public KillerRoboticsGenericList()
    {
        GenList = new List<T>();
    }

    public void Add(T item)
    {
        GenList.Add(item);
    }

    public T Sum()
   {
	T sum;
	foreach(T i in GenList)
	{
	 sum += i;
	}
	return sum;
   }

}

The above class can now be defined for various types as seen below:

class Program
        {
            public static void Main()
            {
              KillerRoboticsIntList<int> intList = new KillerRoboticsIntList<int>();
		        intList.Add(1);
		        intList.Add(2);
		        intList.Add(3);
		        intList.Add(4);
		        int sum = intList.Sum();
                Console.WriteLine(“Int Sum = {0}.", sum);

		        KillerRoboticsIntList<double> = new KillerRoboticsIntList<double>();
		        doubleList.Add(0.1);
		        doubleList.Add(2.2);
		        doubleList.Add(3.0);
		        doubleList.Add(1.4);
		        double dSum = doubleList.Sum();
                Console.WriteLine(“Double Sum = {0}.", dSum);

            }
        }

In some cases you might want to put a restriction on the types that can be utilised to implement a generic class of method, this can be achieved by utilising constraints. For example the class we defined above can be restricted to types that implement the IComparable interface by simple changing the first line as follows:

public class KillerRoboticsGenericList<T> where T : IComparable

Some additional examples of constraints are:

where T : Product

This restricts the type of T to an implementation of the class Product or any of its child classes.

where T : struct

This restricts the type of T to the value type struct.

where T : new()

This restricts the type of T to an object with a default constructor.

Multiple Constraints can also be appled at the same time, for example:

 
public class KillerRoboticsGenericList<T> where T : IComparable, new() 

A Generic class can be defined to utilise multiple types, for example:

 
public class KillerRoboticsGenericList<T,U,V>  

It is also worth mentioning that the default c# List class used in the above examples also utilises generics, along with all the other predefined c# collections contained in System.Collections.Generic.

I hope this post has been useful and I will be posting on some additional C# topics, such as Delegates, Lamda Expressions, LINQ, Extension Methods, etc. over the next few months.

Bite Size C# – Generics

What is the Cloud? A Layman’s Guide

The Cloud

Wikipedia defines the Cloud as “Cloud computing is a kind of Internet-based computing that provides shared processing resources and data to computers and other devices on demand”. This is a great and concise definition, but what does it really mean and how would you explain it to someone with minimal technological knowledge?

So, let us try to break it down in a way in which you can explain it to the more technologically challenged in your life.

In reality most households own multiple computers, and by computers I mean any device capable of a fair amount of processing power, this includes laptops, desktop PCs, gaming consoles, tablets and even smart phones. This is a sign of the times and it is great to have all this computing power and the potential it holds available to us, but in reality it is not very cost efficient. We all spend a lot of money on all these devices (and inherently the computing power they hold) but we only use them a fraction of the time. I know I am lucky if I get to turn on my game console for 4 hours a week, which means it sits idle and unused the remaining 164 hours of the week, resulting in a utilisation rate of just over 2%. Would it not be much more economical for a group of people to buy and share these devices thus ensuring their usage is as close to 100% as possible? This sounds like an easy question to answer, but in reality the practicalities thereof are a bit more difficult to address, issues arise regarding things like everyone getting access to the device, what happens if more than one person wants to use the device at the same time, etc. This fundamental reasoning is where the concept of the Cloud comes in.

The Cloud is a way of sharing computing power and data storage remotely over the Internet, thus resolving the issues related to physical access to the device in question. Now how does this work? Let us take data storage as an example. In the past if you wanted to store files (such as music, picture, documents or anything else really) you had to go to a shop and purchase some form of storage device, be that a USB memory stick, a hard drive, etc. You had to carry the cost of purchasing the item, but also the risk that you could lose it or it could break, which would result in the loss of your data. So you also had to get some additional storage to create a second copy, i.e. a backup, which increased the cost even more. But these days Cloud Storage solutions like Dropbox, OneDrive, Google Drive and iCloud offer a way of storing your files at a low cost and with backups and other maintenance activities and costs being taken care of by the provider, all for a small subscription fee (although all the above mentioned offer a free entry-level package and you only pay if you require additional capacity). The purchase of an ‘asset’ is thus replaced by a paid-for service. And because many people use these services, economies of scale come into play, thus everyone ends up paying less that they would have if they had gone and purchased the storage devices themselves.

Another example is the concept of Cloud Gaming. In the past if you wanted to play video games you either had to buy a gaming console or invest a fair amount of money into a gaming PC. There are now however quite a few Cloud Gaming companies (such as UGameNow, GameFly and Nvidia GeForce Now) that allow you to play video games on nothing more than a Smart TV or entry-level PC. How this is achieved is that the device used by the player simply acts as a mechanism to receive and send user input and render a video stream to display, with all the processing and intensive tasks being performed remotely on servers in the service providers’ data centres. These Cloud Gaming Companies also operate on a subscription bases, and although this industry is still in its infancy and is still experiencing numerous growing pains, it is not unreasonable to think that in the future we will no longer have to purchase specialised hardware to play video games, but will simply pay a monthly subscription fee, knowing we will never have the pains of upgrading hardware to play the latest games again.

Obviously the Cloud goes further than just individual consumer uses and spans into the space of revolutionising business information systems as well. No longer will businesses have to spend millions on buying expensive servers and building data center in isolation of one another, with enough computational and storage capacity to cater for peak usage which only occurs a fraction of the time and the majority of these computational and storage resources sitting idle the majority of the time. An example of this is a company’s payroll system which gets used 1 or 2 days a month when the employee payroll is processed and sits idle for the remainder of the month. Businesses can reap the same rewards that individual consumers can by utilising a Cloud Service, with economies of scale once again resulting in cost savings and less maintenance for the businesses who are the clients of these Cloud Services. The Cloud also offers businesses a great deal of agility in adjusting to changes in demand for processing and storage resources by providing on-demand access to a shared pool of configurable computing resources. The two main players in this space are Microsoft and Amazon, with their Microsoft Azure and Amazon Web Services offerings.

These Cloud Offerings are broken down into 3 main categories, namely Infrastructure As A Service (IaaS), Platform As A Service (PaaS) and Software As A Service (SaaS). Let us briefly have a look at each of these:

Infrastructure As A Service (IaaS) – This model involves only paying for the hardware, i.e. processing and storage utilised. All software related installations, licensing costs and maintenance remains the responsibility of the client. This process typically involves businesses migrating Virtual Machines from their on premise servers to the cloud.

Platform As A Service (PaaS) – Similarly to IaaS the client still pays for the processing and storage utilised, but now additionally for the provider to maintain all system software. This means that the client is no longer responsible for the installations, licensing costs and maintenance of system software, and these become the responsibility of the Cloud provider.

Software As A Service (SaaS) – In this case the business simply rents an application from a vendor. The maintenance and backup activities thus are the responsibility of the Cloud provider. Great examples of this is Microsoft Office 365, OneDrive, Dropbox and iCloud. Even Netflix operates on this model.

Businesses can choose one of the following options for their Cloud configuration:

Public Cloud – In this configuration the business will utilise computer resources and storage shared in the public cloud, by multiple companies and individuals.

Private Cloud – This is when the business makes use of cloud infrastructure operated only for them and the computer resources and storage are only shared by divisions from within the business itself. This cloud Infrastructure can be managed internally by the company or externally by a service provider.

Hybrid Cloud – When utilising a combination of the Cloud and traditionally on premise data center it is referred to as a hybrid cloud configuration.

One major requirement for the utilisation of the Cloud and reaping the benefits thereof by either businesses or by individual consumers is the presence of a reliable high-speed internet connection, which is not a problem in most first world countries, however in the developing world this is not always available. This can result in a compounded negative economic impact on these countries who then become even more uncompetitive compared to their first world counterparts.

One question I get asked more than any other is whether the Cloud is secure? And the answer is, as long as good security practices are followed (like not sticking your password on a post-it note on your screen etc.), that it is as secure as any other computer resource and quite often due to the increased focus on security in the cloud it might even be more secure. I also get asked whether other people will be able to see your files as the files are stored on shared resources, the answer to this is no. Although the files might be stored on a shared storage resource there are various layers of security technologies in play to prevent unauthorised access to individuals and companies’ files in the cloud.

This concept of sharing the cost of an underlying infrastructure so that everyone can benefit from the service thereof is not a new concept (think of public libraries, gyms or even the electricity generation and distribution infrastructure) but it is becoming ever more prevalent as an increased emphasis is being placed on the service being rendered as opposed to owning the item that renders that service. Even companies like Uber are built on this model as well as the planned Tesla car share initiative, and in the future we will see many more companies and offerings that follow this mindset.

What is the Cloud? A Layman’s Guide

SunFounder DIY 4-DOF Sloth Robot Kit

Today we will have a look at a robot kit created by SunFounder. The Sloth is a bi-pedal robot based on the Arduino Nano. It utilises an ultrasonic module for obstacle detection and four servos for movement.

I found the kit to be an easy and fun build that took approximately an hour to complete. SunFounder have uploaded a YouTube video that serves as detailed introductions and assembly tutorial for the robot. It covers the entire assembly process, including the process to test the ultrasonic module as well as all the servos (before assembly), which is a good thing as one of the servos included with my kit turned out to be broken, but luckily I had a replacement servo on hand.

One thing to note is that the robot utilises two 18650 batteries, which after some research turned out to be commonly used in high-end flashlights and e-cigarettes, and are relatively pricey.

The robot can also be powered through the mini USB port on the Arduino (which I did while I waited for the batteries I had ordered to be delivered).

The code for the robot can be downloaded from here on the SunFounder website. Just note that the default code did not work for me as the ultrasound module did not detect obstacles. I rectified this by replacing the following code:

void loop()
{
 	int <span class="mceItemHidden" data-mce-bogus="1"><span class="hiddenSpellError" pre="int " data-mce-bogus="1">tooclose</span></span> = 0; // Define the test times, the initial value is 0
 	for(int a=0; a&lt;5; a++)  //for is a cyclical function and its cyclic times are determined by the second condition in the bracket. Here a&lt;5, a’s initial value is 0. When a&lt;5, run the program in the bracket. After running, a becomes a++ and it means adding 1 to a’s value.
	{
		delay(50); // Delay 50ms
		int din = sonar.ping_in(); // Call the ultrasonic transducer to read the distance that ultrasonic detected.
		if (din &lt; 7 &amp;&amp; din &gt; 0) tooclose++; // The smoothing. The times add 1 when the detect distance less than 7cm and greater than 0cm.
	}

With this:

void loop()
{
	int <span class="mceItemHidden" data-mce-bogus="1"><span class="hiddenSpellError" pre="int " data-mce-bogus="1">tooclose</span></span> = 0; // Define the test times, the initial value is 0
	for(int a=0; a&lt;5; a++)  //for is a cyclical function and its cyclic times are determined by the second condition in the bracket. Here a&lt;5, a’s initial value is 0. When a&lt;5, run the program in the bracket. After running, a becomes a++ and it means adding 1 to a’s value.
	{
		delay(50); // Delay 50ms
		int din = sonar.ping(); // Call the ultrasonic transducer to read the distance that ultrasonic detected.
		if (din &lt; 750 &amp;&amp; din &gt; 0) tooclose++;
	}

I really enjoyed assembling and playing with this little robot and would definitely recommend it to anyone interested in getting started in basic robotics.

SunFounder DIY 4-DOF Sloth Robot Kit

The Legend of Zelda Breath of the Wild


abloggersjourney

This post forms part of a series covering the entire Legend of Zelda franchise hosted by NekoJonez , so if you love the Legend of Zelda as much as I do, browse over to this hub article on his blog, which contains links to article (like this one) on each Legend of Zelda game in the series created by a variety of different bloggers.

The legend of Zelda series is one of my favorite gaming series, as can be seen by the numerous Legend of Zelda items in my gaming collection.

So to say that I was eagerly awaiting the release of Breath of the Wild earlier this year is an understatement of note, so was it worth the wait? Did it live up to the hype? Lets find out.

BOTW_WiiU

The Legend of Zelda Breath of the Wild is the latest, and in my opinion greatest, adventure in the Legend of Zelda series. It released in March 2017 (Nearly 6 years after Skyward Sword, the last major console Legend of Zelda game released) on the WiiU and Nintendo Switch and received almost unanimous perfect review scores (With a current Metacritic score of 97%).

The Legend of Zelda games have always been open world to some extent, but Breath of the Wild not only truly introduced the Zelda series to a fully realized open world, but also changed the way that we will look at all other open world games going forward, revitalizing the open world genre as a whole. Unlike many other open world games, where the world seems lifeless and repetitive, Breath of the Wild managed to create a representation of Hyrule that seems alive, dynamic and real.

The amount of freedom the game allows is also truly amazing, and any situation the game presents can be approached from various different ways. This combined with an amazing physics engine fully releases the player’s imagination in a sandbox of almost endless possibilities. Some examples of this is how bombs can be used to kill fish in ponds which can then be easily collected, or how the player can “cheat” in the motion controlled ball and maze puzzle shrines by simply flipping the control pad upside down and using the flat back of the maze to easily guide the ball to the target, or realizing that any metal item can conduct electricity and then using spare weapons and armor to solve electricity puzzles, or how an enemy encampment can be destroyed by using the wind and a patch of dry grass to start a wild-fire to burn it to a crisp, or how a wooden shield can be used to catch and collect enemy arrows fired at you . These are but a few of many examples.

Breath of the Wild is not an easy game, but you never feel that it is unfair. Breath of the Wild harks back to a time in gaming when games actually presented a genuine challenge. This is very apparent in Breath of the Wild in how even from very early in the game you are free to go to areas where very high level and dangerous enemies reside, which in the beginning you are very unlikely to defeat. But as you gain more health and stamina, get better weapons and armor and also get better at the game you will later be able to defeat those same enemies much more easily. For example, the first time I encountered a Stone Talus it was a long and grueling fight, which I only beat after numerous attempts, but after I upgraded my armor and weapons and also learned to better utilize my ranged attacks and dodging, I can now take down a Stone Talus without much effort.

The different regions in the game world vary greatly in look and feel, from the grassy plains of the Great Plateau, to the fiery Death Mountain, to the water rich Zora’s Domain, to the sandy desert of the Gerudo Wasteland. All the regions are beautifully bought to life, each with its own inhabitants, sub-quests and story arcs. All of these regions also contain villages, all unique and wonderful to explore.

Another great feature in the game is that you can buy a house, and make various upgrades to it. This provides a handy place to store items you have collected, freeing up some valuable inventory space.

One of my favorite things to do in Breath of the Wild is to go out in the world and scavenge for useful items, chopping down trees for wood, mining minerals with my hammer, hunting a variety of animals for meat or simply picking fruits, vegetables and mushrooms to use in recipes.

Crafting is done in Breath of the Wild through its cooking system. Various recipes can be discovered, through experimentation, to create a variety of potions and food items offering not only health restoration but also a wide range of temporary upgrades to attributes like stamina and sneaking.

After everything we have covered and we haven’t even touched on a major element of the game, the dungeons. Dungeons come in two varieties, firstly shrines, which are mini dungeons in which you unlock abilities and spirit orbs (which are used to upgrade health and stamina) and then the five main dungeons. The five main dungeons consist of the four Divine Beats and finally Hyrule Castle. All five main dungeons end with a boss encounter with an embodiment of Ganon. These dungeons offer a wide variety of challenges, from truly impressive puzzles to powerful enemies, and finishing one gives you a real sense of achievement.

If you haven’t realized this yet, I truly love this game and it is easily in my top three favorite games of all time, and is definitely my favorite Legend of Zelda game.

I enjoyed every second of this game and even after spending far over a hundred hours playing, I still feel that there are things left to discover.

Quite often when a game gets huge amounts of hype and amazing reviews it ends up being a disappointment as expectations are built too high and it fails to live up to them, but this is not the case with Breath of the Wild. This game not only lives up to the hype but also exceeds it.

The Legend of Zelda Breath of the Wild

Book Review – The Maker Movement Manifesto by Mark Hatch

makerM.png

The Maker Movement Manifesto is an interesting look into the Maker Movement by Mark Hatch, the CEO and cofounder of TechShop a popular maker space.

It starts out by defining the Maker Movement Manifesto which is broken down into 9 points:

  • Make
  • Share
  • Give
  • Learn
  • Tool up
  • Play
  • Participate
  • Support
  • Change

This is interesting and explains everything from the values underlying the movement to how to set up a maker space in your own community, however what was of more interest to myself was the following sections where numerous stories were relaid about success stories of makers developing their passions into successful businesses from within TechShop.

The book covers not only the Maker Movement from an internal perspective, but also the far wider reaching socio-economic impacts of giving anyone access to the tools, knowledge and abilities to make things for themselves, be that anything from a proof of concept to a product to art. It looks at how this wider access to these facilities accelerates innovation, democratizes tools/equipment and information and creates a new breed of person, what is referred to as a pro-am, a professional amateur. And how this mindset change might be better suited to addressing the challenges the world is experiencing today.

I really enjoyed The Maker Movement Manifesto, and found it to be inspiring, it really got my Maker juices flowing. So if you are a Maker or interested in the Movement give this book a try.

Book Review – The Maker Movement Manifesto by Mark Hatch

A Story About A Game

15 Years ago I wrote a small game called Hellspawn and I rediscovered it again when I was going through some old backup discs. It is a top down shooter and was developed in Borland C++ Builder (I think version 6). It was a very basic game (especially looking back now) from when I was still a very inexperienced developer, still studying to get a degree.

So if anyone is interested here it is: HellSpawn

To get it working on windows 10:

Use Hellspawn.exe to start the game, but first in file properties:

  • Set executable to run in compatibility mode  – Windows 98 / Windows ME
  • Reduced Color mode – 16-bit
  • Override DPI Scaling Behavior, Scaling performed by – Application
  • Can also set to run in 640 x 480, however is best to change screen resolution in windows to 1024 x 768 for best experience.

compatibility

The controls are as follows:

  • Arrow keys to move
  • Left ctrl keys to fire weapon

Simply kill all the enemies to proceed to the next level.

On another note I have some Steam game keys to give away!

For a chance to win one simply email killerrobotics.me@gmail.com with the subject line ‘Killer Robotics Steam Giveaway’ and for the message content just be creative.

Winners will be randomly selected and announced via twitter.

A Story About A Game